Skip to content

Commit

Permalink
updated ruff with NPY201
Browse files Browse the repository at this point in the history
  • Loading branch information
Frix-x committed Feb 23, 2025
1 parent 251a093 commit c2f7d53
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 20 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ indent-width = 4
target-version = "py39"

[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "B"]
select = ["E4", "E7", "E9", "F", "B", "NPY201"]
unfixable = ["B"]

[tool.ruff.format]
Expand Down
2 changes: 1 addition & 1 deletion shaketune/graph_creators/axes_map_graph_creator.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def _wavelet_denoise(self, data: np.ndarray, wavelet: str = 'db1', level: int =
return denoised_data, noise

def _integrate_trapz(self, accel: np.ndarray, time: np.ndarray) -> np.ndarray:
return np.array([np.trapz(accel[:i], time[:i]) for i in range(2, len(time) + 1)])
return np.array([np.trapezoid(accel[:i], time[:i]) for i in range(2, len(time) + 1)])

def _process_acceleration_data(
self, time: np.ndarray, accel_x: np.ndarray, accel_y: np.ndarray, accel_z: np.ndarray
Expand Down
24 changes: 12 additions & 12 deletions shaketune/graph_creators/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def plot_axes_map_detection_graph(self, data):
# Add titles and logo
try:
filename = measurements[0]['name']
dt = datetime.strptime(f"{filename.split('_')[2]} {filename.split('_')[3]}", '%Y%m%d %H%M%S')
dt = datetime.strptime(f'{filename.split("_")[2]} {filename.split("_")[3]}', '%Y%m%d %H%M%S')
title_line2 = dt.strftime('%x %X')
if accel is not None:
title_line2 += f' -- at {accel:0.0f} mm/s²'
Expand Down Expand Up @@ -309,7 +309,7 @@ def plot_static_frequency_graph(self, data):
)

# Plot cumulative energy
ax_2.plot(np.trapz(pdata, t, axis=0), bins, color=self.KLIPPAIN_COLORS['orange'])
ax_2.plot(np.trapezoid(pdata, t, axis=0), bins, color=self.KLIPPAIN_COLORS['orange'])
ax_2.set_ylim([bins[0], bins[-1]])
self.configure_axes(
ax_2, xlabel='Cumulative Energy', ylabel='Time (s)', sci_axes='x', title='Vibrations', legend=False
Expand Down Expand Up @@ -350,7 +350,7 @@ def plot_belts_graph(self, data):
# Add titles and logo
try:
filename = measurements[0]['name']
dt = datetime.strptime(f"{filename.split('_')[2]} {filename.split('_')[3]}", '%Y%m%d %H%M%S')
dt = datetime.strptime(f'{filename.split("_")[2]} {filename.split("_")[3]}', '%Y%m%d %H%M%S')
title_line2 = dt.strftime('%x %X')
if kinematics is not None:
title_line2 += ' -- ' + kinematics.upper() + ' kinematics'
Expand Down Expand Up @@ -739,7 +739,7 @@ def plot_input_shaper_graph(self, data):
fontcolor = 'red' if psd[peak] > peaks_threshold[1] else 'black'
fontweight = 'bold' if psd[peak] > peaks_threshold[1] else 'normal'
ax_1.annotate(
f'{idx+1}',
f'{idx + 1}',
(freqs[peak], psd[peak]),
textcoords='offset points',
xytext=(8, 5),
Expand Down Expand Up @@ -787,7 +787,7 @@ def plot_input_shaper_graph(self, data):
for idx, peak in enumerate(peaks):
ax_2.axvline(peak, color='cyan', linestyle='dotted', linewidth=1)
ax_2.annotate(
f'Peak {idx+1}',
f'Peak {idx + 1}',
(peak, bins[-1] * 0.9),
textcoords='data',
color='cyan',
Expand Down Expand Up @@ -958,7 +958,7 @@ def plot_vibrations_graph(self, data):
# Add title
try:
filename_parts = measurements[0]['name'].split('_')
dt = datetime.strptime(f"{filename_parts[4]} {filename_parts[5].split('-')[0]}", '%Y%m%d %H%M%S')
dt = datetime.strptime(f'{filename_parts[4]} {filename_parts[5].split("-")[0]}', '%Y%m%d %H%M%S')
title_line2 = dt.strftime('%x %X')
if accel is not None:
title_line2 += f' at {accel} mm/s² -- {kinematics.upper()} kinematics'
Expand All @@ -985,15 +985,15 @@ def plot_vibrations_graph(self, data):
distance = 0.27 if motors[0].get_config('autotune_enabled') else 0.16
if motors[0].get_config('autotune_enabled'):
config_blocks = [
f"| {lbl}: {mot.get_config('motor').upper()} on {mot.get_config('tmc').upper()} @ {mot.get_config('voltage'):0.1f}V {mot.get_config('run_current'):0.2f}A - {mot.get_config('microsteps')}usteps"
f'| {lbl}: {mot.get_config("motor").upper()} on {mot.get_config("tmc").upper()} @ {mot.get_config("voltage"):0.1f}V {mot.get_config("run_current"):0.2f}A - {mot.get_config("microsteps")}usteps'
for mot, lbl in motor_details
]
config_blocks.append(
f'| TMC Autotune enabled (PWM freq target: X={int(motors[0].get_config("pwm_freq_target")/1000)}kHz / Y={int(motors[1].get_config("pwm_freq_target")/1000)}kHz)'
f'| TMC Autotune enabled (PWM freq target: X={int(motors[0].get_config("pwm_freq_target") / 1000)}kHz / Y={int(motors[1].get_config("pwm_freq_target") / 1000)}kHz)'
)
else:
config_blocks = [
f"| {lbl}: {mot.get_config('tmc').upper()} @ {mot.get_config('run_current'):0.2f}A - {mot.get_config('microsteps')}usteps"
f'| {lbl}: {mot.get_config("tmc").upper()} @ {mot.get_config("run_current"):0.2f}A - {mot.get_config("microsteps")}usteps'
for mot, lbl in motor_details
]
config_blocks.append('| TMC Autotune not detected')
Expand Down Expand Up @@ -1142,7 +1142,7 @@ def plot_vibrations_graph(self, data):
)
for idx, peak in enumerate(vibration_peaks):
ax_2_2.annotate(
f'{idx+1}',
f'{idx + 1}',
(all_speeds[peak], vibration_metric[peak]),
textcoords='offset points',
xytext=(5, 5),
Expand All @@ -1159,7 +1159,7 @@ def plot_vibrations_graph(self, data):
vibration_metric[start:end],
color='green',
alpha=0.2,
label=f'Zone {idx+1}: {all_speeds[start]:.1f} to {all_speeds[end]:.1f} mm/s',
label=f'Zone {idx + 1}: {all_speeds[start]:.1f} to {all_speeds[end]:.1f} mm/s',
)

fontP = self.configure_axes(
Expand Down Expand Up @@ -1202,7 +1202,7 @@ def plot_vibrations_graph(self, data):
for idx, peak in enumerate(vibration_peaks):
ax_5.axvline(all_speeds[peak], color='cyan', linewidth=0.75)
ax_5.annotate(
f'Peak {idx+1}',
f'Peak {idx + 1}',
(all_speeds[peak], all_angles[-1] * 0.9),
textcoords='data',
color='cyan',
Expand Down
6 changes: 3 additions & 3 deletions shaketune/graph_creators/vibrations_graph_creator.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def compute(self):

# Store the interpolated PSD and integral values
psds[angle][speed] = np.interp(target_freqs, first_freqs, psd_sum)
psds_sum[angle][speed] = np.trapz(psd_sum, first_freqs)
psds_sum[angle][speed] = np.trapezoid(psd_sum, first_freqs)

measured_angles = sorted(psds_sum.keys())
measured_speeds = sorted({speed for angle_speeds in psds_sum.values() for speed in angle_speeds.keys()})
Expand Down Expand Up @@ -270,7 +270,7 @@ def _compute_motor_profiles(
all_angles_energy[angle] ** energy_amplification_factor
) # First weighting factor is based on the total vibrations of the machine at the specified angle
curve_area = (
np.trapz(motor_profiles[angle], freqs) ** energy_amplification_factor
np.trapezoid(motor_profiles[angle], freqs) ** energy_amplification_factor
) # Additional weighting factor is based on the area under the current motor profile at this specified angle
total_angle_weight = angle_energy * curve_area

Expand Down Expand Up @@ -335,7 +335,7 @@ def get_interpolated_vibrations(data: dict, speed: float, speeds: List[float]) -
return spectrum_angles, spectrum_speeds, spectrum_vibrations

def _compute_angle_powers(self, spectrogram_data: np.ndarray) -> np.ndarray:
angles_powers = np.trapz(spectrogram_data, axis=1)
angles_powers = np.trapezoid(spectrogram_data, axis=1)

# Since we want to plot it on a continuous polar plot later on, we need to append parts of
# the array to start and end of it to smooth transitions when doing the convolution
Expand Down
5 changes: 4 additions & 1 deletion shaketune/helpers/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@

from collections import namedtuple

ResTesterConfig = namedtuple('ResTesterConfig', ['default_min_freq', 'default_max_freq', 'default_accel_per_hz', 'test_points'])
ResTesterConfig = namedtuple(
'ResTesterConfig', ['default_min_freq', 'default_max_freq', 'default_accel_per_hz', 'test_points']
)


def res_tester_config(config) -> ResTesterConfig:
printer = config.get_printer()
Expand Down
3 changes: 1 addition & 2 deletions shaketune/shaketune.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@
DEFAULT_MEASUREMENTS_CHUNK_SIZE = 2 # Maximum number of measurements to keep in memory at once
ST_COMMANDS = {
'EXCITATE_AXIS_AT_FREQ': (
'Maintain a specified excitation frequency for a period '
'of time to diagnose and locate a source of vibrations'
'Maintain a specified excitation frequency for a period of time to diagnose and locate a source of vibrations'
),
'AXES_MAP_CALIBRATION': (
'Perform a set of movements to measure the orientation of the accelerometer '
Expand Down

0 comments on commit c2f7d53

Please sign in to comment.