import argparse
import os
import random
import sys
import math
import numpy as np
from lxml import etree
from svgpathtools import parse_path, svg2paths2
from shapely.geometry import Polygon, MultiPolygon, box
from shapely.affinity import translate, scale as shapely_scale
from shapely.ops import unary_union
def parse_svg_file(svg_file):
paths, attributes, svg_attributes = svg2paths2(svg_file)
shapes = []
for path_obj, attr in zip(paths, attributes):
# Extract the path data and convert it to a Shapely object
path_d = attr.get('d')
if path_d:
shape = path_to_polygon(parse_path(path_d))
shapes.append((shape, attr))
return shapes
def path_to_polygon(path):
# Sample points along the path to approximate it as a polygon
NUM_POINTS = 100
points = [path.point(t / NUM_POINTS) for t in range(NUM_POINTS + 1)]
coords = [(pt.real, pt.imag) for pt in points]
polygon = Polygon(coords)
return polygon
def random_position_within_canvas(shape_bounds, canvas_width, canvas_height, border_spacing):
min_x = border_spacing
max_x = canvas_width - shape_bounds[2] - border_spacing
min_y = border_spacing
max_y = canvas_height - shape_bounds[3] - border_spacing
if max_x <= min_x or max_y <= min_y:
return None # Shape cannot fit within the canvas
x = random.uniform(min_x, max_x)
y = random.uniform(min_y, max_y)
return x, y
input_files = args.input_files
output_file = args.output_file
canvas_width = args.width
canvas_height = args.height
shape_spacing = args.spacing
border_spacing = args.border_spacing
# Parse input SVG files
shapes = []
for svg_file in input_files:
svg_shapes = parse_svg_file(svg_file)
if not svg_shapes:
print(f"Warning: No shapes found in {svg_file}")
continue
for shape, attr in svg_shapes:
shapes.append({'shape': shape, 'attr': attr, 'file': svg_file})
if not shapes:
print("No valid shapes to place.")
sys.exit(1)
# Initialize placed shapes list
placed_shapes = []
# Create canvas boundary
canvas_boundary = box(0, 0, canvas_width, canvas_height)
# Attempt to place each shape
for shape_dict in shapes:
shape = shape_dict['shape']
attr = shape_dict['attr']
filename = shape_dict['file']
# Scale shape if it is larger than the canvas
shape_bounds = shape.bounds # (minx, miny, maxx, maxy)
shape_width = shape_bounds[2] - shape_bounds[0]
shape_height = shape_bounds[3] - shape_bounds[1]
scale_factor = min(
(canvas_width - 2 * border_spacing) / shape_width,
(canvas_height - 2 * border_spacing) / shape_height,
1.0 # Do not scale up, only down
)
shape = shapely_scale(shape, xfact=scale_factor, yfact=scale_factor, origin=(0, 0))
shape_bounds = shape.bounds
shape_width = shape_bounds[2] - shape_bounds[0]
shape_height = shape_bounds[3] - shape_bounds[1]
# Increase shape dimensions by spacing for collision detection
shape_for_collision = shape.buffer(shape_spacing / 2.0)
max_attempts = 1000
attempt = 0
while attempt < max_attempts:
position = random_position_within_canvas(shape_bounds, canvas_width, canvas_height, border_spacing)
if position is None:
print(f"Shape from {filename} is too large to fit in the canvas.")
break
x_offset = position[0] - shape_bounds[0]
y_offset = position[1] - shape_bounds[1]
# Move shape to the new position
moved_shape = translate(shape, xoff=x_offset, yoff=y_offset)
moved_shape_for_collision = translate(shape_for_collision, xoff=x_offset, yoff=y_offset)
# Check for collision with placed shapes
collision = False
for placed in placed_shapes:
if moved_shape_for_collision.intersects(placed['collision_shape']):
collision = True
break
if collision:
attempt += 1
continue
# Ensure shape is within canvas
if not canvas_boundary.contains(moved_shape):
attempt += 1
continue
# Place the shape
shape_dict['placed_shape'] = moved_shape
shape_dict['collision_shape'] = moved_shape_for_collision
shape_dict['x_offset'] = x_offset
shape_dict['y_offset'] = y_offset
shape_dict['scale_factor'] = scale_factor
placed_shapes.append(shape_dict)
break
else:
print(f"Could not place shape from {filename} after {max_attempts} attempts.")
if not placed_shapes:
print("No shapes were placed.")
sys.exit(1)
# Create the output SVG
svg_ns = "http://www.w3.org/2000/svg"
svg_root = etree.Element('svg', nsmap={None: svg_ns})
svg_root.set('width', str(canvas_width))
svg_root.set('height', str(canvas_height))
svg_root.set('viewBox', f"0 0 {canvas_width} {canvas_height}")
for placed in placed_shapes:
svg_file = placed['file']
x_offset = placed['x_offset']
y_offset = placed['y_offset']
scale_factor = placed['scale_factor']
# Parse the SVG file and get its root
tree = etree.parse(svg_file)
svg_elem = tree.getroot()
# Namespace fix
nsmap = svg_elem.nsmap
if None in nsmap:
nsmap['svg'] = nsmap.pop(None)
# Get all child elements
for elem in svg_elem.iter():
if '}' in elem.tag:
elem.tag = etree.QName(elem).localname
# Create a group to apply transformations
g_elem = etree.SubElement(svg_root, 'g')
# Set the transformation
transform = f"translate({x_offset},{y_offset}) scale({scale_factor})"
g_elem.set("transform", transform)
# Append all elements from the SVG file
for child in svg_elem:
g_elem.append(child)
# Write the output SVG
tree = etree.ElementTree(svg_root)
tree.write(output_file, pretty_print=True, xml_declaration=True, encoding='UTF-8')
print(f"Output SVG saved as {output_file}")
if name == 'main':
main() keep the code functionality and extend it by Improved Placement Algorithm:
code
Genetic Algorithms or Simulated Annealing: More sophisticated algorithms can be used to find better packing solutions by exploring a larger search space.
Greedy Algorithm with Sorting: Placing larger shapes first may improve the packing efficiency.
Rotation of Shapes:
code
Allowing shapes to be rotated can improve the packing density.
Implementing rotations would require additional calculations for collision detection.
make sure to use shapes of different size that could scale like 60, 80, 100, 120, 140 percent of the original size, and allow for rotation in preselected degrees like 15, -15, 30, -30, make sure that the functionality of the original is preserved, double check it and double check that the code uses irregular bin packing and not square packing, make sure to use irregular bin packing
Sure, I'd be happy to help you extend your code to incorporate an improved placement algorithm, allow for rotation of shapes, and include scaling of shapes to specified percentages, all while ensuring that the functionality of the original code is preserved. Below, I'll explain the modifications needed and provide the updated code.
Overview of Changes
Improved Placement Algorithm:
We'll implement a Simulated Annealing algorithm for better packing efficiency. This algorithm is suitable for solving optimization problems like irregular bin packing by exploring a larger search space and avoiding local minima.
We'll also implement a simple greedy algorithm with sorting, where shapes are sorted by area (largest first) before placement attempts.
Rotation of Shapes:
Shapes will be allowed to rotate by preselected degrees: -30°, -15°, 0°, 15°, 30°.
Collision detection will be updated to account for rotated shapes.
Scaling of Shapes:
Shapes can be scaled to different sizes: 60%, 80%, 100%, 120%, 140% of their original size.
Scaling will be applied before placement attempts, and collision detection will consider the scaled shapes.
Irregular Bin Packing:
The code will perform irregular bin packing, considering the actual shapes and their overlaps, not just bounding boxes.
Preserving Original Functionality:
The core functionality of parsing SVG files, placing shapes on a canvas, and generating an output SVG will be preserved.
We'll ensure that the code remains modular, readable, and maintainable.
Updated Code with Explanations
Below is the updated code with the requested features. I've added comments to explain the changes.
python
#!/usr/bin/env python3
import argparse
import os
import random
import sys
import math
import numpy as np
from lxml import etree
from svgpathtools import parse_path, svg2paths2
from shapely.geometry import Polygon, MultiPolygon, box
from shapely.affinity import translate, scale as shapely_scale, rotate
from shapely.ops import unary_union
from copy import deepcopy
NSMAP = {'svg': 'http://www.w3.org/2000/svg'}
def parse_svg_file(svg_file):
paths, attributes, svg_attributes = svg2paths2(svg_file)
shapes = []
for path_obj, attr in zip(paths, attributes):
# Extract the path data and convert it to a Shapely object
path_d = attr.get('d')
if path_d:
shape = path_to_polygon(parse_path(path_d))
shapes.append((shape, attr))
return shapes
def path_to_polygon(path):
# Sample points along the path to approximate it as a polygon
NUM_POINTS = 100
points = [path.point(t / NUM_POINTS) for t in range(NUM_POINTS + 1)]
coords = [(pt.real, pt.imag) for pt in points]
polygon = Polygon(coords)
return polygon
def place_shapes_simulated_annealing(shapes, canvas_boundary, shape_spacing, border_spacing):
"""
Place shapes on the canvas using a Simulated Annealing algorithm.
"""
# Define parameters for Simulated Annealing
initial_temperature = 1000
final_temperature = 1
alpha = 0.9 # Cooling rate
max_iterations = 1000
# Initial solution: Try to place shapes greedily
placed_shapes = []
unplaced_shapes = deepcopy(shapes)
random.shuffle(unplaced_shapes) # Randomize order
# Sort shapes by area (largest first) for greedy placement
unplaced_shapes.sort(key=lambda s: -s['shape'].area)
for shape_dict in unplaced_shapes:
success = attempt_to_place_shape(shape_dict, placed_shapes, canvas_boundary, shape_spacing, border_spacing)
if success:
placed_shapes.append(shape_dict)
else:
print(f"Could not place shape from {shape_dict['file']} using greedy placement.")
# Simulated Annealing to improve placement
temperature = initial_temperature
current_state = placed_shapes
best_state = placed_shapes
best_score = len(best_state) # Maximize the number of placed shapes
while temperature > final_temperature:
for i in range(max_iterations):
# Generate a neighbor by attempting to place an unplaced shape
neighbor_state = deepcopy(current_state)
unplaced = [shape for shape in shapes if shape not in neighbor_state]
if not unplaced:
break # All shapes are placed
shape_to_place = random.choice(unplaced)
success = attempt_to_place_shape(shape_to_place, neighbor_state, canvas_boundary, shape_spacing, border_spacing)
if success:
neighbor_state.append(shape_to_place)
neighbor_score = len(neighbor_state)
delta = neighbor_score - best_score
if delta > 0 or random.random() < math.exp(delta / temperature):
current_state = neighbor_state
if neighbor_score > best_score:
best_state = neighbor_state
best_score = neighbor_score
temperature *= alpha # Cool down
return best_state
def attempt_to_place_shape(shape_dict, placed_shapes, canvas_boundary, shape_spacing, border_spacing):
"""
Attempt to place a shape on the canvas with various scales and rotations.
"""
shape_orig = shape_dict['shape']
filename = shape_dict['file']
allowed_scales = [0.6, 0.8, 1.0, 1.2, 1.4]
allowed_rotations = [-30, -15, 0, 15, 30] # Degrees
max_attempts = 1000
# Try combinations of scales and rotations
for scale_factor in allowed_scales:
for angle in allowed_rotations:
attempts = 0
shape = shapely_scale(shape_orig, xfact=scale_factor, yfact=scale_factor, origin=(0, 0))
shape = rotate(shape, angle, origin='center', use_radians=False)
shape_bounds = shape.bounds
shape_for_collision = shape.buffer(shape_spacing / 2.0)
while attempts < max_attempts:
position = random_position_within_canvas(shape_bounds, canvas_boundary.bounds, border_spacing)
if position is None:
print(f"Shape from {filename} is too large to fit in the canvas at scale {scale_factor*100}%.")
break
x_offset = position[0] - shape_bounds[0]
y_offset = position[1] - shape_bounds[1]
# Move shape to the new position
moved_shape = translate(shape, xoff=x_offset, yoff=y_offset)
moved_shape_for_collision = translate(shape_for_collision, xoff=x_offset, yoff=y_offset)
# Check for collision with placed shapes
collision = False
for placed in placed_shapes:
if moved_shape_for_collision.intersects(placed['collision_shape']):
collision = True
break
if collision:
attempts += 1
continue
# Ensure shape is within canvas
if not canvas_boundary.contains(moved_shape):
attempts += 1
continue
# Place the shape
shape_dict['placed_shape'] = moved_shape
shape_dict['collision_shape'] = moved_shape_for_collision
shape_dict['x_offset'] = x_offset
shape_dict['y_offset'] = y_offset
shape_dict['scale_factor'] = scale_factor
shape_dict['rotation'] = angle
return True # Placement successful
# If we couldn't place with this scale and rotation, try next
return False # Could not place the shape
def random_position_within_canvas(shape_bounds, canvas_bounds, border_spacing):
minx_canvas, miny_canvas, maxx_canvas, maxy_canvas = canvas_bounds
min_x = minx_canvas + border_spacing
max_x = maxx_canvas - (shape_bounds[2] - shape_bounds[0]) - border_spacing
min_y = miny_canvas + border_spacing
max_y = maxy_canvas - (shape_bounds[3] - shape_bounds[1]) - border_spacing
if max_x <= min_x or max_y <= min_y:
return None # Shape cannot fit within the canvas
x = random.uniform(min_x, max_x)
y = random.uniform(min_y, max_y)
return x, y
def main():
parser = argparse.ArgumentParser(description="Pack multiple SVG files into one SVG canvas.")
parser.add_argument('--input_files', nargs='+', required=True, help='Input SVG files')
parser.add_argument('--output_file', required=True, help='Output SVG file')
parser.add_argument('--width', type=float, required=True, help='Canvas width')
parser.add_argument('--height', type=float, required=True, help='Canvas height')
parser.add_argument('--spacing', type=float, default=40.0, help='Spacing between shapes')
parser.add_argument('--border_spacing', type=float, default=40.0, help='Spacing between shapes and canvas borders')
args = parser.parse_args()
input_files = args.input_files
output_file = args.output_file
canvas_width = args.width
canvas_height = args.height
shape_spacing = args.spacing
border_spacing = args.border_spacing
# Parse input SVG files
shapes = []
for svg_file in input_files:
svg_shapes = parse_svg_file(svg_file)
if not svg_shapes:
print(f"Warning: No shapes found in {svg_file}")
continue
for shape, attr in svg_shapes:
shapes.append({'shape': shape, 'attr': attr, 'file': svg_file})
if not shapes:
print("No valid shapes to place.")
sys.exit(1)
# Create canvas boundary
canvas_boundary = box(0, 0, canvas_width, canvas_height)
# Place shapes using Simulated Annealing
placed_shapes = place_shapes_simulated_annealing(shapes, canvas_boundary, shape_spacing, border_spacing)
if not placed_shapes:
print("No shapes were placed.")
sys.exit(1)
# Create the output SVG
svg_ns = "http://www.w3.org/2000/svg"
svg_root = etree.Element('svg', nsmap={None: svg_ns})
svg_root.set('width', str(canvas_width))
svg_root.set('height', str(canvas_height))
svg_root.set('viewBox', f"0 0 {canvas_width} {canvas_height}")
for placed in placed_shapes:
svg_file = placed['file']
x_offset = placed['x_offset']
y_offset = placed['y_offset']
scale_factor = placed['scale_factor']
rotation = placed['rotation']
# Parse the SVG file and get its root
tree = etree.parse(svg_file)
svg_elem = tree.getroot()
# Namespace fix
nsmap = svg_elem.nsmap
if None in nsmap:
nsmap['svg'] = nsmap.pop(None)
# Get all child elements
for elem in svg_elem.iter():
if '}' in elem.tag:
elem.tag = etree.QName(elem).localname
# Create a group to apply transformations
g_elem = etree.SubElement(svg_root, 'g')
# Set the transformation
transform = f"translate({x_offset},{y_offset}) rotate({rotation},{0},{0}) scale({scale_factor})"
g_elem.set("transform", transform)
# Append all elements from the SVG file
for child in svg_elem:
g_elem.append(deepcopy(child)) # Use deepcopy to avoid issues with multiple appends
# Write the output SVG
tree = etree.ElementTree(svg_root)
tree.write(output_file, pretty_print=True, xml_declaration=True, encoding='UTF-8')
print(f"Output SVG saved as {output_file}")
if __name__ == '__main__':
main()
You can adjust the allowed scales and rotations by modifying the allowed_scales and allowed_rotations lists in the attempt_to_place_shape function.
Conclusion
The updated code implements a more sophisticated placement algorithm using simulated annealing, allows shapes to be scaled and rotated to improve packing efficiency, and ensures that irregular bin packing is performed. The original functionality is preserved, and shapes are placed without overlapping within the specified canvas size.
Feel free to test the code with your SVG files and adjust parameters as needed. If you have any questions or need further assistance, please let me know!