6 Commits

Author SHA1 Message Date
Félix Boisselier
358773ddef Merge pull request #2 from Frix-x/develop
Localisation fix and additional safety checks
2023-10-28 14:11:16 +02:00
Félix Boisselier
d0930261f7 removed symbols in console prints 2023-10-28 14:09:59 +02:00
Félix Boisselier
a03a3c2e4b Added some safety checks and forced C locale for console printing 2023-10-27 14:44:06 +02:00
Félix Boisselier
c102d4145c fixed MHI LUT to give values on all the range 2023-10-26 18:52:34 +02:00
Félix Boisselier
c39f0fe781 bugfixes 2023-10-26 18:18:18 +02:00
Félix Boisselier
6742a785d3 added logging for filename in case of an unexpected error 2023-10-26 13:56:15 +02:00
5 changed files with 105 additions and 36 deletions

View File

@@ -28,10 +28,6 @@ import locale
from datetime import datetime from datetime import datetime
matplotlib.use('Agg') matplotlib.use('Agg')
try:
locale.setlocale(locale.LC_TIME, locale.getdefaultlocale())
except locale.Error:
locale.setlocale(locale.LC_TIME, 'C')
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # For paired peaks names ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # For paired peaks names
@@ -54,6 +50,22 @@ KLIPPAIN_COLORS = {
} }
# Set the best locale for time and date formating (generation of the titles)
try:
locale.setlocale(locale.LC_TIME, locale.getdefaultlocale())
except locale.Error:
locale.setlocale(locale.LC_TIME, 'C')
# Override the built-in print function to avoid problem in Klipper due to locale settings
original_print = print
def print_with_c_locale(*args, **kwargs):
original_locale = locale.setlocale(locale.LC_ALL, None)
locale.setlocale(locale.LC_ALL, 'C')
original_print(*args, **kwargs)
locale.setlocale(locale.LC_ALL, original_locale)
print = print_with_c_locale
###################################################################### ######################################################################
# Computation of the PSD graph # Computation of the PSD graph
###################################################################### ######################################################################
@@ -330,15 +342,15 @@ def compute_mhi(combined_data, similarity_coefficient, num_unpaired_peaks):
def mhi_lut(mhi): def mhi_lut(mhi):
if 0 <= mhi <= 30: if 0 <= mhi <= 30:
return "Excellent mechanical health" return "Excellent mechanical health"
elif 31 <= mhi <= 45: elif 30 < mhi <= 45:
return "Good mechanical health" return "Good mechanical health"
elif 46 <= mhi <= 55: elif 45 < mhi <= 55:
return "Acceptable mechanical health" return "Acceptable mechanical health"
elif 56 <= mhi <= 70: elif 55 < mhi <= 70:
return "Potential signs of a mechanical issue" return "Potential signs of a mechanical issue"
elif 71 <= mhi <= 85: elif 70 < mhi <= 85:
return "Likely a mechanical issue" return "Likely a mechanical issue"
elif 86 <= mhi <= 100: elif 85 < mhi <= 100:
return "Mechanical issue detected" return "Mechanical issue detected"
@@ -570,11 +582,15 @@ def belts_calibration(lognames, klipperdir="~/klipper", max_freq=200.):
ax2 = fig.add_subplot(gs[1]) ax2 = fig.add_subplot(gs[1])
# Add title # Add title
title_line1 = "RELATIVE BELT CALIBRATION TOOL"
fig.text(0.12, 0.965, title_line1, ha='left', va='bottom', fontsize=20, color=KLIPPAIN_COLORS['purple'], weight='bold')
try:
filename = lognames[0].split('/')[-1] filename = lognames[0].split('/')[-1]
dt = datetime.strptime(f"{filename.split('_')[1]} {filename.split('_')[2]}", "%Y%m%d %H%M%S") dt = datetime.strptime(f"{filename.split('_')[1]} {filename.split('_')[2]}", "%Y%m%d %H%M%S")
title_line1 = "RELATIVE BELT CALIBRATION TOOL"
title_line2 = dt.strftime('%x %X') title_line2 = dt.strftime('%x %X')
fig.text(0.12, 0.965, title_line1, ha='left', va='bottom', fontsize=20, color=KLIPPAIN_COLORS['purple'], weight='bold') except:
print("Warning: CSV filenames look to be different than expected (%s , %s)" % (lognames[0], lognames[1]))
title_line2 = lognames[0].split('/')[-1] + " / " + lognames[1].split('/')[-1]
fig.text(0.12, 0.957, title_line2, ha='left', va='top', fontsize=16, color=KLIPPAIN_COLORS['dark_purple']) fig.text(0.12, 0.957, title_line2, ha='left', va='top', fontsize=16, color=KLIPPAIN_COLORS['dark_purple'])
# Plot the graphs # Plot the graphs

