import random
from deap import base, creator, tools, algorithms
import numpy as np
from shapely.geometry import Polygon
from shapely.affinity import translate, rotate, scale
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon as MplPolygon
from svgpathtools import svg2paths2
Đường dẫn tới file SVG của bạn
svg_file = 'C:/Users/tamhi/Desktop/svg.svg' # Thay bằng đường dẫn tới file SVG
Giả sử đối tượng đầu tiên là đối tượng cần nesting
Tương tự như trước
...
Đối tượng cần nesting
if len(paths) < 1:
print("Không tìm thấy đối tượng trong file SVG.")
exit()
Chuyển đổi path thành Polygon
def path_to_polygon(path):
num_samples = 100
points = []
for segment in path:
try:
line_points = [segment.point(t) for t in np.linspace(0, 1, num_samples)]
points.extend([(p.real, p.imag) for p in line_points])
except:
continue
polygon = Polygon(points)
if not polygon.is_valid:
polygon = polygon.buffer(0)
return polygon
creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) # Chúng ta muốn giảm thiểu diện tích chưa sử dụng
creator.create("Individual", list, fitness=creator.FitnessMin)
toolbox = base.Toolbox()
Một cá thể là một danh sách các thông số [x, y, góc xoay] cho mỗi bản sao
def create_individual():
# Tạo cá thể mới
individual = []
for _ in range(num_copies):
x = random.uniform(0, material_width)
y = random.uniform(0, material_height)
angle = random.choice([0, 90, 180, 270])
individual.extend([x, y, angle])
return creator.Individual(individual)
def evaluate(individual):
placed_polygons = []
# Tạo tấm nguyên liệu
material = Polygon([
(0, 0), (material_width, 0),
(material_width, material_height), (0, material_height)
])
# Đặt các đối tượng
collision = False
for i in range(num_copies):
x = individual[3 * i]
y = individual[3 * i + 1]
angle = individual[3 * i + 2]
rotated_poly = rotate(nesting_object, angle, origin='center', use_radians=False)
moved_poly = translate(rotated_poly, xoff=x, yoff=y)
if not material.contains(moved_poly):
return (float('inf'),) # Ngoài vật liệu, giải pháp không hợp lệ
for placed_poly in placed_polygons:
if moved_poly.intersects(placed_poly):
return (float('inf'),) # Chồng lấn, giải pháp không hợp lệ
placed_polygons.append(moved_poly)
# Tính diện tích vật liệu chưa sử dụng
union_polygons = cascaded_union(placed_polygons)
unused_area = material.area - union_polygons.area
return (unused_area,)
def main():
population = toolbox.population(n=50) # Kích thước quần thể
NGEN = 40 # Số thế hệ
for gen in range(NGEN):
offspring = algorithms.varAnd(population, toolbox, cxpb=0.5, mutpb=0.2)
fits = toolbox.map(toolbox.evaluate, offspring)
for fit, ind in zip(fits, offspring):
ind.fitness.values = fit
population = toolbox.select(offspring, k=len(population))
# In ra thông tin
best_ind = tools.selBest(population, 1)[0]
print(f"Thế hệ {gen}, Best fitness: {best_ind.fitness.values[0]}")
# Kết quả tốt nhất
best_ind = tools.selBest(population, 1)[0]
# Vẽ kết quả
placed_polygons = []
for i in range(num_copies):
x = best_ind[3 * i]
y = best_ind[3 * i + 1]
angle = best_ind[3 * i + 2]
rotated_poly = rotate(nesting_object, angle, origin='center', use_radians=False)
moved_poly = translate(rotated_poly, xoff=x, yoff=y)
placed_polygons.append(moved_poly)
# Vẽ kết quả như trước
fig, ax = plt.subplots(figsize=(10, 20))
material = Polygon([
(0, 0), (material_width, 0),
(material_width, material_height), (0, material_height)
])
material_patch = MplPolygon(
list(material.exterior.coords),
closed=True,
fill=False,
edgecolor='black',
linewidth=2
)
ax.add_patch(material_patch)
cmap = plt.get_cmap('tab20')
for idx, poly in enumerate(placed_polygons):
x, y = poly.exterior.xy
coords = list(zip(x, y))
color = cmap(idx % 20)
poly_patch = MplPolygon(
coords,
closed=True,
facecolor=color,
edgecolor='black',
alpha=0.7
)
ax.add_patch(poly_patch)
ax.set_xlim(-10, material_width + 10)
ax.set_ylim(-10, material_height + 10)
ax.set_aspect('equal', adjustable='box')
ax.set_title('Kết quả Nesting')
plt.gca().invert_yaxis()
plt.show()
if name == 'main':
main() thay đổi mã này bằng cách sử dụng thư viện svgnest thông qua node.js hướng dẫn chi tiết từng bước và tạo mã hoàn chỉnh
Được rồi, tôi sẽ hướng dẫn bạn từng bước thay đổi mã của bạn bằng cách sử dụng thư viện SVGNest thông qua Node.js, và cung cấp mã hoàn chỉnh để thực hiện việc nesting đối tượng từ file SVG của bạn.
1. Cài đặt Node.js và npm
Trước tiên, bạn cần cài đặt Node.js trên máy tính nếu chưa có. Bạn có thể tải Node.js tại trang web chính thức: https://nodejs.org/
Sau khi cài đặt Node.js, bạn sẽ có npm (Node Package Manager) để quản lý các thư viện.
2. Tạo một thư mục dự án mới
Tạo một thư mục mới cho dự án của bạn và chuyển vào thư mục đó:
bash
mkdir svg-nesting-project
cd svg-nesting-project
3. Khởi tạo dự án Node.js
Khởi tạo một dự án Node.js mới bằng cách tạo file package.json:
bash
npm init -y
4. Cài đặt các thư viện cần thiết
Chúng ta sẽ cần cài đặt các thư viện sau:
svgnest: Thư viện nesting chính.
d3: Thư viện mà svgnest phụ thuộc.
xmldom và xpath: Để xử lý file SVG.
svgpath: Để thao tác với các đường path trong SVG.
fs: Thư viện tích hợp của Node.js để đọc/ghi file.
Cài đặt các thư viện:
bash
npm install svgnest d3 xmldom xpath svgpath
Lưu ý: Nếu bạn gặp lỗi khi cài đặt svgnest, hãy đảm bảo rằng bạn đang sử dụng phiên bản Node.js phù hợp và có internet để tải các gói.
5. Cấu trúc file dự án
Trong thư mục dự án, tạo các file sau:
index.js: File mã chính của bạn.
input.svg: File SVG đầu vào của bạn (sao chép file svg.svg của bạn vào đây).
output.svg: File SVG đầu ra sau khi nesting.
6. Viết mã trong index.js
Dưới đây là mã hoàn chỉnh cho index.js với các giải thích chi tiết:
javascript
// index.js
const fs = require('fs');
const d3 = require('d3');
const SVGNest = require('svgnest');
const { DOMParser, XMLSerializer } = require('xmldom');
const xpath = require('xpath');
const svgpath = require('svgpath');
// Đọc nội dung của file SVG đầu vào
const svgInput = fs.readFileSync('input.svg', 'utf8');
// Phân tích cú pháp SVG thành DOM
const parser = new DOMParser();
const serializer = new XMLSerializer();
const svgDoc = parser.parseFromString(svgInput, 'image/svg+xml');
// Lấy kích thước của tấm nguyên liệu (material)
const materialWidth = 1000; // Thay đổi tùy ý
const materialHeight = 2000; // Thay đổi tùy ý
// Số lượng bản sao
const numCopies = 20; // Thay đổi số lượng tùy ý
// Lấy đối tượng cần nesting từ SVG (giả sử phần tử path đầu tiên)
const nodes = xpath.select('//path', svgDoc);
if (nodes.length === 0) {
console.log("Không tìm thấy đối tượng <path> trong file SVG.");
process.exit(1);
}
const pathNode = nodes[0];
// Lấy dữ liệu d của path
const dValue = pathNode.getAttribute('d');
// Hàm tạo các đối tượng cần nesting
function createNestPaths(dValue, numCopies) {
let nestPaths = [];
for (let i = 0; i < numCopies; i++) {
// Tạo phần tử path mới với cùng dữ liệu d
let newPath = {
d: dValue,
id: `path-${i}`,
};
nestPaths.push(newPath);
}
return nestPaths;
}
// Tạo các đối tượng cần nesting
let nestPaths = createNestPaths(dValue, numCopies);
// Tạo đối tượng tấm nguyên liệu
let binPolygon = {
x: 0,
y: 0,
width: materialWidth,
height: materialHeight,
};
// Khởi tạo SVGNest
let svgNest = new SVGNest();
// Thiết lập bin (tấm nguyên liệu)
svgNest.binPolygon = binPolygon;
// Cung cấp các đối tượng cần nesting
svgNest.polygons = nestPaths;
// Thiết lập các tùy chọn (nếu cần)
svgNest.config = {
spacing: 0, // Khoảng cách giữa các đối tượng
rotatable: true, // Cho phép xoay các đối tượng
rotations: 4, // Số lượng góc xoay (360/4 = 90 độ mỗi lần xoay)
// Bạn có thể thêm các tùy chọn khác tại đây
};
// Bắt đầu thực hiện nesting
svgNest.start(function (result) {
// Kết quả là một mảng các đối tượng đã được đặt vị trí
// Tạo một SVG mới để lưu kết quả
const svgNS = 'http://www.w3.org/2000/svg';
let outputDoc = parser.parseFromString('<svg xmlns="http://www.w3.org/2000/svg"></svg>', 'image/svg+xml');
let svgRoot = outputDoc.documentElement;
// Thiết lập kích thước cho SVG đầu ra
svgRoot.setAttribute('width', materialWidth);
svgRoot.setAttribute('height', materialHeight);
// Vẽ tấm nguyên liệu (tùy chọn)
let rect = outputDoc.createElementNS(svgNS, 'rect');
rect.setAttribute('x', 0);
rect.setAttribute('y', 0);
rect.setAttribute('width', materialWidth);
rect.setAttribute('height', materialHeight);
rect.setAttribute('fill', 'none');
rect.setAttribute('stroke', 'black');
svgRoot.appendChild(rect);
// Thêm các đối tượng đã được nesting vào SVG đầu ra
result.forEach(item => {
let pathElement = outputDoc.createElementNS(svgNS, 'path');
pathElement.setAttribute('d', item.d);
// Áp dụng các phép biến đổi vị trí và góc xoay
let transform = '';
if (item.rotation) {
transform += `rotate(${item.rotation}, 0, 0) `;
}
if (item.x || item.y) {
transform += `translate(${item.x}, ${item.y}) `;
}
if (transform) {
pathElement.setAttribute('transform', transform.trim());
}
pathElement.setAttribute('fill', 'none');
pathElement.setAttribute('stroke', 'red');
svgRoot.appendChild(pathElement);
});
// Chuyển SVG DOM thành chuỗi
const outputSvg = serializer.serializeToString(outputDoc);
// Ghi kết quả vào file output.svg
fs.writeFileSync('output.svg', outputSvg);
console.log('Đã hoàn thành nesting và lưu kết quả vào file output.svg');
});
Chương trình sẽ thực hiện nesting và lưu kết quả vào output.svg.
9. Kiểm tra kết quả
Mở file output.svg bằng trình duyệt hoặc một công cụ xem SVG để xem kết quả nesting.
10. Tùy chỉnh thêm
Bạn có thể tùy chỉnh thêm các tham số trong svgNest.config để điều chỉnh kết quả:
spacing: Khoảng cách giữa các đối tượng.
rotatable: Cho phép xoay đối tượng hay không.
rotations: Số lượng góc xoay (ví dụ: 4 tương ứng với 0°, 90°, 180°, 270°).
population: Kích thước quần thể cho thuật toán genetic.
mutationRate: Tỷ lệ đột biến.
Ví dụ:
javascript
svgNest.config = {
spacing: 5, // Thêm khoảng cách 5 đơn vị giữa các đối tượng
rotatable: true,
rotations: 8, // Cho phép xoay mỗi 45°
population: 10,
mutationRate: 10,
};
11. Ghi chú quan trọng
SVGNest sử dụng thuật toán genetic để tối ưu hóa vị trí của các đối tượng, do đó kết quả có thể khác nhau mỗi lần chạy.
Thư viện SVGNest hoạt động tốt với các đối tượng là polygon (đa giác). Nếu đối tượng của bạn phức tạp hoặc có nhiều đường cong, bạn có thể cần chuyển đổi nó thành dạng polygon.
Nếu đối tượng của bạn là một path phức tạp, việc nesting có thể mất nhiều thời gian hơn.
12. Chuyển đổi path thành polygon (nếu cần)
Nếu bạn gặp vấn đề với việc nesting một path phức tạp, bạn có thể chuyển đổi path thành polygon bằng cách sử dụng thư viện svgpath hoặc các công cụ khác.
Ví dụ, sử dụng svgpath để lấy các điểm và tạo polygon:
javascript
const svgPath = svgpath(dValue);
const segments = svgPath.segments;
// Chuyển đổi các segment thành điểm và tạo polygon
let points = [];
segments.forEach(segment => {
// Xử lý từng segment để lấy tọa độ điểm
// ...
});
Tuy nhiên, việc chuyển đổi phức tạp và cần nhiều xử lý hơn, bạn có thể tìm kiếm các thư viện hoặc công cụ hỗ trợ việc này.
13. Kết luận
Bằng cách sử dụng thư viện SVGNest thông qua Node.js, bạn có thể thực hiện việc nesting các đối tượng từ file SVG một cách hiệu quả và tối ưu. Thư viện này cung cấp nhiều tùy chọn để bạn điều chỉnh theo nhu cầu cụ thể của mình.
Hy vọng hướng dẫn chi tiết này sẽ giúp bạn hoàn thành dự án của mình.