-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.py
More file actions
287 lines (253 loc) · 9.51 KB
/
Copy pathcli.py
File metadata and controls
287 lines (253 loc) · 9.51 KB
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
"""The pyGCodeDecode CLI Module.
Interact with pyGCodeDecode via the command line to run examples and plot GCode files.
Features:
- Run built-in examples: `brace`, `benchy`
- Plot GCode files with printer presets and output options
- Save simulation summaries, metrics, screenshots, and VTK files
Usage Examples:
- `pygcd --help`
- `pygcd run_example brace`
- `pygcd plot -g myfile.gcode`
- `pygcd plot -g myfile.gcode -p presets.yaml -pn my_printer`
- `pygcd plot -g myfile.gcode -o ./outputs -lc ";LAYER"`
"""
import argparse
import importlib.resources
import pathlib
from pyGCodeDecode import __version__
from pyGCodeDecode.examples.benchy import benchy_example
from pyGCodeDecode.examples.brace import brace_example
from pyGCodeDecode.gcode_interpreter import setup, simulation
from pyGCodeDecode.helpers import custom_print
from pyGCodeDecode.plotter import plot_3d
from pyGCodeDecode.tools import save_layer_metrics
def _run_example(args: argparse.Namespace) -> None:
"""Generate a plot from a GCode file."""
if args.example == "brace":
brace_example()
if args.example == "benchy":
benchy_example()
def _plot(args: argparse.Namespace) -> None:
"""Generate a plot from a GCode file."""
def _find_gcode_file(specified_path: pathlib.Path | None) -> pathlib.Path:
"""Check if the G-code file exists and try to find one in the cwd if not specified."""
if specified_path is not None and specified_path.is_file():
g_code_file = specified_path
elif specified_path is not None:
custom_print(
f"❌ The specified G-code:\n{specified_path.resolve()}\nis not valid."
"\n🛑 Exiting the program.",
lvl=1,
)
exit()
else:
custom_print(
"⚠️ No G-code file specified. Looking for a G-code file in the current directory"
"... 👀",
lvl=1,
)
files_list = list(pathlib.Path.cwd().glob("*.gcode"))
if files_list.__len__() == 0:
custom_print(
"❌ No G-code file found in the current directory.\n🛑 Exiting the program.",
lvl=1,
)
exit()
elif files_list.__len__() == 1:
g_code_file = files_list[0]
else:
custom_print("❌ Multiple G-code files found in the current directory:", lvl=1)
for file in files_list:
custom_print(f" - {file.resolve()}", lvl=1)
custom_print("🛑 Exiting the program.", lvl=1)
exit()
custom_print(f"✅ Using the G-code file:\n{g_code_file.resolve()}")
return g_code_file
def _get_presets_file(presets_file: pathlib.Path | None) -> pathlib.Path:
"""Get the machine setup from the presets file."""
if presets_file is None:
custom_print(
"⚠️ No presets file specified. Using the default presets shipped with pyGCD."
)
presets_file = importlib.resources.files("pyGCodeDecode").joinpath(
"data/default_printer_presets.yaml"
) # type: ignore
elif not presets_file.is_file():
custom_print(
f"❌ The specified presets file:\n{presets_file.resolve()}\n"
"is not valid.\n🛑 Exiting the program.",
lvl=1,
)
exit()
else:
custom_print(f"✅ Using the presets file:\n{presets_file.resolve()}")
return presets_file # type: ignore
def _get_out_dir(
out_dir: pathlib.Path | None, g_code_file: pathlib.Path
) -> pathlib.Path | None:
"""Get the output directory for the plot."""
if out_dir is None:
answer = ""
while answer.lower() not in ("y", "yes", "n", "no"):
answer = input(
"⚠️ No output directory specified! Do you want to create one in the current "
"working directory?"
"\nIf not, no outputs will be saved!"
"\nYou must answer with yes (y) or no (n)!\n"
)
if answer.lower() in ["n", "no"]:
custom_print("⚠️ Not creating any output files.")
return None
elif answer.lower() in ["y", "yes"]:
out_dir = pathlib.Path.cwd() / f"output_{g_code_file.stem}"
if out_dir is not None:
custom_print(f"✅ Using the output directory: {out_dir.resolve()}")
return out_dir
g_code_file = _find_gcode_file(args.gcode)
out_dir = _get_out_dir(args.out_dir, g_code_file)
presets_file = _get_presets_file(args.presets)
if args.printer_name is not None:
printer_name = args.printer_name
custom_print(f"✅ Using the printer: {printer_name}")
else:
custom_print("⚠️ No printer specified. Using the default printer Anisoprint A4.")
printer_name = "anisoprint_a4"
# setting up the printer
printer_setup = setup(
presets_file=presets_file,
printer=printer_name,
layer_cue=args.layer_cue,
)
# running the simulation by creating a simulation object
sim = simulation(
gcode_path=g_code_file,
initial_machine_setup=printer_setup,
)
svalue = args.scalar_value if args.scalar_value is not None else "velocity"
ploteonly = args.extrusion_only == "True" if args.extrusion_only is not None else True
if out_dir is not None:
out_dir.mkdir(parents=True, exist_ok=True)
# save a short summary of the simulation
sim.save_summary(filepath=out_dir / f"{g_code_file.stem}_summary.yaml")
# print a file containing some metrics for each layer
save_layer_metrics(
simulation=sim,
filepath=out_dir / f"{g_code_file.stem}_layer_metrics.csv",
locale="en_US.utf8",
delimiter=",",
)
# create a 3D-plot and save a VTK as well as a screenshot
mesh = plot_3d(
sim,
extrusion_only=ploteonly,
screenshot_path=out_dir / f"{g_code_file.stem}.png",
vtk_path=out_dir / f"{g_code_file.stem}.vtk",
scalar_value=svalue,
)
else:
mesh = None
# create an interactive 3D-plot
plot_3d(sim, mesh=mesh, scalar_value=svalue)
def _main(args: list | None = None) -> None:
"""Entry point function for the command-line interface (CLI)."""
global_parser = argparse.ArgumentParser(
prog="pygcd",
description=__doc__.splitlines()[0] # type: ignore
+ f" You are running version {__version__}.",
)
global_parser.add_argument(
"-v",
"--version",
action="version",
version=__version__,
)
# subparsers for various functions
subparsers = global_parser.add_subparsers(
title="subcommands",
description="Functions accessible via this CLI.",
)
# subparser to run examples
example_parser = subparsers.add_parser("run_example", help="Run one of the provided examples.")
example_parser.add_argument(
"example",
help="The name of the example to run.",
choices=["brace", "benchy"],
)
example_parser.set_defaults(func=_run_example)
# subparser to plot a GCode file
plot_parser = subparsers.add_parser("plot", help="Generate a plot from a GCode file.")
plot_parser.set_defaults(func=_plot)
plot_parser.add_argument(
"-g",
"--gcode",
action="store",
nargs="?",
help="The path to the G-code file. Looks for a G-code file in the "
"current directory if not specified.",
default=None,
type=pathlib.Path,
metavar="<PATH>",
)
plot_parser.add_argument(
"-s",
"--scalar_value",
action="store",
help="The scalar value to visualize in the plot (e.g., 'rel_vel_err', 'acceleration', "
"'velocity'...).",
default=None,
type=str,
metavar="<NAME>",
)
plot_parser.add_argument(
"-e",
"--extrusion_only",
type=str,
choices=["True", "False"],
default="True",
help="Only visualize the extrusion paths.",
metavar="<BOOL>",
)
plot_parser.add_argument(
"-p",
"--presets",
action="store",
help="The path to the printer presets file. Default printers can be used if not specified.",
default=None,
type=pathlib.Path,
metavar="<PATH>",
)
plot_parser.add_argument(
"-pn",
"--printer_name",
action="store",
help="The name of the printer as specified in the presets file or the "
"defaults if no presets were specified",
default=None,
type=str,
metavar="<NAME>",
)
plot_parser.add_argument(
"-o",
"--out_dir",
action="store",
help="The path to the output directory.",
default=None,
type=pathlib.Path,
metavar="<PATH>",
)
plot_parser.add_argument(
"-lc",
"--layer_cue",
action="store",
help="The cue indicating a layer switch in the GCode.",
default=None,
type=str,
metavar="<cue>",
)
# parse the arguments
parsed_args = global_parser.parse_args(args)
# call the respective function specified by the subparser
if hasattr(parsed_args, "func"):
parsed_args.func(parsed_args)
else:
global_parser.print_help()