View File

@@ -35,10 +35,6 @@ import locale
from datetime import datetime from datetime import datetime
matplotlib.use('Agg') matplotlib.use('Agg')
try:
locale.setlocale(locale.LC_TIME, locale.getdefaultlocale())
except locale.Error:
locale.setlocale(locale.LC_TIME, 'C')
PEAKS_DETECTION_THRESHOLD = 0.05 PEAKS_DETECTION_THRESHOLD = 0.05
@@ -52,6 +48,22 @@ KLIPPAIN_COLORS = {
} }
# Set the best locale for time and date formating (generation of the titles)
try:
locale.setlocale(locale.LC_TIME, locale.getdefaultlocale())
except locale.Error:
locale.setlocale(locale.LC_TIME, 'C')
# Override the built-in print function to avoid problem in Klipper due to locale settings
original_print = print
def print_with_c_locale(*args, **kwargs):
original_locale = locale.setlocale(locale.LC_ALL, None)
locale.setlocale(locale.LC_ALL, 'C')
original_print(*args, **kwargs)
locale.setlocale(locale.LC_ALL, original_locale)
print = print_with_c_locale
###################################################################### ######################################################################
# Computation # Computation
###################################################################### ######################################################################
@@ -73,7 +85,7 @@ def calibrate_shaper_with_damping(datas, max_smoothing):
fr, zeta = compute_damping_ratio(psd, freqs) fr, zeta = compute_damping_ratio(psd, freqs)
print("Recommended shaper is %s @ %.1f Hz" % (shaper.name, shaper.freq)) print("Recommended shaper is %s @ %.1f Hz" % (shaper.name, shaper.freq))
print("Axis has a resonant frequency ω0=%.1fHz with an estimated damping ratio ζ=%.3f" % (fr, zeta)) print("Axis has a main resonant frequency at %.1fHz with an estimated damping ratio of %.3f" % (fr, zeta))
return shaper.name, all_shapers, calibration_data, fr, zeta return shaper.name, all_shapers, calibration_data, fr, zeta
@@ -311,11 +323,15 @@ def shaper_calibration(lognames, klipperdir="~/klipper", max_smoothing=None, max
ax2 = fig.add_subplot(gs[1]) ax2 = fig.add_subplot(gs[1])
# Add title # Add title
filename_parts = (lognames[0].split('/')[-1]).split('_')
dt = datetime.strptime(f"{filename_parts[3]} {filename_parts[4].split('.')[0]}", "%Y%m%d %H%M%S")
title_line1 = "INPUT SHAPER CALIBRATION TOOL" title_line1 = "INPUT SHAPER CALIBRATION TOOL"
title_line2 = dt.strftime('%x %X') + ' -- ' + filename_parts[2].upper() + ' axis'
fig.text(0.12, 0.965, title_line1, ha='left', va='bottom', fontsize=20, color=KLIPPAIN_COLORS['purple'], weight='bold') fig.text(0.12, 0.965, title_line1, ha='left', va='bottom', fontsize=20, color=KLIPPAIN_COLORS['purple'], weight='bold')
try:
filename_parts = (lognames[0].split('/')[-1]).split('_')
dt = datetime.strptime(f"{filename_parts[1]} {filename_parts[2]}", "%Y%m%d %H%M%S")
title_line2 = dt.strftime('%x %X') + ' -- ' + filename_parts[3].upper().split('.')[0] + ' axis'
except:
print("Warning: CSV filename look to be different than expected (%s)" % (lognames[0]))
title_line2 = lognames[0].split('/')[-1]
fig.text(0.12, 0.957, title_line2, ha='left', va='top', fontsize=16, color=KLIPPAIN_COLORS['dark_purple']) fig.text(0.12, 0.957, title_line2, ha='left', va='top', fontsize=16, color=KLIPPAIN_COLORS['dark_purple'])
# Plot the graphs # Plot the graphs

View File

@@ -29,10 +29,6 @@ import locale
from datetime import datetime from datetime import datetime
matplotlib.use('Agg') matplotlib.use('Agg')
try:
locale.setlocale(locale.LC_TIME, locale.getdefaultlocale())
except locale.Error:
locale.setlocale(locale.LC_TIME, 'C')
PEAKS_DETECTION_THRESHOLD = 0.05 PEAKS_DETECTION_THRESHOLD = 0.05
@@ -46,6 +42,22 @@ KLIPPAIN_COLORS = {
} }
# Set the best locale for time and date formating (generation of the titles)
try:
locale.setlocale(locale.LC_TIME, locale.getdefaultlocale())
except locale.Error:
locale.setlocale(locale.LC_TIME, 'C')
# Override the built-in print function to avoid problem in Klipper due to locale settings
original_print = print
def print_with_c_locale(*args, **kwargs):
original_locale = locale.setlocale(locale.LC_ALL, None)
locale.setlocale(locale.LC_ALL, 'C')
original_print(*args, **kwargs)
locale.setlocale(locale.LC_ALL, original_locale)
print = print_with_c_locale
###################################################################### ######################################################################
# Computation # Computation
###################################################################### ######################################################################
@@ -348,7 +360,7 @@ def setup_klipper_import(kdir):
shaper_calibrate = importlib.import_module('.shaper_calibrate', 'extras') shaper_calibrate = importlib.import_module('.shaper_calibrate', 'extras')
def vibrations_calibration(lognames, klipperdir="~/klipper", axisname=None, max_freq=200., remove=0): def vibrations_calibration(lognames, klipperdir="~/klipper", axisname=None, max_freq=1000., remove=0):
setup_klipper_import(klipperdir) setup_klipper_import(klipperdir)
# Parse the raw data and get them ready for analysis # Parse the raw data and get them ready for analysis
@@ -368,11 +380,15 @@ def vibrations_calibration(lognames, klipperdir="~/klipper", axisname=None, max_
ax1 = fig.add_subplot(gs[0]) ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1]) ax2 = fig.add_subplot(gs[1])
title_line1 = "VIBRATIONS MEASUREMENT TOOL"
fig.text(0.12, 0.965, title_line1, ha='left', va='bottom', fontsize=20, color=KLIPPAIN_COLORS['purple'], weight='bold')
try:
filename_parts = (lognames[0].split('/')[-1]).split('_') filename_parts = (lognames[0].split('/')[-1]).split('_')
dt = datetime.strptime(f"{filename_parts[1]} {filename_parts[2].split('-')[0]}", "%Y%m%d %H%M%S") dt = datetime.strptime(f"{filename_parts[1]} {filename_parts[2].split('-')[0]}", "%Y%m%d %H%M%S")
title_line1 = "VIBRATIONS MEASUREMENT TOOL"
title_line2 = dt.strftime('%x %X') + ' -- ' + axisname.upper() + ' axis' title_line2 = dt.strftime('%x %X') + ' -- ' + axisname.upper() + ' axis'
fig.text(0.12, 0.965, title_line1, ha='left', va='bottom', fontsize=20, color=KLIPPAIN_COLORS['purple'], weight='bold') except:
print("Warning: CSV filename look to be different than expected (%s)" % (lognames[0]))
title_line2 = lognames[0].split('/')[-1]
fig.text(0.12, 0.957, title_line2, ha='left', va='top', fontsize=16, color=KLIPPAIN_COLORS['dark_purple']) fig.text(0.12, 0.957, title_line2, ha='left', va='top', fontsize=16, color=KLIPPAIN_COLORS['dark_purple'])
# Remove speeds duplicates and graph the processed datas # Remove speeds duplicates and graph the processed datas

