Plot a CNC program using Python.
This quick guide shows how to easily display the toolpath of an NC program using Python.
Visualising CNC programs is a useful way to check the movements before sending the NC code to a real machine. In this tutorial, we will start with the setup and demonstrate how to plot a short NC program using Python.
For the setup, we use the Jupiter Notebook; actually, we use Google Colab, where everything is already set up. To do this, go to Colab and start an empty new notebook.
at the head of the book we first install a library to caculate the toolpath. for this We use ncplot7py.
s a Python module that can be used to create a CNC machine and simulate a program. This is the first time we will use a standard CNC machine that has been built in.
So we go to oure empty Notebook and we first install the ncplot7py
Step 1: Install `ncplot7py
!pip install ncplot7pyStep 2: Import the required modules
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from ncplot7py.application.nc_execution import NCExecutionEngine
from ncplot7py.domain.cnc_state import CNCState
from ncplot7py.domain.machines import get_machine_config
from ncplot7py.infrastructure.machines.base_stateful_control import (UniversalConfigDrivenControl,)- CNCState: stores the state of the virtual CNC machine
- get_machine_config: loads a predefined machine configuration
- UniversalConfigDrivenControl: controls the simulated machine
- NCExecutionEngine: executes the NC program and returns the simulation result
Step 3: Create a sample CNC program
In order to simulate something, we need to create the CNC program that we want to simulate.
The first step is to just move some axes; later, we can go much deeper.
Get Damian R’s stories in your inbox
Join Medium for free to get updates from this writer.
For this example, we will simulate a simple rectangular toolpath:
program = """
G94
G0 X0 Y0 Z10
G1 X50 Y0 F300
G1 X50 Y50
G1 X0 Y50
G1 X0 Y0
M30
"""Step 4: Create the CNC machine simulation
Next we need to define the Machine. There are a lot of predefined machines. We use the Siemens for this example but we could also use others like Fanuc turing and Fanuc mill
state = CNCState(machine_config=get_machine_config("SIEMENS_840DI"))
control = UniversalConfigDrivenControl(init_nc_states=[state])
engine = NCExecutionEngine(control)Step 5: Execute the NC program
So next we can already execute our Program. Because it can also simulate multichanelprogram it calls get_Syncro_plot The returned result contains plot-ready information for the simulated toolpath. You can also inspect errors and the calculated runtime:
result = engine.get_Syncro_plot([program],synch=False)
errors = engine.errors
runtime = engine.get_cacluated_runtime()
print("Errors:", errors)
print("Calculated runtime:", runtime)Step 6: Extract the toolpath coordinates
The plot data is returned for each simulated channel. The following code collects the X, Y, and Z coordinates:
all_x = []
all_y = []
all_z = []
for channel in result:
for segment in channel.get("plot", []):
all_x.extend(segment.get("x", []))
all_y.extend(segment.get("y", []))
all_z.extend(segment.get("z", []))At this point, the coordinate arrays contain the simulated tool movements.
Step 7: Create a 3D plot
Now we can display the CNC toolpath with Matplotlib:
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection="3d")
ax.plot(all_x,all_y,all_z,label="CNC Toolpath",color="blue",linewidth=2)
ax.set_xlabel("X [mm]")
ax.set_ylabel("Y [mm]")
ax.set_zlabel("Z [mm]")
ax.set_title("NC Toolpath Simulation")
ax.legend()
plt.show()The result should show a rectangular toolpath in a 3D coordinate system.
There is also a webpage that impements the ncplot7py
Here we have once again the hole Program. If you like to go deeper you can let me know. So we make other example
!pip install ncplot7pyimport matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from ncplot7py.application.nc_execution import NCExecutionEngine
from ncplot7py.domain.cnc_state import CNCState
from ncplot7py.domain.machines import get_machine_config
from ncplot7py.infrastructure.machines.base_stateful_control import UniversalConfigDrivenControl
program = """
G90 G54
G0 X0 Y0 Z10
G1 X50 Y0 F300
G1 X50 Y50
G1 X0 Y50
G1 X0 Y0
M30
"""
state = CNCState(machine_config=get_machine_config("SIEMENS_840DI"))
control = UniversalConfigDrivenControl(init_nc_states=[state])
engine = NCExecutionEngine(control)
result = engine.get_Syncro_plot([program], synch=False)
# Extract X, Y, Z coordinates from the plot segments
all_x, all_y, all_z = [], [], []
for canal in result:
for line in canal.get("plot", []):
all_x.extend(line.get("x", []))
all_y.extend(line.get("y", []))
all_z.extend(line.get("z", []))
# 3D Toolpath Plot
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.plot(all_x, all_y, all_z, label="Toolpath", color="blue")
ax.set_xlabel("X [mm]")
ax.set_ylabel("Y [mm]")
ax.set_zlabel("Z [mm]")
ax.set_title("NC Toolpath Simulation")
plt.legend()
plt.show()



