code cleanup, added util file

Make stitches file breaking with bezier import, look into this
main
Howard DaCosta 2022-04-05 11:49:05 -04:00
rodzic 965cc5bab9
commit d1ef25927c
6 zmienionych plików z 103 dodań i 369 usunięć

BIN
.DS_Store vendored

Plik binarny nie jest wyświetlany.

Wyświetl plik

@ -6,6 +6,7 @@ from inkex import Polyline, PathElement
from lxml import etree from lxml import etree
from sympy import Segment, Point from sympy import Segment, Point
from wiredb_proxy import WireDBProxy from wiredb_proxy import WireDBProxy
import wire_util
class Connector(): class Connector():
''' '''
@ -139,13 +140,12 @@ class CombineGridsWorker():
# range where interpolation routing is present # range where interpolation routing is present
start, end = self.interp_wire_helper.is_in_group_interpolation_range(group_key, curr_wire_idx) start, end = self.interp_wire_helper.is_in_group_interpolation_range(group_key, curr_wire_idx)
if start is not None: # we are in interpolation range! if start is not None: # we are in interpolation range!
inkex.errormsg("IN interp range!")
interp_points = self.interp_wire_helper.get_custom_interpolation_route(group_key, start, end, curr_wire_idx) interp_points = self.interp_wire_helper.get_custom_interpolation_route(group_key, start, end, curr_wire_idx)
joint_wire_points.extend(interp_points) joint_wire_points.extend(interp_points)
generated_combined_wires.append(joint_wire_points) generated_combined_wires.append(joint_wire_points)
joint_wire_points = ['{},{}'.format(p[0],p[1]) for p in joint_wire_points] joint_wire_points = ['{},{}'.format(p[0],p[1]) for p in joint_wire_points]
elem = self.create_path(joint_wire_points, is_horizontal=self.is_horizontal_connection) elem = wire_util.create_path(self.svg, joint_wire_points, is_horizontal=self.is_horizontal_connection)
generated_ids.append(elem.get_id()) generated_ids.append(elem.get_id())
# generate new grouping of wires # generate new grouping of wires
@ -157,16 +157,6 @@ class CombineGridsWorker():
inkex.errormsg("Please change your template routing wires.") inkex.errormsg("Please change your template routing wires.")
return return
def connect_custom_wires(self, wire_groups_dict):
# how many wires are grouped together???
num_wires = len(wire_groups_dict[list(wire_groups_dict.keys())[0]])
interpolation_wires = [[p for p in w.path.end_points] for w in self.interpolation_wires]
interp_dict = self.generate_interpolation_points(interpolation_wires, num_wires)
# determine the wiregroups where the interpolation wires start
# interp_start_indices = self.calculate_interp_wire_group(wire_groups_dict, interpolation_wires)
self.connect_wires(wire_groups_dict, interpolation_wires, interp_dict, interp_start_indices=None)
def has_valid_interpolation_points(self, generated_combined_wires): def has_valid_interpolation_points(self, generated_combined_wires):
''' '''
generated_combined_wires: list of interpolation wire_points for each wire generated_combined_wires: list of interpolation wire_points for each wire
@ -204,89 +194,11 @@ class CombineGridsWorker():
return False return False
return True return True
def segment_line(self, line, num_points):
'''
Breaks line into num_points equal parts
returns array of points
line: A shapely.LineString object (interpolation along line can be done manually but this is easier)
'''
points = []
def parameterize_line(t):
x_t = line[0][0] + (line[1][0] - line[0][0]) * t
y_t = line[0][1] + (line[1][1] - line[0][1]) * t
return x_t, y_t
segment_length = 1 / (num_points + 1)
for i in range(1 ,num_points+2): # adjust from 0 to n+1 bc we cant put in 0 to the parameterized line equation
x, y = parameterize_line(i * segment_length)
points.append([x,y])
return points
def generate_interpolation_points(self, interpolation_wires, num_wires):
'''
Generates a dict mapping a pair of points on interpolation wires to the intermediate
points to be used by wires
'''
interp_dict = {}
for i in range(len(interpolation_wires) - 1):
wire1 = interpolation_wires[i]
wire2 = interpolation_wires[i+1]
for j in range(1, len(wire1) - 1): # exclude parts of interp wire that connect to sensor wire
x1, y1 = wire1[j].x, wire1[j].y
x2, y2 = wire2[j].x, wire2[j].y
line = [[x1, y1], [x2, y2]]
interp_dict[(x1, y1, x2, y2)] = [[x1, y1]]
# FOR NOW, assume interp wires are placed @ top and bottommost wire
# need to account for these points already placed by subtracting 2
# in future, user may only want custom wiring for SOME wires and default for others
# in this case, need to add additional detection mechanisms to see where they are
interp_points = self.segment_line(line, num_wires - 2)
interp_dict[(x1, y1, x2, y2)].extend(interp_points)
# points = ['{},{}'.format(p[0],p[1]) for p in line]
# self.create_path(points, False)
return interp_dict
def calculate_interp_wire_group(self, wire_groups_dict, interpolation_wires):
'''
Find where interpolation wires start on a wire group
(and where they end on another?)
'''
start_points = sorted(list(wire_groups_dict.keys()))
interp_start_indices = []
for sp in start_points:
for wire_idx, wire in enumerate(wire_groups_dict[sp]):
# assumption that interpolation wire starts at END of a wire
for w in interpolation_wires:
if wire[-1].x == w[0][0] and wire[-1].y == w[0][1]:
interp_start_indices.append((sp,wire_idx))
return interp_start_indices
def add_interpolation_points(self, wire_idx, interpolation_wires, interpolation_dict):
'''
Generates list of interpolation points to add to current wire
FOR NOW ASSUMING TWO INTERPOLATION WIRES
'''
wire1, wire2 = interpolation_wires
intermediate_points = []
for i in range(1, len(wire1) - 1):
x1, y1 = wire1[i].x, wire1[i].y
xn, yn = wire2[i].x , wire2[i].y
interpolation_points = interpolation_dict[(x1,y1,xn,yn)]
intermediate_points.append(interpolation_points[wire_idx])
return intermediate_points
def run(self): def run(self):
for elem in self.svg.get_selected(): for elem in self.svg.get_selected():
if type(elem) == PathElement: #connector if type(elem) == PathElement: #connector
points = [p for p in elem.path.end_points] points = [p for p in elem.path.end_points]
# inkex.errormsg("\n\n\IDs:{}".format(elem.get_id()))
self.wires.append(elem) self.wires.append(elem)
wire_groups = self.group_wires(self.wires) wire_groups = self.group_wires(self.wires)
@ -368,19 +280,16 @@ class InterpolationWires():
def localize_interpolation_wire(self, start_point): def localize_interpolation_wire(self, start_point):
inkex.errormsg("\n\n start point of interp: {} \n\n".format(start_point))
for g_key in self.wire_groups_dict.keys(): for g_key in self.wire_groups_dict.keys():
wire_group = self.wire_groups_dict[g_key] wire_group = self.wire_groups_dict[g_key]
for wire_idx, wire_elem in enumerate(wire_group): for wire_idx, wire_elem in enumerate(wire_group):
wire_points = [p for p in wire_elem.path.end_points] wire_points = [p for p in wire_elem.path.end_points]
wire_start = wire_points[0] wire_start = wire_points[0]
wire_end = wire_points[-1] wire_end = wire_points[-1]
inkex.errormsg("\n\nstart end {} {}\n\n".format(wire_start, wire_end))
def check_same_point(p1, p2): def check_same_point(p1, p2):
return round(p1.x, 2) == round(p2.x, 2) and round(p1.y, 2) == round(p2.y, 2) return round(p1.x, 2) == round(p2.x, 2) and round(p1.y, 2) == round(p2.y, 2)
inkex.errormsg(round(start_point.x,2) == round(wire_end.x,2) and round(start_point.y,2) == round(wire_end.y, 2)) inkex.errormsg(round(start_point.x,2) == round(wire_end.x,2) and round(start_point.y,2) == round(wire_end.y, 2))
if check_same_point(start_point, wire_start) or check_same_point(start_point, wire_end): if check_same_point(start_point, wire_start) or check_same_point(start_point, wire_end):
inkex.errormsg("FOUND A WIRE!")
if g_key not in self.group_interpolation_ranges: if g_key not in self.group_interpolation_ranges:
self.group_interpolation_ranges[g_key] = [] self.group_interpolation_ranges[g_key] = []
self.group_interpolation_ranges[g_key].append(wire_idx) self.group_interpolation_ranges[g_key].append(wire_idx)
@ -406,7 +315,6 @@ class InterpolationWires():
else: else:
self.group_connections[w.get_id()] = (group1, group1_idx) self.group_connections[w.get_id()] = (group1, group1_idx)
inkex.errormsg("what is ranges:{}".format(self.group_interpolation_ranges))
def get_group_interpolation_range(self, g_key): def get_group_interpolation_range(self, g_key):
''' '''
@ -460,12 +368,8 @@ class InterpolationWires():
TODO: MAKE THIS DOCUMENTATION CLEARER TODO: MAKE THIS DOCUMENTATION CLEARER
''' '''
interp_dict = {} interp_dict = {}
# if g_key in self.group_interpolation_ranges.keys():
# interp_range = self.group_interpolation_ranges[g_key]
# if start_idx in interp_range and end_idx in interp_range:
for g_key in self.group_interpolation_ranges.keys(): # for every group for g_key in self.group_interpolation_ranges.keys(): # for every group
interp_range = self.group_interpolation_ranges[g_key] # get interpolation range interp_range = self.group_interpolation_ranges[g_key] # get interpolation range
inkex.errormsg("\n\nwhat is interp range:{}".format(interp_range))
for i in range(len(interp_range) - 1): # go over interp wires in pairs for i in range(len(interp_range) - 1): # go over interp wires in pairs
start_idx = interp_range[i] # first wire index start_idx = interp_range[i] # first wire index
end_idx = interp_range[i+1] # second wire index end_idx = interp_range[i+1] # second wire index
@ -480,7 +384,9 @@ class InterpolationWires():
end_interp_wire = find_wire(g_key, end_idx) end_interp_wire = find_wire(g_key, end_idx)
start_interp_wire_points = [p for p in start_interp_wire.path.end_points] start_interp_wire_points = [p for p in start_interp_wire.path.end_points]
end_interp_wire_points = [p for p in end_interp_wire.path.end_points] end_interp_wire_points = [p for p in end_interp_wire.path.end_points]
inkex.errormsg("interp wire points: {} \n\n {}".format(start_interp_wire_points, end_interp_wire_points)) if len(start_interp_wire_points) != len(end_interp_wire_points):
inkex.errormsg("interpolation wires connecting the same groups must have the same number of points!")
return
num_wires = end_idx - start_idx + 1 num_wires = end_idx - start_idx + 1
# generate interpolation points between the two wires # generate interpolation points between the two wires
for point_idx in range(1, len(start_interp_wire_points) - 1): # exclude parts of interp wire that connect to sensor wire for point_idx in range(1, len(start_interp_wire_points) - 1): # exclude parts of interp wire that connect to sensor wire
@ -488,7 +394,7 @@ class InterpolationWires():
x2, y2 = end_interp_wire_points[point_idx].x, end_interp_wire_points[point_idx].y x2, y2 = end_interp_wire_points[point_idx].x, end_interp_wire_points[point_idx].y
line = [[x1, y1], [x2, y2]] line = [[x1, y1], [x2, y2]]
interp_dict[(x1, y1, x2, y2)] = [[x1, y1]] # map these points to the line connecting corresponding points interp_dict[(x1, y1, x2, y2)] = [[x1, y1]] # map these points to the line connecting corresponding points
interp_points = self.segment_line(line, num_wires - 2) # partition the line into num_wires parts interp_points = wire_util.segment_line(line, num_wires - 2) # partition the line into num_wires parts
interp_dict[(x1, y1, x2, y2)].extend(interp_points) interp_dict[(x1, y1, x2, y2)].extend(interp_points)
# we now have a dict of interpolation points, mapping each pair of points # we now have a dict of interpolation points, mapping each pair of points