View File

@@ -63,7 +63,16 @@ def get_belts_graph():
current_date = datetime.now().strftime('%Y%m%d_%H%M%S') current_date = datetime.now().strftime('%Y%m%d_%H%M%S')
lognames = [] lognames = []
for filename in glob.glob('/tmp/raw_data_axis*.csv'): globbed_files = glob.glob('/tmp/raw_data_axis*.csv')
if not globbed_files:
print("No CSV files found in the /tmp folder to create the belt graphs!")
sys.exit(1)
if len(globbed_files) < 2:
print("Not enough CSV files found in the /tmp folder. Two files are required for the belt graphs!")
sys.exit(1)
sorted_files = sorted(globbed_files, key=os.path.getmtime, reverse=True)
for filename in sorted_files[:2]:
# Wait for the file handler to be released by Klipper # Wait for the file handler to be released by Klipper
while is_file_open(filename): while is_file_open(filename):
time.sleep(3) time.sleep(3)
@@ -86,13 +95,13 @@ def get_belts_graph():
def get_shaper_graph(): def get_shaper_graph():
current_date = datetime.now().strftime('%Y%m%d_%H%M%S') current_date = datetime.now().strftime('%Y%m%d_%H%M%S')
# Get all the files and sort them based on last modified time to select the most recent one
globbed_files = glob.glob('/tmp/raw_data*.csv') globbed_files = glob.glob('/tmp/raw_data*.csv')
if len(globbed_files) > 1: if not globbed_files:
print("There is more than 1 measurement.csv found in the /tmp folder. Unable to plot the shaper graphs!") print("No CSV files found in the /tmp folder to create the input shaper graphs!")
print("Please clean the files in the /tmp folder and start again.")
sys.exit(1) sys.exit(1)
sorted_files = sorted(globbed_files, key=os.path.getmtime, reverse=True)
filename = globbed_files[0] filename = sorted_files[0]
# Wait for the file handler to be released by Klipper # Wait for the file handler to be released by Klipper
while is_file_open(filename): while is_file_open(filename):
@@ -114,7 +123,15 @@ def get_vibrations_graph(axis_name):
current_date = datetime.now().strftime('%Y%m%d_%H%M%S') current_date = datetime.now().strftime('%Y%m%d_%H%M%S')
lognames = [] lognames = []
for filename in glob.glob('/tmp/adxl345-*.csv'): globbed_files = glob.glob('/tmp/adxl345-*.csv')
if not globbed_files:
print("No CSV files found in the /tmp folder to create the vibration graphs!")
sys.exit(1)
if len(globbed_files) < 3:
print("Not enough CSV files found in the /tmp folder. At least 3 files are required for the vibration graphs!")
sys.exit(1)
for filename in globbed_files:
# Wait for the file handler to be released by Klipper # Wait for the file handler to be released by Klipper
while is_file_open(filename): while is_file_open(filename):
time.sleep(3) time.sleep(3)

