### Build and Install Packaide
Source: https://github.com/danielliamanderson/packaide/blob/master/README.md
Minimal commands to build the library from source on a Nix system using CMake and Make.
```bash
mkdir build && cd build
cmake ..
make
```
--------------------------------
### Install Python Library via setup.py
Source: https://github.com/danielliamanderson/packaide/blob/master/python/CMakeLists.txt
This snippet defines an installation target that executes the setup.py script using the found Python interpreter.
```cmake
# Add an installation target for the Python library
set(SETUP_PY "${CMAKE_CURRENT_SOURCE_DIR}/setup.py")
install(CODE "execute_process(
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMAND ${Python3_EXECUTABLE} ${SETUP_PY} install)
")
```
--------------------------------
### Perform 2D Nesting with Packaide
Source: https://github.com/danielliamanderson/packaide/blob/master/README.md
Example demonstrating how to define shapes and sheets as SVG strings and invoke the packaide.pack function.
```python
# Example usage of Packaide
import packaide
# Shapes are provided in SVG format
shapes = """
"""
# The target sheet / material is also represented as an SVG
# document. Shapes given on the sheet are interpreted as
# holes that must be avoided when placing new parts. In this
# case, a square in the upper-left-hand corner.
sheet = """
"""
# Attempts to pack as many of the parts as possible.
result, placed, fails = packaide.pack(
[sheet], # A list of sheets (SVG documents)
shapes, # An SVG document containing the parts
tolerance = 2.5, # Discretization tolerance
offset = 5, # The offset distance around each shape (dilation)
partial_solution = True, # Whether to return a partial solution
rotations = 1, # The number of rotations of parts to try
persist = True # Cache results to speed up next run
)
# If partial_solution was False, then either every part is placed or none
# are. Otherwise, as many as possible are placed. placed and fails denote
# the number of parts that could be and could not be placed respectively
print("{} parts were placed. {} parts could not fit on the sheets".format(placed, fails))
# The results are given by a list of pairs (i, out), where
# i is the index of the sheet on which shapes were packed, and
# out is an SVG representation of the parts that are to be
```
--------------------------------
### Include Python Library Installation Subdirectory
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Includes the 'python' subdirectory, which is responsible for handling the installation of Python-related components of the project. This typically involves packaging and installing Python modules.
```cmake
add_subdirectory(python)
```
--------------------------------
### Rotation Optimization for Packing
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Compares packing results with and without rotation optimization. This example uses long, thin rectangles and tests packing with 4 rotations versus a single rotation to demonstrate improved arrangements.
```python
import packaide
sheets = [packaide.blank_sheet(100, 50)]
# Long thin rectangles that might pack better when rotated
shapes = """
"
# Try 4 rotations: 0°, 90°, 180°, 270°
result, placed, fails = packaide.pack(
sheets,
shapes,
tolerance=1,
offset=2,
partial_solution=True,
rotations=4, # Try 4 evenly spaced rotations
persist=False
)
print(f"With 4 rotations: placed {placed}, failed {fails}")
# Compare with no rotation
result2, placed2, fails2 = packaide.pack(
sheets,
shapes,
tolerance=1,
offset=2,
partial_solution=True,
rotations=1, # No rotation, original orientation only
persist=False
)
print(f"With 1 rotation: placed {placed2}, failed {fails2}")
```
--------------------------------
### Part-in-Part Nesting with Packaide
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Illustrates how Packaide can pack smaller shapes into the holes of larger shapes. This example defines a shape with a cutout and a small shape to be nested, maximizing material utilization. Ensure the 'packaide' library is imported.
```python
import packaide
# Create a blank sheet
sheets = [packaide.blank_sheet(50, 50)]
# Define a shape with a hole (outer rect with inner cutout) and a small shape
# Path uses M (moveto) L (lineto) Z (close) commands
# First path: 30x30 outer square with 20x20 inner hole
# Second shape: small 5x5 square that fits in the hole
shapes = """
"
result, placed, fails = packaide.pack(
sheets,
shapes,
tolerance=0.5,
offset=1,
partial_solution=False,
rotations=1,
persist=False
)
# Both shapes should be placed - small rect inside the hole
print(f"Placed {placed} shapes (small shape nested inside hole)")
```
--------------------------------
### Set Minimum CMake Version and Project Details
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Specifies the minimum required CMake version and defines project metadata such as name, version, description, and supported languages. Ensure your CMake installation meets the version requirement.
```cmake
cmake_minimum_required(VERSION 3.13)
project(Packaide VERSION 1.0
DESCRIPTION "Fast and robust 2D nesting"
LANGUAGES CXX)
```
--------------------------------
### Create 'check-installed' Target
Source: https://github.com/danielliamanderson/packaide/blob/master/test/CMakeLists.txt
Defines a custom target 'check-installed' that runs all tests using CTest without loading source libraries. This verifies the installed version of the library.
```cmake
# Create a target that runs all of the tests via CTest without
# loading the source libraries. This will ensure that the libraries
# are installed somewhere visible to Python
add_custom_target(check-installed
${CMAKE_CTEST_COMMAND} --no-tests=error --output-on-failure
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
add_dependencies(check PackaideBindings)
```
--------------------------------
### Configure Packaide Python Bindings with CMake
Source: https://github.com/danielliamanderson/packaide/blob/master/src/CMakeLists.txt
Use this configuration to locate dependencies, define the shared library target, and set installation paths for Python bindings. Note that library names for Boost and Python may vary by operating system and require manual adjustment.
```cmake
find_package(Python3 REQUIRED)
find_package(PythonLibs REQUIRED)
find_package(Boost REQUIRED COMPONENTS system python)
# Use correct extension on Apple
if(APPLE)
set(CMAKE_SHARED_LIBRARY_SUFFIX ".so")
endif(APPLE)
# Configure the target for the bindings library
add_library(PackaideBindings SHARED bindings.cpp)
target_include_directories(PackaideBindings PRIVATE ${PROJECT_SOURCE_DIR}/include ${PYTHON_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS})
target_link_libraries(PackaideBindings ${PYTHON_LIBRARIES} ${Boost_LIBRARIES} PackaideLib)
target_compile_options(PackaideBindings PRIVATE -Wfatal-errors)
# Configure installation. We opt to install into the Python packages
# directory rather than the system library directory, for consistency
# with the Python part of the library
set_target_properties(PackaideBindings PROPERTIES PREFIX "")
install(TARGETS PackaideBindings DESTINATION "${Python3_SITELIB}")
```
--------------------------------
### Locate Python Interpreter in CMake
Source: https://github.com/danielliamanderson/packaide/blob/master/python/CMakeLists.txt
Use this command to ensure the Python interpreter is available before attempting to run installation scripts.
```cmake
find_package(Python3 REQUIRED COMPONENTS Interpreter)
```
--------------------------------
### Run Benchmarks with Make
Source: https://github.com/danielliamanderson/packaide/blob/master/README.md
Executes the library's performance benchmarks using the 'make benchmarks' command. The 'make plots' command generates visualizations from the benchmark results.
```bash
make benchmarks
```
```bash
make plots
```
--------------------------------
### Display General Configuration Information
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Outputs various build configuration details to the console during the CMake configuration process. This helps in verifying the build environment and settings.
```cmake
message(STATUS "--------------- General configuration -------------")
message(STATUS "CMake Generator: ${CMAKE_GENERATOR}")
message(STATUS "Compiler: ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}")
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
message(STATUS "CMAKE_CXX_FLAGS_DEBUG: ${CMAKE_CXX_FLAGS_DEBUG}")
message(STATUS "CMAKE_CXX_FLAGS_RELEASE: ${CMAKE_CXX_FLAGS_RELEASE}")
message(STATUS "CMAKE_CXX_FLAGS_RELWITHDEBINFO: ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}")
message(STATUS "CMAKE_EXE_LINKER_FLAGS ${CMAKE_CXX_LINKER_FLAGS}")
message(STATUS "CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}" )
message(STATUS "---------------------------------------------------")
```
--------------------------------
### Include Benchmarks Subdirectory
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Includes the 'benchmark' subdirectory, which contains the build configuration for performance benchmarks. This allows benchmarks to be compiled and run as part of the project.
```cmake
add_subdirectory(benchmark)
```
--------------------------------
### Discover and List Test Cases
Source: https://github.com/danielliamanderson/packaide/blob/master/test/CMakeLists.txt
Executes the test script to discover and list all available test cases. The output is then parsed into a list for individual test target creation.
```cmake
# Extract a list of test case names
execute_process(COMMAND ${Python3_EXECUTABLE} ${TEST_PACKING} --list-tests
OUTPUT_VARIABLE STR_TESTS
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_STRIP_TRAILING_WHITESPACE)
separate_arguments(TEST_LIST UNIX_COMMAND ${STR_TESTS})
```
--------------------------------
### Define Multiple Sheets and Pack Shapes
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Demonstrates how to define multiple sheets with different configurations and pack a set of shapes that may not fit on a single sheet. The output includes the number of successfully placed shapes and processed results for each sheet.
```python
sheets = [
'',
''
]
shapes = """
"
result, placed, fails = packaide.pack(
sheets,
shapes,
tolerance=0.5,
offset=2,
partial_solution=False,
rotations=1,
persist=False
)
print(f"Successfully placed {placed} shapes across {len(result)} sheets")
# Process results from each sheet
for sheet_idx, svg_output in result:
print(f"Sheet {sheet_idx} has parts placed")
with open(f'output_sheet_{sheet_idx}.svg', 'w') as f:
f.write(svg_output)
```
--------------------------------
### Define Benchmark and Plot Targets
Source: https://github.com/danielliamanderson/packaide/blob/master/benchmark/CMakeLists.txt
Creates custom targets for running benchmarks and plotting results, ensuring the correct PYTHONPATH is set for bindings.
```cmake
# Executes the benchmarks and creates the output files
add_custom_target(benchmarks
COMMAND ${CMAKE_COMMAND} -E env PYTHONPATH=${PYTHON_LIB_DIR}:${BINDINGS_LIB_DIR}:$ENV{PYTHONPATH}
${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/benchmark.py --run
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
add_dependencies(benchmarks PackaideBindings)
# Plots the results of the benchmarks
add_custom_target(plots
COMMAND ${CMAKE_COMMAND} -E env PYTHONPATH=${PYTHON_LIB_DIR}:${BINDINGS_LIB_DIR}:$ENV{PYTHONPATH}
${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/benchmark.py --plot
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
```
--------------------------------
### Configure Default Build Type
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Sets the default build type to 'Release' if not already specified. This ensures a consistent build configuration for release versions. Supported types include Debug, Release, RelWithDebInfo, and MinSizeRel.
```cmake
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING
"Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel."
FORCE)
endif(NOT CMAKE_BUILD_TYPE)
```
--------------------------------
### Include Python Bindings Subdirectory
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Includes the 'src' subdirectory, which is expected to contain the source files for the project, likely including C++ code for the main library and potentially bindings.
```cmake
add_subdirectory(src)
```
--------------------------------
### Enable Testing
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Enables the testing framework for the project using CTest. This allows tests to be discovered, configured, and run as part of the build process.
```cmake
enable_testing()
add_subdirectory(test)
```
--------------------------------
### Define Test Script and Library Locations
Source: https://github.com/danielliamanderson/packaide/blob/master/test/CMakeLists.txt
Sets variables for the paths to the test script, Python library source, and compiled C++ bindings. These are used to configure test execution environments.
```cmake
# Locations of the test script, the python library source,
# and the compiled library for the C++ bindings
set(TEST_PACKING "${CMAKE_CURRENT_SOURCE_DIR}/test_packing.py")
set(PYTHON_LIB_DIR ${CMAKE_SOURCE_DIR}/python)
set(BINDINGS_LIB_DIR ${CMAKE_BINARY_DIR}/src)
```
--------------------------------
### packaide.blank_sheet
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Creates an SVG string representing a blank sheet with specified dimensions.
```APIDOC
## blank_sheet(width, height)
### Description
Generates an empty SVG string for use as a packing sheet.
### Parameters
- **width** (int) - Required - Width of the sheet.
- **height** (int) - Required - Height of the sheet.
### Response
- **svg_string** (string) - The generated SVG document.
```
--------------------------------
### Link with CGAL Library
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Finds the CGAL package and links the Packaide library against it. This ensures that CGAL headers and libraries are available during the build process.
```cmake
find_package(CGAL)
target_link_libraries(PackaideLib INTERFACE CGAL::CGAL)
```
--------------------------------
### Create Individual Test Targets
Source: https://github.com/danielliamanderson/packaide/blob/master/test/CMakeLists.txt
Iterates through the discovered test cases and creates a separate CMake test target for each. This allows individual tests to be run.
```cmake
# Create a test target for each test case.
foreach(TEST ${TEST_LIST})
add_test(NAME ${TEST}
COMMAND ${Python3_EXECUTable} ${TEST_PACKING} "-v" ${TEST}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
endforeach()
```
--------------------------------
### packaide.State
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Class for managing persistence and caching of No-Fit Polygon (NFP) computations.
```APIDOC
## State()
### Description
Allows fine-grained control over caching of NFP computations to share data across multiple pack operations.
```
--------------------------------
### SVG Attribute Preservation in Packing
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Demonstrates how Packaide preserves original SVG attributes such as id, class, name, fill, and stroke. This allows for tracking input shapes in the output and applying specific styling or identification.
```python
import packaide
sheets = [packaide.blank_sheet(200, 200)]
# Shapes with preserved attributes
shapes = """
"
result, placed, fails = packaide.pack(
sheets,
shapes,
tolerance=1,
offset=3,
partial_solution=False,
rotations=2,
persist=False
)
# Output SVG will contain paths with preserved id, class, name,
# and presentation attributes, plus transform for placement
for sheet_idx, svg_output in result:
print(f"Output contains shapes with preserved attributes:")
print(svg_output[:500]) # Print first 500 chars
```
--------------------------------
### Create blank sheets
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Generates an empty SVG sheet string for use in packing operations.
```python
import packaide
# Create a blank 300x200 sheet
sheet = packaide.blank_sheet(300, 200)
# Returns: ''
# Use blank sheets for packing
sheets = [packaide.blank_sheet(500, 500)]
shapes = ''
result, placed, fails = packaide.pack(
sheets,
shapes,
tolerance=1,
offset=2,
partial_solution=False,
rotations=4,
persist=False
)
print(f"Placed {placed} shapes successfully")
```
--------------------------------
### Manage persistence state
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Uses the State class to share cached No-Fit Polygon (NFP) data across multiple packing operations.
```python
import packaide
# Create a custom state for caching
state = packaide.State()
# First packing run - computes and caches NFPs
sheets = [packaide.blank_sheet(1000, 1000)]
shapes1 = ''
result1, placed1, _ = packaide.pack(
sheets,
shapes1,
tolerance=2.5,
offset=5,
partial_solution=False,
rotations=1,
persist=True,
custom_state=state # Use custom state
)
# Second packing run - reuses cached NFPs for same shapes
shapes2 = ''
result2, placed2, _ = packaide.pack(
sheets,
shapes2,
tolerance=2.5,
offset=5,
partial_solution=False,
rotations=1,
persist=True,
custom_state=state # Reuse same state - rect NFP is already cached
)
print(f"First pack: {placed1} shapes, Second pack: {placed2} shapes")
```
--------------------------------
### Enable Frame Pointer for Profiling
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Ensures the '-fno-omit-frame-pointer' flag is set for 'RelWithDebInfo' build types to facilitate profiling. This flag is crucial for accurate stack trace analysis during performance debugging.
```cmake
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -fno-omit-frame-pointer")
```
--------------------------------
### Define Packaide Interface Library
Source: https://github.com/danielliamanderson/packaide/blob/master/CMakeLists.txt
Defines an INTERFACE library for Packaide, setting include directories and C++17 standard. This is a modern CMake approach for header-only or interface libraries.
```cmake
add_library(PackaideLib INTERFACE)
set(LIB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/include")
target_include_directories(PackaideLib INTERFACE ${LIB_INCLUDE_DIR})
target_compile_features(PackaideLib INTERFACE cxx_std_17)
```
--------------------------------
### packaide.pack
Source: https://context7.com/danielliamanderson/packaide/llms.txt
The primary function for packing SVG shapes onto one or more sheets.
```APIDOC
## pack(sheets, shapes, tolerance, offset, partial_solution, rotations, persist, custom_state)
### Description
Pack SVG shapes onto one or more sheets. Returns the packed results with placement information.
### Parameters
- **sheets** (list) - Required - List of sheet SVG documents.
- **shapes** (string) - Required - SVG document containing parts to pack.
- **tolerance** (float) - Optional - Discretization tolerance for curves.
- **offset** (float) - Optional - Spacing distance between shapes (dilation).
- **partial_solution** (boolean) - Optional - Return partial solution if not all fit.
- **rotations** (int) - Optional - Number of rotations to try.
- **persist** (boolean) - Optional - Cache results for faster subsequent runs.
- **custom_state** (State) - Optional - Custom state object for caching.
### Response
- **result** (list) - List of tuples containing (sheet_index, svg_output).
- **placed** (int) - Number of parts placed.
- **fails** (int) - Number of parts that could not fit.
```
--------------------------------
### Write SVG Results to Files
Source: https://github.com/danielliamanderson/packaide/blob/master/README.md
Iterates through results and writes each SVG output to a separate file named 'result_sheet_i.svg'.
```python
for i, out in result:
with open('result_sheet_{}.svg'.format(i), 'w') as f_out:
f_out.write(out)
```
--------------------------------
### Pack SVG shapes onto sheets
Source: https://context7.com/danielliamanderson/packaide/llms.txt
Uses the pack function to arrange SVG shapes onto provided sheets, supporting configuration for tolerance, spacing, and persistence.
```python
import packaide
# Define shapes to pack in SVG format
shapes = """
"""
# Define a sheet with existing holes to avoid (shapes on sheet are treated as holes)
sheet = """
"""
# Pack shapes onto the sheet
result, placed, fails = packaide.pack(
[sheet], # List of sheets (SVG documents)
shapes, # SVG document containing parts to pack
tolerance=2.5, # Discretization tolerance for curves
offset=5, # Spacing distance between shapes (dilation)
partial_solution=True, # Return partial solution if not all fit
rotations=1, # Number of rotations to try (1 = no rotation)
persist=True # Cache results for faster subsequent runs
)
# Output results
print(f"{placed} parts were placed. {fails} parts could not fit on the sheets")
# Save packed results - each item is (sheet_index, svg_output)
for i, out in result:
with open(f'result_sheet_{i}.svg', 'w') as f_out:
f_out.write(out)
```
--------------------------------
### Create 'check' Target for All Tests
Source: https://github.com/danielliamanderson/packaide/blob/master/test/CMakeLists.txt
Defines a custom target 'check' that runs all discovered tests using CTest. It sets the PYTHONPATH to ensure the source version of the library is used.
```cmake
# Create a single target that runs all of the tests via CTest. We
# set the PYTHONPATH environment variable to ensure that the test
# script always loads the source version of the library, rather than
# a possibly out-of-date installed version of the library.
add_custom_target(check
COMMAND ${CMAKE_COMMAND} -E env PYTHONPATH=${PYTHON_LIB_DIR}:${BINDINGS_LIB_DIR}:$ENV{PYTHONPATH}
${CMAKE_CTEST_COMMAND} --no-tests=error --output-on-failure
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
add_dependencies(check PackaideBindings)
```
--------------------------------
### Find Python 3 Interpreter
Source: https://github.com/danielliamanderson/packaide/blob/master/test/CMakeLists.txt
Locates the Python 3 interpreter, which is required for running Python-based tests.
```cmake
include(CTest)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.