Wyświetl plik

@ -7,6 +7,7 @@ from lxml import etree
import pyembroidery import pyembroidery
import math import math
from wiredb_proxy import WireDBProxy from wiredb_proxy import WireDBProxy
import wire_util
@ -49,9 +50,6 @@ class CreateCustomGridWorker():
self.upper_left, self.lower_left, self.upper_right, self.lower_right = self.compute_corners() self.upper_left, self.lower_left, self.upper_right, self.lower_right = self.compute_corners()
self.wiredb_proxy = WireDBProxy() self.wiredb_proxy = WireDBProxy()
def compute_euclidean_distance(self, x1, y1, x2, y2):
return math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
def compute_corners(self): def compute_corners(self):
''' '''
@ -64,7 +62,7 @@ class CreateCustomGridWorker():
upper_right, lower_right = sorted(left_arranged[2:], key = lambda p: p.y) upper_right, lower_right = sorted(left_arranged[2:], key = lambda p: p.y)
return upper_left, lower_left, upper_right, lower_right return upper_left, lower_left, upper_right, lower_right
def draw_corners(self): def draw_corners(self):
''' '''
Debugging tool to make sure correct side vectors are identified Debugging tool to make sure correct side vectors are identified
''' '''
@ -86,10 +84,10 @@ class CreateCustomGridWorker():
# self.draw_corners() # self.draw_corners()
if self.num_horizontal_wires != 0: if self.num_horizontal_wires != 0:
# look at left and right side, take shorter one to compute spacing # look at left and right side, take shorter one to compute spacing
left_side_distance = self.compute_euclidean_distance(self.upper_left.x, self.upper_left.y, left_side_distance = wire_util.compute_euclidean_distance(self.upper_left.x, self.upper_left.y,
self.lower_left.x, self.lower_left.y) self.lower_left.x, self.lower_left.y)
right_side_distance = self.compute_euclidean_distance(self.upper_right.x, self.upper_right.y, right_side_distance = wire_util.compute_euclidean_distance(self.upper_right.x, self.upper_right.y,
self.lower_right.x, self.lower_right.y) self.lower_right.x, self.lower_right.y)
min_height = min(left_side_distance, right_side_distance) min_height = min(left_side_distance, right_side_distance)
@ -102,14 +100,14 @@ class CreateCustomGridWorker():
number of wires or increase the size of the grid and try again.'''.format(MIN_GRID_SPACING, horizontal_wire_spacing)) number of wires or increase the size of the grid and try again.'''.format(MIN_GRID_SPACING, horizontal_wire_spacing))
return return
horizontal_wire_ids = self.lay_horizontal_wires(left_side_distance, right_side_distance) horizontal_wire_ids = self.lay_horizontal_wires()
self.wiredb_proxy.insert_new_wire_group(horizontal_wire_ids) self.wiredb_proxy.insert_new_wire_group(horizontal_wire_ids)
if self.num_vertical_wires != 0: if self.num_vertical_wires != 0:
top_side_distance = self.compute_euclidean_distance(self.upper_left.x, self.upper_left.y, top_side_distance = wire_util.compute_euclidean_distance(self.upper_left.x, self.upper_left.y,
self.upper_right.x, self.upper_right.y) self.upper_right.x, self.upper_right.y)
bottom_side_distance = self.compute_euclidean_distance(self.lower_left.x, self.lower_left.y, bottom_side_distance = wire_util.compute_euclidean_distance(self.lower_left.x, self.lower_left.y,
self.lower_right.x, self.lower_right.y) self.lower_right.x, self.lower_right.y)
min_width = min(top_side_distance, bottom_side_distance) min_width = min(top_side_distance, bottom_side_distance)
total_vertical_spacing = min_width / (self.num_vertical_wires + 1) total_vertical_spacing = min_width / (self.num_vertical_wires + 1)
@ -121,94 +119,41 @@ class CreateCustomGridWorker():
number of wires or increase the size of the grid and try again.'''.format(MIN_GRID_SPACING, vertical_wire_spacing)) number of wires or increase the size of the grid and try again.'''.format(MIN_GRID_SPACING, vertical_wire_spacing))
return return
vertical_wire_ids = self.lay_vertical_wires(top_side_distance, bottom_side_distance) vertical_wire_ids = self.lay_vertical_wires()
self.wiredb_proxy.insert_new_wire_group(vertical_wire_ids) self.wiredb_proxy.insert_new_wire_group(vertical_wire_ids)
def segment_line(self, line, line_distance, num_points): def lay_horizontal_wires(self):
'''
Breaks line into num_points equal parts
returns array of points
line: A shapely.LineString object (interpolation along line can be done manually but this is easier)
'''
points = []
def parameterize_line(t):
x_t = line[0][0] + (line[1][0] - line[0][0]) * t
y_t = line[0][1] + (line[1][1] - line[0][1]) * t
return x_t, y_t
segment_length = 1 / (num_points + 1)
for i in range(1 ,num_points+1): # adjust from 0 to n+1 bc we cant put in 0 to the parameterized line equation
x, y = parameterize_line(i * segment_length)
points.append([x,y])
return points
def lay_horizontal_wires(self, left_side_distance, right_side_distance):
left_line = [(self.upper_left.x, self.upper_left.y), (self.lower_left.x, self.lower_left.y)] left_line = [(self.upper_left.x, self.upper_left.y), (self.lower_left.x, self.lower_left.y)]
right_line = [(self.upper_right.x, self.upper_right.y), (self.lower_right.x, self.lower_right.y)] right_line = [(self.upper_right.x, self.upper_right.y), (self.lower_right.x, self.lower_right.y)]
left_side_points = self.segment_line(left_line, left_side_distance, self.num_horizontal_wires) left_side_points = wire_util.segment_line(left_line, self.num_horizontal_wires)
right_side_points = wire_util.segment_line(right_line, self.num_horizontal_wires)
right_side_points = self.segment_line(right_line, right_side_distance, self.num_horizontal_wires)
inkex.errormsg("\n\n num points lr:{} {}".format(len(left_side_points), len(right_side_points)))
return self.lay_wire(left_side_points, right_side_points, is_horizontal=True) return self.lay_wire(left_side_points, right_side_points, is_horizontal=True)
def lay_vertical_wires(self, top_side_distance, bottom_side_distance): def lay_vertical_wires(self):
top_line = [(self.upper_left.x, self.upper_left.y), (self.upper_right.x, self.upper_right.y)] top_line = [(self.upper_left.x, self.upper_left.y), (self.upper_right.x, self.upper_right.y)]
bottom_line = [(self.lower_left.x, self.lower_left.y), (self.lower_right.x, self.lower_right.y)] bottom_line = [(self.lower_left.x, self.lower_left.y), (self.lower_right.x, self.lower_right.y)]
top_side_points = self.segment_line(top_line, top_side_distance, self.num_vertical_wires) top_side_points = wire_util.segment_line(top_line, self.num_vertical_wires)
bottom_side_points = self.segment_line(bottom_line, bottom_side_distance, self.num_vertical_wires) bottom_side_points = wire_util.segment_line(bottom_line, self.num_vertical_wires)
return self.lay_wire(top_side_points, bottom_side_points, is_horizontal=False) return self.lay_wire(top_side_points, bottom_side_points, is_horizontal=False)
def lay_wire(self, wire1_points, wire2_points, is_horizontal): def lay_wire(self, wire1_points, wire2_points, is_horizontal):
points = []
wire_count = 0
wire1_idx = 0 wire1_idx = 0
wire2_idx = 0 wire2_idx = 0
wire_ids = [] wire_ids = []
while wire1_idx < len(wire1_points) and wire2_idx < len(wire2_points): while wire1_idx < len(wire1_points) and wire2_idx < len(wire2_points):
# if wire_count % 2 == 0: points = []
if wire1_idx < len(wire1_points): if wire1_idx < len(wire1_points):
points.append('{},{}'.format(wire1_points[wire1_idx][0], wire1_points[wire1_idx][1])) points.append('{},{}'.format(wire1_points[wire1_idx][0], wire1_points[wire1_idx][1]))
wire1_idx += 1 wire1_idx += 1
if wire2_idx < len(wire2_points): if wire2_idx < len(wire2_points):
points.append('{},{}'.format(wire2_points[wire2_idx][0], wire2_points[wire2_idx][1])) points.append('{},{}'.format(wire2_points[wire2_idx][0], wire2_points[wire2_idx][1]))
wire2_idx += 1 wire2_idx += 1
wire = self.create_path(points, is_horizontal) wire = wire_util.create_path(self.svg, points, is_horizontal)
wire_ids.append(wire.get_id()) wire_ids.append(wire.get_id())
points = []
# else:
# if wire2_idx < len(wire2_points):
# points.append('{},{}'.format(wire2_points[wire2_idx][0], wire2_points[wire2_idx][1]))
# wire2_idx += 1
# if wire1_idx < len(wire1_points):
# points.append('{},{}'.format(wire1_points[wire1_idx][0], wire1_points[wire1_idx][1]))
# wire1_idx += 1
inkex.errormsg("num wires generated:{} is horz:{}".format(len(wire_ids), is_horizontal)) inkex.errormsg("num wires generated:{} is horz:{}".format(len(wire_ids), is_horizontal))
return wire_ids return wire_ids
def create_path(self, points, is_horizontal):
'''
Creates a wire segment path given all of the points sequentially
'''
color = "red" if is_horizontal else "blue"
path_str = ' '.join(points)
path = inkex.Polyline(attrib={
'id': "wire_segment",
'points': path_str,
})
line_attribs = {
'style' : "stroke: %s; stroke-width: 0.4; fill: none; stroke-dasharray:0.4,0.4" % color,
'd': str(path.get_path())
# 'points': 'M 0,0 9,9 5,5'
}
elem = etree.SubElement(self.svg.get_current_layer(), inkex.addNS('path','svg'), line_attribs)
return elem
if __name__ == '__main__': if __name__ == '__main__':
CreateCustomGridEffect().run() CreateCustomGridEffect().run()

