-
Notifications
You must be signed in to change notification settings - Fork 1
/
travel2extrude.py
308 lines (249 loc) · 10.4 KB
/
travel2extrude.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# Travel2Extrude
#
# special thanks to [he made the script!]:
# www.github.com/neut
# Neut <m.neut@ultimaker.com>
###############################################################################
# Imports
###############################################################################
import re
import numpy as np
import os.path
import sys
from math import trunc
###############################################################################
# Class definitions
###############################################################################
class Parser:
# Define regular expressions
regex_x = re.compile('X([-+]?\d*\.*\d+)', re.IGNORECASE)
regex_y = re.compile('Y([-+]?\d*\.*\d+)', re.IGNORECASE)
regex_z = re.compile('Z([-+]?\d*\.*\d+)', re.IGNORECASE)
regex_e = re.compile('E([-+]?\d*\.*\d+)', re.IGNORECASE)
regex_f = re.compile('F([-+]?\d*\.*\d+)', re.IGNORECASE)
def __init__(self, file_path, e_per_mm=False):
# Check if we can open the file
if os.path.isfile(file_path):
self.file_path = file_path
else:
sys.exit('Could not open file')
self.writer = Writer(file_path + '.new')
# Describe initial state
self.state = {'prev_x': 0,
'prev_y': 0,
'prev_z': 0,
'prev_e': 0,
'prev_f': 0,
'retract': False,
'total_line_length': 0,
'total_extruded_length': 0}
self.settings = {'e_per_mm': self.estimate_e_per_mm()}
def parse(self):
# Open file and parse contents
with open(self.file_path) as file:
# Go line by line
for line in file:
# Split line on whitespaces (spaces)
line_split = line.split()
# Check for blank lines
if not line_split:
# print('[.] Ignoring blank line')
self.writer.appendLine(newline=True)
# Go to next line
continue
# Check if travel move or extrusion move is detected
if (line_split[0] == 'G0') or (line_split[0] == 'G1'):
# Travel or extrusion move detected. Pass line to parse_move()
self.parse_move(line)
# Reset E axis if required
# NOTE: Assuming G92 is always followed by E0
elif (line_split[0] == 'G92'):
# Reset prev_e
self.state['prev_e'] = 0
self.writer.appendLine(line, newline=True)
continue
# Keep track of retract state
elif (line_split[0] == 'G10'):
# Enable retract
self.state['retract'] = True
self.writer.appendLine(line)
elif (line_split[0] == 'G11'):
self.state['retract'] = False
self.writer.appendLine(line)
else:
# Some other line. Can be copied directly
self.writer.appendLine(line)
def parse_move(self, line):
# Initiate new line
new_line = 'G1 '
g92flag = False
# Perform regular expressions to find xyzef commands
f = self.regex_f.search(line)
x = self.regex_x.search(line)
y = self.regex_y.search(line)
z = self.regex_z.search(line)
e = self.regex_e.search(line)
# Always pass F commands
if f:
f_new = np.float(f.group(1))
new_line += 'F{0} '.format(trunc(f_new))
self.state['prev_f'] = f_new
if x:
x_new = np.float(x.group(1))
new_line += 'X{0} '.format(x_new)
xdist = x_new - self.state['prev_x']
self.state['prev_x'] = x_new
else:
xdist = 0
if y:
y_new = np.float(y.group(1))
new_line += 'Y{0} '.format(y_new)
ydist = y_new - self.state['prev_y']
self.state['prev_y'] = y_new
else:
ydist = 0
if z:
z_new = np.float(z.group(1))
new_line += 'Z{0} '.format(z_new)
zdist = z_new - self.state['prev_z']
self.state['prev_z'] = z_new
else:
zdist = 0
# Compute total cartesian distance (line length)
segment_length = np.sqrt(xdist**2 + ydist**2 + zdist**2)
self.state['total_line_length'] += segment_length
if e:
# Existing extrude move, don't change, just pass as format x-y-z-e
e_new = np.float(e.group(1))
# Track delta_e (for computing total extruded length)
delta_e = e_new - self.state['prev_e']
# Update previous e
self.state['prev_e'] = e_new
else:
# Don't perform E-axis extrusion override when retract is enabled
if self.state['retract'] is True:
e_new = self.state['prev_e']
delta_e = 0
else:
# Not E, i.e. any move without extrusion. Enforce extrusion here
delta_e = segment_length*self.settings['e_per_mm']
e_new = self.state['prev_e'] + delta_e
g92flag = True
# Update total extruded lenghts:
self.state['total_extruded_length'] += delta_e
if delta_e > 0:
# Append E axis is there is extrusion to mention
new_line += 'E{0:0.5f}'.format(e_new)
# Write line
self.writer.appendLine(new_line, newline=True)
# Write G92 to line to recognize where stuff happened
if g92flag is True:
self.writer.appendLine('G92 E{0:0.5f}'.format(self.state['prev_e']), newline=True)
g92flag = False
def estimate_e_per_mm(self):
# Estimates the e_per_mm variable
# This opens the file for reading, and parses a part of it (first n lines)
# number of lines to read
n = 100
# initial e_per_mm
e_per_mm = 0
# initial values for xye
prev_x = 0
prev_y = 0
prev_e = 0
# initial values for total line and e-axis length
sum_e_per_mm = 0
num_e_per_mm = 0
avg_e_per_mm = 0
with open(self.file_path) as f:
line_number = 0
for line in f:
# Break if line threshold is hit
if line_number > n:
# print('Average e_per_mm: ', avg_e_per_mm)
return avg_e_per_mm
# Split line on on whitespaces (spaces)
line_split = line.split()
# Ignore blank lines
if not line_split:
continue
# Record moves
if (line_split[0] == 'G0') or (line_split[0] == 'G1'):
# Only count lines if they contain a move
line_number += 1
x = self.regex_x.search(line)
y = self.regex_y.search(line)
e = self.regex_e.search(line)
if x and y:
x_new = np.float(x.group(1))
y_new = np.float(y.group(1))
if e:
e_new = np.float(e.group(1))
line_length = np.sqrt((x_new - prev_x)**2 + (y_new - prev_y)**2)
# Since e is cumulative in the Ggcode file, no need to update this here
delta_e = e_new - prev_e
# update e_per_mm
e_per_mm = delta_e / line_length
sum_e_per_mm += e_per_mm
num_e_per_mm += 1
avg_e_per_mm = sum_e_per_mm/num_e_per_mm
# print(e_per_mm, avg_e_per_mm)
prev_e = e_new
prev_x = x_new
prev_y = y_new
else:
# Ignore anything else
continue
# If file ends before number of lines threshold is hit
return e_per_mm
def set_e_per_mm(self):
# Placeholder method to manually compute e_per_mm based on flowrate, speed and other parameters
return 0
def getSummary(self):
self.writer.prependLine()
print('== Summary ==')
print('Used e_per_mm: ', self.settings['e_per_mm'])
print('Total line length: ', self.state['total_line_length'])
print('Total extruded length: ', self.state['total_extruded_length'])
def finalize(self):
# Write final stuff to buffer, then write buffer to file and close file.
self.writer.prependLine(newline=True)
self.writer.prependLine(';Total extruded length: {0}'.format(self.state['total_extruded_length']), newline=True)
self.writer.prependLine(';Total line length: {0}'.format(self.state['total_line_length']), newline=True)
self.writer.prependLine(';Used e_per_mm: {0}'.format(self.settings['e_per_mm']), newline=True)
self.writer.prependLine(';==SUMMARY==', newline=True)
# Actually write buffer to file, then close file
self.writer.write()
self.writer.close()
class Writer:
def __init__(self, file_path):
# Open file for writing
self.file = open(file_path, mode='w+')
self.buffer = []
def appendLine(self, line='', newline=False):
if newline is False:
self.buffer.append(line)
else:
self.buffer.append(line + '\n')
def prependLine(self, line='', newline=False):
if newline is False:
self.buffer.insert(0, line)
else:
self.buffer.insert(0, line + '\n')
def write(self):
self.file.writelines(self.buffer)
def close(self):
self.file.close()
###############################################################################
# Main
###############################################################################
def main(args):
parser = Parser(args[1])
parser.parse()
parser.getSummary()
parser.finalize()
###############################################################################
# Runtime
###############################################################################
if __name__ == '__main__':
main(sys.argv)