View File

@@ -40,11 +40,15 @@ For those not using the full [Klippain](https://github.com/Frix-x/klippain), fol
install_script: install.sh install_script: install.sh
``` ```
> **Note**:
>
> If already using my old IS workflow scripts, please remove everything before installing this new module. This include the macros, the Python scripts, the `plot_graph.sh` and the `[gcode_shell_command plot_graph]` section.
## Usage ## Usage
Ensure your machine is homed, then invoke one of the following macros as needed: Ensure your machine is homed, then invoke one of the following macros as needed:
- `BELTS_SHAPER_CALIBRATION` for belt resonance graphs, useful for verifying belt tension and differential belt paths behavior. - `BELTS_SHAPER_CALIBRATION` for belt resonance graphs, useful for verifying belt tension and differential belt paths behavior.
- `AXES_SHAPER_CALIBRATION` for input shaper graphs to mitigate ringing/ghosting by tuning Klipper's `[input_shaper]` system. - `AXES_SHAPER_CALIBRATION` for input shaper graphs to mitigate ringing/ghosting by tuning Klipper's input shaper system.
- `VIBRATIONS_CALIBRATION` for machine vibration graphs to optimize your slicer speed profiles. - `VIBRATIONS_CALIBRATION` for machine vibration graphs to optimize your slicer speed profiles.
- `EXCITATE_AXIS_AT_FREQ` to sustain a specific excitation frequency, useful to let you inspect and find out what is resonating. - `EXCITATE_AXIS_AT_FREQ` to sustain a specific excitation frequency, useful to let you inspect and find out what is resonating.