Reduce PEP 8 warning and remove unused dependecies

This commit is contained in:
Padlex
2020-05-02 17:43:12 +02:00
parent 8b3937cd28
commit 616566295d

394
laser.py
View File

@@ -25,25 +25,23 @@ You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" """
import inkex, simplestyle, simplepath import inkex
import cubicsuperpath, simpletransform, bezmisc import simplestyle
import cubicsuperpath
import simpletransform
import os import os
import math import math
import bezmisc import bezmisc
import re import re
import copy
import sys import sys
import time import time
import cmath
import numpy import numpy
import codecs
import random
import gettext import gettext
_ = gettext.gettext _ = gettext.gettext
### Check if inkex has errormsg (0.46 version doesnot have one.) Could be removed later. # Check if inkex has error messages. (0.46 version does not have one) Could be removed later.
if "errormsg" not in dir(inkex): if "errormsg" not in dir(inkex):
inkex.errormsg = lambda msg: sys.stderr.write((unicode(msg) + "\n").encode("UTF-8")) inkex.errormsg = lambda msg: sys.stderr.write((unicode(msg) + "\n").encode("UTF-8"))
@@ -69,13 +67,10 @@ def bezierslopeatt(((bx0, by0), (bx1, by1), (bx2, by2), (bx3, by3)), t):
bezmisc.bezierslopeatt = bezierslopeatt bezmisc.bezierslopeatt = bezierslopeatt
################################################################################ ################################################################################
### #
### Styles and additional parameters # Styles and additional parameters
### #
################################################################################ ################################################################################
math.pi2 = math.pi * 2 math.pi2 = math.pi * 2
@@ -189,27 +184,13 @@ styles = {
################################################################################ ################################################################################
### Cubic Super Path additional functions # Cubic Super Path additional functions
################################################################################ ################################################################################
def csp_segment_to_bez(sp1, sp2): def csp_segment_to_bez(sp1, sp2):
return sp1[1:] + sp2[:2] return sp1[1:] + sp2[:2]
# draw_pointer( list(csp_at_t(csp1[dist[1]][dist[2]-1],csp1[dist[1]][dist[2]],dist[3]))
# + list(csp_at_t(csp2[dist[4]][dist[5]-1],csp2[dist[4]][dist[5]],dist[6])), "#507","line")
def csp_split(sp1, sp2, t=.5): def csp_split(sp1, sp2, t=.5):
[x1, y1], [x2, y2], [x3, y3], [x4, y4] = sp1[1], sp1[2], sp2[0], sp2[1] [x1, y1], [x2, y2], [x3, y3], [x4, y4] = sp1[1], sp1[2], sp2[0], sp2[1]
x12 = x1 + (x2 - x1) * t x12 = x1 + (x2 - x1) * t
@@ -227,23 +208,6 @@ def csp_split(sp1, sp2, t=.5):
return [sp1[0], sp1[1], [x12, y12]], [[x1223, y1223], [x, y], [x2334, y2334]], [[x34, y34], sp2[1], sp2[2]] return [sp1[0], sp1[1], [x12, y12]], [[x1223, y1223], [x, y], [x2334, y2334]], [[x34, y34], sp2[1], sp2[2]]
############################################################################
### csp_segments_intersection(sp1,sp2,sp3,sp4)
###
### Returns array containig all intersections between two segmets of cubic
### super path. Results are [ta,tb], or [ta0, ta1, tb0, tb1, "Overlap"]
### where ta, tb are values of t for the intersection point.
############################################################################
def csp_curvature_at_t(sp1, sp2, t, depth=3): def csp_curvature_at_t(sp1, sp2, t, depth=3):
ax, ay, bx, by, cx, cy, dx, dy = bezmisc.bezierparameterize(csp_segment_to_bez(sp1, sp2)) ax, ay, bx, by, cx, cy, dx, dy = bezmisc.bezierparameterize(csp_segment_to_bez(sp1, sp2))
@@ -273,12 +237,6 @@ def csp_curvature_at_t(sp1, sp2, t, depth=3):
return 1e100 return 1e100
def csp_at_t(sp1, sp2, t): def csp_at_t(sp1, sp2, t):
ax, bx, cx, dx = sp1[1][0], sp1[2][0], sp2[0][0], sp2[1][0] ax, bx, cx, dx = sp1[1][0], sp1[2][0], sp2[0][0], sp2[1][0]
ay, by, cy, dy = sp1[1][1], sp1[2][1], sp2[0][1], sp2[1][1] ay, by, cy, dy = sp1[1][1], sp1[2][1], sp2[0][1], sp2[1][1]
@@ -294,27 +252,13 @@ def csp_at_t(sp1, sp2, t):
return [x, y] return [x, y]
def cspseglength(sp1, sp2, tolerance=0.001): def cspseglength(sp1, sp2, tolerance=0.001):
bez = (sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:]) bez = (sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:])
return bezmisc.bezierlength(bez, tolerance) return bezmisc.bezierlength(bez, tolerance)
# Distance calculation from point to arc
def point_to_arc_distance(p, arc): def point_to_arc_distance(p, arc):
### Distance calculattion from point to arc
P0, P2, c, a = arc P0, P2, c, a = arc
dist = None dist = None
p = P(p) p = P(p)
@@ -352,102 +296,10 @@ def csp_to_arc_distance(sp1, sp2, arc1, arc2, tolerance=0.01): # arc = [start,e
return d1[0] return d1[0]
################################################################################ ################################################################################
### Bezier additional functions # Common functions
################################################################################ ################################################################################
################################################################################
### Some vector functions
################################################################################
################################################################################
### Common functions
################################################################################
def atan2(*arg): def atan2(*arg):
if len(arg) == 1 and (type(arg[0]) == type([0., 0.]) or type(arg[0]) == type((0., 0.))): if len(arg) == 1 and (type(arg[0]) == type([0., 0.]) or type(arg[0]) == type((0., 0.))):
return (math.pi / 2 - math.atan2(arg[0][0], arg[0][1])) % math.pi2 return (math.pi / 2 - math.atan2(arg[0][0], arg[0][1])) % math.pi2
@@ -458,26 +310,11 @@ def atan2(*arg):
raise ValueError, "Bad argumets for atan! (%s)" % arg raise ValueError, "Bad argumets for atan! (%s)" % arg
def between(c, x, y): def between(c, x, y):
return x - straight_tolerance <= c <= y + straight_tolerance or y - straight_tolerance <= c <= x + straight_tolerance return x - straight_tolerance <= c <= y + straight_tolerance or y - straight_tolerance <= c <= x + straight_tolerance
# Print arguments into specified log file
################################################################################
### print_ prints any arguments into specified log file
################################################################################
def print_(*arg): def print_(*arg):
f = open(options.log_filename, "a") f = open(options.log_filename, "a")
for s in arg: for s in arg:
@@ -488,8 +325,9 @@ def print_(*arg):
################################################################################ ################################################################################
### Point (x,y) operations # Point (x,y) operations
################################################################################ ################################################################################
class P: class P:
def __init__(self, x, y=None): def __init__(self, x, y=None):
if not y == None: if not y == None:
@@ -526,39 +364,23 @@ class P:
else: else:
return P(0, 0) return P(0, 0)
def angle(self): def angle(self):
return math.atan2(self.y, self.x) return math.atan2(self.y, self.x)
def __repr__(self): def __repr__(self):
return '%f,%f' % (self.x, self.y) return '%f,%f' % (self.x, self.y)
def l2(self): def l2(self):
return self.x * self.x + self.y * self.y return self.x * self.x + self.y * self.y
################################################################################ ################################################################################
### #
### Offset function # Biarc function
### #
### This function offsets given cubic super path. # Calculates biarc approximation of cubic super path segment
### It's based on src/livarot/PathOutline.cpp from Inkscape's source code. # splits segment if needed or approximates it with straight line
### #
###
################################################################################
################################################################################
###
### Biarc function
###
### Calculates biarc approximation of cubic super path segment
### splits segment if needed or approximates it with straight line
###
################################################################################ ################################################################################
def biarc(sp1, sp2, z1, z2, depth=0): def biarc(sp1, sp2, z1, z2, depth=0):
def biarc_split(sp1, sp2, z1, z2, depth): def biarc_split(sp1, sp2, z1, z2, depth):
@@ -656,34 +478,13 @@ def biarc(sp1, sp2, z1, z2, depth=0):
[[P2.x, P2.y], 'arc', [R2.x, R2.y], a2, [P4.x, P4.y], [zm, z2]]] [[P2.x, P2.y], 'arc', [R2.x, R2.y], a2, [P4.x, P4.y], [zm, z2]]]
################################################################################ ################################################################################
### Polygon class # Polygon class
################################################################################ ################################################################################
class Polygon: class Polygon:
def __init__(self, polygon=None): def __init__(self, polygon=None):
self.polygon = [] if polygon == None else polygon[:] self.polygon = [] if polygon == None else polygon[:]
def add(self, add): def add(self, add):
if type(add) == type([]): if type(add) == type([]):
self.polygon += add[:] self.polygon += add[:]
@@ -691,11 +492,7 @@ class Polygon:
self.polygon += add.polygon[:] self.polygon += add.polygon[:]
class ArrangementGenetic:
class Arangement_Genetic:
# gene = [fittness, order, rotation, xposition] # gene = [fittness, order, rotation, xposition]
# spieces = [gene]*shapes count # spieces = [gene]*shapes count
# population = [spieces] # population = [spieces]
@@ -709,26 +506,13 @@ class Arangement_Genetic:
self.move_mutate_factor = 1. self.move_mutate_factor = 1.
################################################################################ ################################################################################
### ###
### Gcodetools class ### Gcodetools class
### ###
################################################################################ ################################################################################
class laser_gcode(inkex.Effect): class LaserGcode(inkex.Effect):
def export_gcode(self, gcode): def export_gcode(self, gcode):
gcode_pass = gcode gcode_pass = gcode
@@ -736,49 +520,69 @@ class laser_gcode(inkex.Effect):
gcode += "G91\nG1 Z-" + self.options.pass_depth + "\nG90\n" + gcode_pass gcode += "G91\nG1 Z-" + self.options.pass_depth + "\nG90\n" + gcode_pass
f = open(self.options.directory + self.options.file, "w") f = open(self.options.directory + self.options.file, "w")
f.write( f.write(
self.options.laser_off_command + " S0" + "\n" + self.header + "G1 F" + self.options.travel_speed + "\n" + gcode + self.footer) self.options.laser_off_command + " S0" + "\n" + self.header +
"G1 F" + self.options.travel_speed + "\n" + gcode + self.footer)
f.close() f.close()
def __init__(self): def __init__(self):
inkex.Effect.__init__(self) inkex.Effect.__init__(self)
self.OptionParser.add_option("-d", "--directory", action="store", type="string", dest="directory", default="", add_option = self.OptionParser.add_option
add_option("-d", "--directory", action="store", type="string", dest="directory", default="",
help="Output directory") help="Output directory")
self.OptionParser.add_option("-f", "--filename", action="store", type="string", dest="file",
add_option("-f", "--filename", action="store", type="string", dest="file",
default="output.gcode", help="File name") default="output.gcode", help="File name")
self.OptionParser.add_option("", "--add-numeric-suffix-to-filename", action="store", type="inkbool",
add_option("", "--add-numeric-suffix-to-filename", action="store", type="inkbool",
dest="add_numeric_suffix_to_filename", default=False, dest="add_numeric_suffix_to_filename", default=False,
help="Add numeric suffix to file name") help="Add numeric suffix to file name")
self.OptionParser.add_option("", "--laser-command", action="store", type="string", dest="laser_command",
add_option("", "--laser-command", action="store", type="string", dest="laser_command",
default="M03", help="Laser gcode command") default="M03", help="Laser gcode command")
self.OptionParser.add_option("", "--laser-off-command", action="store", type="string", dest="laser_off_command",
add_option("", "--laser-off-command", action="store", type="string", dest="laser_off_command",
default="M05", help="Laser gcode end command") default="M05", help="Laser gcode end command")
self.OptionParser.add_option("", "--laser-speed", action="store", type="int", dest="laser_speed", default="750",
add_option("", "--laser-speed", action="store", type="int", dest="laser_speed", default="750",
help="Laser speed (mm/min)") help="Laser speed (mm/min)")
self.OptionParser.add_option("", "--travel-speed", action="store", type="string", dest="travel_speed",
add_option("", "--travel-speed", action="store", type="string", dest="travel_speed",
default="3000", help="Travel speed (mm/min)") default="3000", help="Travel speed (mm/min)")
self.OptionParser.add_option("", "--laser-power", action="store", type="int", dest="laser_power", default="255",
add_option("", "--laser-power", action="store", type="int", dest="laser_power", default="255",
help="S# is 256 or 10000 for full power") help="S# is 256 or 10000 for full power")
self.OptionParser.add_option("", "--passes", action="store", type="int", dest="passes", default="1",
add_option("", "--passes", action="store", type="int", dest="passes", default="1",
help="Quantity of passes") help="Quantity of passes")
self.OptionParser.add_option("", "--pass-depth", action="store", type="string", dest="pass_depth", default="1",
add_option("", "--pass-depth", action="store", type="string", dest="pass_depth", default="1",
help="Depth of laser cut") help="Depth of laser cut")
self.OptionParser.add_option("", "--power-delay", action="store", type="string", dest="power_delay",
add_option("", "--power-delay", action="store", type="string", dest="power_delay",
default="0", help="Laser power-on delay (ms)") default="0", help="Laser power-on delay (ms)")
self.OptionParser.add_option("", "--suppress-all-messages", action="store", type="inkbool",
add_option("", "--suppress-all-messages", action="store", type="inkbool",
dest="suppress_all_messages", default=True, dest="suppress_all_messages", default=True,
help="Hide messages during g-code generation") help="Hide messages during g-code generation")
self.OptionParser.add_option("", "--create-log", action="store", type="inkbool", dest="log_create_log",
add_option("", "--create-log", action="store", type="inkbool", dest="log_create_log",
default=False, help="Create log files") default=False, help="Create log files")
self.OptionParser.add_option("", "--log-filename", action="store", type="string", dest="log_filename",
add_option("", "--log-filename", action="store", type="string", dest="log_filename",
default='', help="Create log files") default='', help="Create log files")
self.OptionParser.add_option("", "--engraving-draw-calculation-paths", action="store", type="inkbool",
add_option("", "--engraving-draw-calculation-paths", action="store", type="inkbool",
dest="engraving_draw_calculation_paths", default=False, dest="engraving_draw_calculation_paths", default=False,
help="Draw additional graphics to debug engraving path") help="Draw additional graphics to debug engraving path")
self.OptionParser.add_option("", "--unit", action="store", type="string", dest="unit",
add_option("", "--unit", action="store", type="string", dest="unit",
default="G21 (All units in mm)", help="Units either mm or inches") default="G21 (All units in mm)", help="Units either mm or inches")
self.OptionParser.add_option("", "--active-tab", action="store", type="string", dest="active_tab", default="",
add_option("", "--active-tab", action="store", type="string", dest="active_tab", default="",
help="Defines which tab is active") help="Defines which tab is active")
self.OptionParser.add_option("", "--biarc-max-split-depth", action="store", type="int",
add_option("", "--biarc-max-split-depth", action="store", type="int",
dest="biarc_max_split_depth", default="4", dest="biarc_max_split_depth", default="4",
help="Defines maximum depth of splitting while approximating using biarcs.") help="Defines maximum depth of splitting while approximating using biarcs.")
@@ -788,7 +592,7 @@ class laser_gcode(inkex.Effect):
return [] return []
p = self.transform_csp(p, layer) p = self.transform_csp(p, layer)
### Sort to reduce Rapid distance # Sort to reduce Rapid distance
k = range(1, len(p)) k = range(1, len(p))
keys = [0] keys = [0]
while len(k) > 0: while len(k) > 0:
@@ -812,11 +616,10 @@ class laser_gcode(inkex.Effect):
print_("Curve: " + str(c)) print_("Curve: " + str(c))
return c return c
def draw_curve(self, curve, layer, group=None, style=styles["biarc_style"]): def draw_curve(self, curve, layer, group=None, style=styles["biarc_style"]):
self.get_defs() self.get_defs()
# Add marker to defs if it doesnot exists # Add marker to defs if it does not exist
if "DrawCurveMarker" not in self.defs: if "DrawCurveMarker" not in self.defs:
defs = inkex.etree.SubElement(self.document.getroot(), inkex.addNS("defs", "svg")) defs = inkex.etree.SubElement(self.document.getroot(), inkex.addNS("defs", "svg"))
marker = inkex.etree.SubElement(defs, inkex.addNS("marker", "svg"), marker = inkex.etree.SubElement(defs, inkex.addNS("marker", "svg"),
@@ -843,7 +646,7 @@ class laser_gcode(inkex.Effect):
del (style['biarc%s_r' % i]["marker-end"]) del (style['biarc%s_r' % i]["marker-end"])
style['biarc%s_r' % i] = simplestyle.formatStyle(style['biarc%s_r' % i]) style['biarc%s_r' % i] = simplestyle.formatStyle(style['biarc%s_r' % i])
if group == None: if group is None:
group = inkex.etree.SubElement(self.layers[min(1, len(self.layers) - 1)], inkex.addNS('g', 'svg'), group = inkex.etree.SubElement(self.layers[min(1, len(self.layers) - 1)], inkex.addNS('g', 'svg'),
{"gcodetools": "Preview group"}) {"gcodetools": "Preview group"})
s, arcn = '', 0 s, arcn = '', 0
@@ -965,13 +768,14 @@ class laser_gcode(inkex.Effect):
################################################################################ ################################################################################
### #
### Generate Gcode # Generate Gcode
### Generates Gcode on given curve. #
### # Curve definition
### Crve defenitnion [start point, type = {'arc','line','move','end'}, arc center, arc angle, end point, [zstart, zend]] # [start point, type = {'arc','line','move','end'}, arc center, arc angle, end point, [zstart, zend]]
### #
################################################################################ ################################################################################
def generate_gcode(self, curve, layer, depth): def generate_gcode(self, curve, layer, depth):
tool = self.tools tool = self.tools
print_("Tool in g-code generator: " + str(tool)) print_("Tool in g-code generator: " + str(tool))
@@ -1125,8 +929,7 @@ class laser_gcode(inkex.Effect):
print_(self.transform_matrix) print_(self.transform_matrix)
print_(self.transform_matrix_reverse) print_(self.transform_matrix_reverse)
###self.Zauto_scale[layer] = math.sqrt( (self.transform_matrix[layer][0][0]**2 + self.transform_matrix[layer][1][1]**2)/2 ) # Zautoscale is absolute
### Zautoscale is absolete
self.Zauto_scale[layer] = 1 self.Zauto_scale[layer] = 1
print_("Z automatic scale = %s (computed according orientation points)" % self.Zauto_scale[layer]) print_("Z automatic scale = %s (computed according orientation points)" % self.Zauto_scale[layer])
@@ -1147,13 +950,12 @@ class laser_gcode(inkex.Effect):
csp[i][j][k] = self.transform(csp[i][j][k], layer, reverse) csp[i][j][k] = self.transform(csp[i][j][k], layer, reverse)
return csp return csp
################################################################################ ################################################################################
### Errors handling function, notes are just printed into Logfile, # Errors handling function, notes are just printed into Logfile,
### warnings are printed into log file and warning message is displayed but # warnings are printed into log file and warning message is displayed but
### extension continues working, errors causes log and execution is halted # extension continues working, errors causes log and execution is halted
### Notes, warnings adn errors could be assigned to space or comma or dot # Notes, warnings adn errors could be assigned to space or comma or dot
### sepparated strings (case is ignoreg). # sepparated strings (case is ignoreg).
################################################################################ ################################################################################
def error(self, s, type_="Warning"): def error(self, s, type_="Warning"):
notes = "Note " notes = "Note "
@@ -1192,9 +994,8 @@ class laser_gcode(inkex.Effect):
inkex.errormsg(s) inkex.errormsg(s)
sys.exit() sys.exit()
################################################################################ ################################################################################
### Get defs from svg # Get defs from svg
################################################################################ ################################################################################
def get_defs(self): def get_defs(self):
self.defs = {} self.defs = {}
@@ -1211,9 +1012,9 @@ class laser_gcode(inkex.Effect):
################################################################################ ################################################################################
### #
### Get Gcodetools info from the svg # Get Gcodetools info from the svg
### #
################################################################################ ################################################################################
def get_info(self): def get_info(self):
self.selected_paths = {} self.selected_paths = {}
@@ -1261,7 +1062,6 @@ class laser_gcode(inkex.Effect):
recursive_search(self.document.getroot(), self.document.getroot()) recursive_search(self.document.getroot(), self.document.getroot())
def get_orientation_points(self, g): def get_orientation_points(self, g):
items = g.getchildren() items = g.getchildren()
items.reverse() items.reverse()
@@ -1295,9 +1095,9 @@ class laser_gcode(inkex.Effect):
return None return None
################################################################################ ################################################################################
### #
### dxfpoints # dxfpoints
### #
################################################################################ ################################################################################
def dxfpoints(self): def dxfpoints(self):
if self.selected_paths == {}: if self.selected_paths == {}:
@@ -1324,9 +1124,9 @@ class laser_gcode(inkex.Effect):
path.set("dxfpoint", "0") path.set("dxfpoint", "0")
################################################################################ ################################################################################
### #
### Laser # Laser
### #
################################################################################ ################################################################################
def laser(self): def laser(self):
@@ -1455,9 +1255,9 @@ class laser_gcode(inkex.Effect):
self.export_gcode(gcode) self.export_gcode(gcode)
################################################################################ ################################################################################
### #
### Orientation # Orientation
### #
################################################################################ ################################################################################
def orientation(self, layer=None): def orientation(self, layer=None):
print_("entering orientations") print_("entering orientations")
@@ -1524,11 +1324,11 @@ class laser_gcode(inkex.Effect):
################################################################################ ################################################################################
### #
### Effect # Effect
### #
### Main function of Gcodetools class # Main function of Gcodetools class
### #
################################################################################ ################################################################################
def effect(self): def effect(self):
global options global options
@@ -1572,5 +1372,5 @@ class laser_gcode(inkex.Effect):
self.laser() self.laser()
e = laser_gcode() e = LaserGcode()
e.affect() e.affect()