Wyświetl plik

@ -5,6 +5,9 @@ from lxml import etree
import pyembroidery import pyembroidery
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import random
from wiredb_proxy import WireDBProxy
import wire_util
MIN_GRID_SPACING = inkex.units.convert_unit(2.5, "mm") MIN_GRID_SPACING = inkex.units.convert_unit(2.5, "mm")
BBOX_SPACING = inkex.units.convert_unit(5, 'mm') BBOX_SPACING = inkex.units.convert_unit(5, 'mm')
@ -58,7 +61,7 @@ class CreateGridEffect(inkex.Effect):
units = "mm" if type(elem) == Rectangle else "px" units = "mm" if type(elem) == Rectangle else "px"
shape_points = [p for p in elem.path.end_points] shape_points = [p for p in elem.path.end_points]
bbox = elem.bounding_box() bbox = elem.bounding_box()
inkex.errormsg("shape points, bbox:{} , {}".format(shape_points, bbox)) inkex.errormsg("ID:{}".format(elem.get_id()))
rectangle = BoundingBoxMetadata(inkex.units.convert_unit(bbox.width, units), rectangle = BoundingBoxMetadata(inkex.units.convert_unit(bbox.width, units),
inkex.units.convert_unit(bbox.height, units), inkex.units.convert_unit(bbox.height, units),
inkex.units.convert_unit(bbox.top, units), inkex.units.convert_unit(bbox.top, units),
@ -78,12 +81,11 @@ class CreateGridWorker():
self.num_vertical_wires = num_vertical_wires self.num_vertical_wires = num_vertical_wires
self.svg = svg self.svg = svg
self.upper_left, self.upper_right,self.lower_left,self.lower_right = self.rectangle.get_rectangle_points() self.upper_left, self.upper_right,self.lower_left,self.lower_right = self.rectangle.get_rectangle_points()
self.wiredb_proxy = WireDBProxy()
def run(self): def run(self):
# check vertical and horizontal spacing # check vertical and horizontal spacing
horizontal_wire = None
vertical_wire = None
if self.num_horizontal_wires != 0: if self.num_horizontal_wires != 0:
total_horizontal_spacing = self.rectangle.height / (self.num_horizontal_wires + 1) total_horizontal_spacing = self.rectangle.height / (self.num_horizontal_wires + 1)
horizontal_wire_spacing = (self.rectangle.height - total_horizontal_spacing) / self.num_horizontal_wires horizontal_wire_spacing = (self.rectangle.height - total_horizontal_spacing) / self.num_horizontal_wires
@ -93,7 +95,9 @@ class CreateGridWorker():
They are currently {} mm apart. Either decrease the They are currently {} mm apart. Either decrease the
number of wires or increase the size of the grid and try again.'''.format(MIN_GRID_SPACING, horizontal_wire_spacing)) number of wires or increase the size of the grid and try again.'''.format(MIN_GRID_SPACING, horizontal_wire_spacing))
return return
horizontal_wire = self.lay_horizontal_wires(total_horizontal_spacing) horizontal_wire_ids = self.lay_horizontal_wires(total_horizontal_spacing)
self.wiredb_proxy.insert_new_wire_group(horizontal_wire_ids)
if self.num_vertical_wires != 0: if self.num_vertical_wires != 0:
total_vertical_spacing = self.rectangle.width / (self.num_vertical_wires + 1) total_vertical_spacing = self.rectangle.width / (self.num_vertical_wires + 1)
vertical_wire_spacing = (self.rectangle.width - total_vertical_spacing) / self.num_vertical_wires vertical_wire_spacing = (self.rectangle.width - total_vertical_spacing) / self.num_vertical_wires
@ -103,173 +107,45 @@ class CreateGridWorker():
They are currently {} mm apart. Either decrease the They are currently {} mm apart. Either decrease the
number of wires or increase the size of the grid and try again.'''.format(MIN_GRID_SPACING, vertical_wire_spacing)) number of wires or increase the size of the grid and try again.'''.format(MIN_GRID_SPACING, vertical_wire_spacing))
return return
vertical_wire = self.lay_vertical_wires(total_vertical_spacing) vertical_wire_ids = self.lay_vertical_wires(total_vertical_spacing)
self.wiredb_proxy.insert_new_wire_group(vertical_wire_ids)
# dynamic stitching stuff! # TODO: maybe combine these two functions
# stitch_worker = MakeStitchesWorker(horizontal_wire, vertical_wire)
# stitch_worker.make_horizontal_stitches()
def lay_horizontal_wires(self, horizontal_wire_spacing): def lay_horizontal_wires(self, horizontal_wire_spacing):
curr_point = list(self.lower_left) curr_point = list(self.lower_left)
wire_count = 0 wire_count = 0
points = [] points = []
wires = [] wires = []
wire_ids = []
while wire_count != self.num_horizontal_wires: while wire_count != self.num_horizontal_wires:
curr_point[1] -= horizontal_wire_spacing curr_point[1] -= horizontal_wire_spacing
# if wire_count % 2 == 0: # if wire_count % 2 == 0:
points.append('{},{}'.format(self.rectangle.left - BBOX_SPACING, curr_point[1])) points.append('{},{}'.format(self.rectangle.left - BBOX_SPACING, curr_point[1]))
points.append('{},{}'.format(self.rectangle.right, curr_point[1])) points.append('{},{}'.format(self.rectangle.right, curr_point[1]))
w = self.create_path(points, is_horizontal=True) elem = wire_util.create_path(self.svg, points, is_horizontal=True)
wires.append(w) wires.append(elem)
wire_ids.append(elem.get_id())
points = [] points = []
# else:
# points.append('{},{}'.format(self.rectangle.right, curr_point[1]))
# points.append('{},{}'.format(self.rectangle.left - BBOX_SPACING, curr_point[1]))
wire_count += 1 wire_count += 1
# return self.create_path(points, is_horizontal=True) return wire_ids
return wires
def lay_vertical_wires(self, vertical_wire_spacing): def lay_vertical_wires(self, vertical_wire_spacing):
curr_point = list(self.upper_left) curr_point = list(self.upper_left)
wire_count = 0 wire_count = 0
points = [] points = []
wires = [] wires = []
wire_ids = []
while wire_count != self.num_vertical_wires: while wire_count != self.num_vertical_wires:
curr_point[0] += vertical_wire_spacing curr_point[0] += vertical_wire_spacing
# if wire_count % 2 == 0:
points.append('{},{}'.format(curr_point[0], self.rectangle.top - BBOX_SPACING)) points.append('{},{}'.format(curr_point[0], self.rectangle.top - BBOX_SPACING))
points.append('{},{}'.format(curr_point[0], self.rectangle.bottom)) points.append('{},{}'.format(curr_point[0], self.rectangle.bottom))
wires.append(self.create_path(points, is_horizontal=False)) elem = wire_util.create_path(self.svg, points, is_horizontal=False)
wires.append(elem)
wire_ids.append(elem.get_id())
points = [] points = []
# else:
# points.append('{},{}'.format(curr_point[0], self.rectangle.bottom))
# points.append('{},{}'.format(curr_point[0], self.rectangle.top - BBOX_SPACING))
wire_count += 1 wire_count += 1
return wires return wire_ids
def create_path(self, points, is_horizontal):
'''
Creates a wire segment path given all of the points sequentially
'''
color = "red" if is_horizontal else "blue"
path_str = ' '.join(points)
path = inkex.Polyline(attrib={
'id': "wire_segment",
'points': path_str,
})
line_attribs = {
'style' : "stroke: %s; stroke-width: 0.4; fill: none; stroke-dasharray:0.4,0.4" % color,
'd': str(path.get_path())
# 'points': 'M 0,0 9,9 5,5'
}
etree.SubElement(self.svg.get_current_layer(), inkex.addNS('path','svg'), line_attribs)
return path
class MakeStitchesWorker():
def __init__(self, horizontal_wire, vertical_wire):
self.horizontal_wire_points = sorted([p for p in horizontal_wire.get_path().end_points], key=lambda p: -p[1])
self.vertical_wire = [p for p in vertical_wire.get_path().end_points]
self.stitch_points = []
def make_horizontal_stitches(self):
unique_x_values = set([p.x for p in self.vertical_wire])
pattern = pyembroidery.EmbPattern()
# add stitches at end points
# for p in self.horizontal_wire_points:
# pattern.add_stitch_absolute(pyembroidery.STITCH, p.x, p.y)
stitch_array = []
inkex.errormsg("HORZ WIRE PTS:{}".format(self.horizontal_wire_points))
for i in range(0, len(self.horizontal_wire_points) - 1, 2):
row_stitch_array = []
p0 = self.horizontal_wire_points[i]
p1 = self.horizontal_wire_points[i+1]
row_stitch_array.append([p0.x, p0.y])
row_stitch_array.append([p1.x,p1.y])
intersection_points = []
if all([p0.x < x < p1.x] for x in unique_x_values):
for x_i in unique_x_values:
intersection_points.append([x_i, p0.y])
intersection_points = sorted(intersection_points, key = lambda p: p[0])
point_idx = 0
if p0.x < p1.x: #p0 is on the right
row_stitch_array.append([(p0.x + intersection_points[point_idx][0]) // 2, p0.y])
row_stitch_array.append([(p1.x + intersection_points[-1][0]) // 2, p1.y])
else:
row_stitch_array.append([(p0.x + intersection_points[-1][0]) // 2, p0.y])
row_stitch_array.append([(p1.x + intersection_points[0][0]) // 2, p1.y])
inkex.errormsg("first and last endpoint x values: {} and {}".format(p0.x, p1.x))
inkex.errormsg("first and last x values:{} and {}".format(intersection_points[point_idx][0], intersection_points[-1][0]))
while point_idx < len(intersection_points)-1:
mid_x = (intersection_points[point_idx][0] + intersection_points[point_idx+1][0]) // 2
point_idx += 1
row_stitch_array.append([mid_x, p0.y])
# need to stitch wire continously from bottom left to top right, so row_stitch array is reversed
# depending on what side of the wire we started on for this iteration
if p0.x < p1.x: #left to right
row_stitch_array = sorted(row_stitch_array, key= lambda p: p[0])
else: # right to left
row_stitch_array = sorted(row_stitch_array, key= lambda p: p[0], reverse=True)
# add to stitch array
stitch_array.extend(row_stitch_array)
# add actual stitches now that the stitch points are in the order we want them to be in
for x, y in stitch_array:
pattern.add_stitch_absolute(pyembroidery.STITCH, x, y)
pyembroidery.write_pes(pattern, '/Users/hdacosta/Desktop/UROP/output/pattern.dst')
# sanity_check
# inkex.errormsg("num intersections:{}".format(len(intersection_points)))
# self.visualize_stitches(pattern)
def visualize_stitches(self, pattern):
#visualize stitches
stitch_info = np.asarray(pattern.stitches)
#Extract info from np.array and convert to mm
x_coord = stitch_info[:,0]/10
y_coord = stitch_info[:,1]/10
num_of_stitches = len(x_coord)
#Plot the stitches
stitch_loc = plt.scatter(x_coord, y_coord, s = 1, c = 'black')
#Add label to every ith stitch
i = 0
while i <= num_of_stitches - 1:
plt.annotate(i, (x_coord[i], y_coord[i]))
i += 1
#label axis
plt.title("Stitch Vis")
plt.xlabel('X Coordinates (mm)')
plt.ylabel('Y Coordinates (mm)')
#show the plot
plt.show()
def make_vertical_stitches(self):
pass
if __name__ == '__main__': if __name__ == '__main__':
CreateGridEffect().run() CreateGridEffect().run()

Wyświetl plik

@ -6,9 +6,15 @@ import numpy as np
from matplotlib import pyplot as plt from matplotlib import pyplot as plt
from lxml import etree from lxml import etree
import math import math
from bezier import Curve from bezier import Curve # TODO: giving some binary issues! CRASHING PYTHON
'''
ValueError: numpy.ndarray size changed, may indicate binary incompatibility.
Expected 88 from C header, got 80 from PyObject
'''
import simplepath import simplepath
import js2py import wire_util
class MakeStitchesEffect(inkex.Effect): class MakeStitchesEffect(inkex.Effect):
def add_arguments(self, pars): def add_arguments(self, pars):
@ -29,36 +35,15 @@ class MakeStitchesEffect(inkex.Effect):
# debugging for mapping out control and end points of a path # debugging for mapping out control and end points of a path
# poi = [p for p in wire.path.end_points] # poi = [p for p in wire.path.end_points]
# points = ['{},{}'.format(p.x,p.y) for p in poi] # points = ['{},{}'.format(p.x,p.y) for p in poi]
# self.create_path(points, True) # wire_util.create_path(self.svg, points, True)
# poi = [p for p in wire.path.control_points] # poi = [p for p in wire.path.control_points]
# points = ['{},{}'.format(p.x,p.y) for p in poi] # points = ['{},{}'.format(p.x,p.y) for p in poi]
# self.create_path(points, False) # wire_util.create_path(self.svg, points, False)
is_curve = True if args.wire_type == 1 else False is_curve = True if args.wire_type == 1 else False
make_stitches_worker = MakeStitchesWorker(wires, is_curve, args.file_name, args.dst_folder) make_stitches_worker = MakeStitchesWorker(wires, is_curve, args.file_name, args.dst_folder)
inkex.errormsg("what is file path:{}".format(args.dst_folder)) inkex.errormsg("what is file path:{}".format(args.dst_folder))
make_stitches_worker.run() make_stitches_worker.run()
def create_path(self, points, is_horizontal):
'''
Creates a wire segment path given all of the points sequentially
'''
color = "red" if is_horizontal else "blue"
path_str = ' '.join(points)
path = inkex.Polyline(attrib={
'id': "wire_segment",
'points': path_str,
})
line_attribs = {
'style' : "stroke: %s; stroke-width: 0.4; fill: none; stroke-dasharray:0.4,0.4" % color,
'd': str(path.get_path())
# 'points': 'M 0,0 9,9 5,5'
}
etree.SubElement(self.svg.get_current_layer(), inkex.addNS('path','svg'), line_attribs)
return path
class MakeStitchesWorker(inkex.Effect): class MakeStitchesWorker(inkex.Effect):
def __init__(self, wires, is_curve, filename, dst_folder): def __init__(self, wires, is_curve, filename, dst_folder):
@ -122,28 +107,6 @@ class MakeStitchesWorker(inkex.Effect):
all_curves.append(stitch_points) all_curves.append(stitch_points)
return all_curves return all_curves
def compute_euclidean_distance(self, x1, y1, x2, y2):
return math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
def segment_line(self, line, num_points):
'''
Breaks line into num_points equal parts
returns array of points
line: A shapely.LineString object (interpolation along line can be done manually but this is easier)
'''
points = []
def parameterize_line(t):
x_t = line[0][0] + (line[1][0] - line[0][0]) * t
y_t = line[0][1] + (line[1][1] - line[0][1]) * t
return x_t, y_t
segment_length = 1 / (num_points + 1)
for i in range(1 ,num_points+2): # adjust from 0 to n+1 bc we cant put in 0 to the parameterized line equation
x, y = parameterize_line(i * segment_length)
points.append([x,y])
return points
def stitch_segment(self): def stitch_segment(self):
stitch_points = [] stitch_points = []
@ -155,18 +118,14 @@ class MakeStitchesWorker(inkex.Effect):
# stitch_points.append([p1.x, p1.y]) # stitch_points.append([p1.x, p1.y])
line = [[p1.x, p1.y], [p2.x, p2.y]] line = [[p1.x, p1.y], [p2.x, p2.y]]
num_points = 3 # could make this a user input somehow? num_points = 3 # could make this a user input somehow?
line_points = [[p1.x, p1.y]] + self.segment_line(line, num_points) line_points = [[p1.x, p1.y]] + wire_util.segment_line(line, num_points)
if count % 2 == 1: if count % 2 == 1:
line_points = line_points[::-1] line_points = line_points[::-1]
stitch_points.append(line_points) stitch_points.append(line_points)
count += 1 count += 1
inkex.errormsg(stitch_points)
return stitch_points return stitch_points
def make_stitches(self, stitch_group): def make_stitches(self, stitch_group):
pattern = pyembroidery.EmbPattern() pattern = pyembroidery.EmbPattern()
for stitch_points in stitch_group: for stitch_points in stitch_group:
@ -190,7 +149,7 @@ class MakeStitchesWorker(inkex.Effect):
i = 0 i = 0
while i <= num_of_stitches - 1: while i <= num_of_stitches - 1:
plt.annotate(i, (x_coord[i], y_coord[i])) plt.annotate(i, (x_coord[i], y_coord[i]))
i += 1 i += 10
#label axis #label axis
plt.title("Stitch Vis") plt.title("Stitch Vis")

Wyświetl plik

@ -0,0 +1,48 @@
import inkex
from lxml import etree
import math
def create_path(svg, points, is_horizontal):
'''
Creates a wire segment path given all of the points sequentially
'''
color = "red" if is_horizontal else "blue"
path_str = ' '.join(points)
path = inkex.Polyline(attrib={
'id': "wire_segment",
'points': path_str,
})
line_attribs = {
'style' : "stroke: %s; stroke-width: 0.4; fill: none; stroke-dasharray:0.4,0.4" % color,
'd': str(path.get_path())
# 'points': 'M 0,0 9,9 5,5'
}
elem = etree.SubElement(svg.get_current_layer(), inkex.addNS('path','svg'), line_attribs)
return elem
def compute_euclidean_distance(x1, y1, x2, y2):
return math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
def segment_line(line, num_points):
'''
Breaks line into num_points equal parts
returns array of points
'''
points = []
def parameterize_line(t):
x_t = line[0][0] + (line[1][0] - line[0][0]) * t
y_t = line[0][1] + (line[1][1] - line[0][1]) * t
return x_t, y_t
segment_length = 1 / (num_points + 1)
for i in range(1 ,num_points+1): # adjust from 0 to n+1 bc we cant put in 0 to the parameterized line equation
x, y = parameterize_line(i * segment_length)
points.append([x,y])
return points