# Checks the loaded bed mesh for bumps, dips and too much height range. # # The bed is naturally bowl-shaped, so a height range alone cannot tell dirt # from normal shape. This fits a smooth surface (polynomial, degree 4) to the # probed points, leaving out outliers, and looks at how far each point is from # it. Measured on this printer's Beacon scans (33x35 points): # clean plate, cold or hot: worst deviation 0.016 mm # residue on the plate, 2026-11: 0.07 (bed 60C), 0.09 (bed 100C, at the old # mesh edge), 0.30 mm (cold, mesh over it) # Only reads the mesh: it moves nothing and changes nothing. # # Install: copy to ~/klipper/klippy/extras/mesh_check.py (install.sh links it) # and add # # [mesh_check] # bump_limit: 0.03 # mm from the smooth surface that counts as a bump or dip # range_limit: 0.30 # mm between the highest and lowest point # # Commands: # BED_MESH_CHECK [BUMP=] [RANGE=] # # Status (printer.mesh_check): result ('ok', 'fail', 'none' = no mesh or the # check failed, 'not run'), range, worst, areas (number of bumps and dips), # summary (no double quotes, usable in a macro's MSG="...") import logging import numpy as np DEGREE = 4 MAX_AREAS = 5 # areas named in the report, biggest deviation first MIN_POINTS = 40 # fewer points cannot carry a degree 4 surface reliably def surface_residuals(z): # Deviation of each point from a smooth surface. Refit without the points # far from it, so a bump does not pull the surface towards itself. ny, nx = z.shape x, y = np.meshgrid(np.linspace(-1., 1., nx), np.linspace(-1., 1., ny)) terms = [x.ravel()**i * y.ravel()**j for i in range(DEGREE + 1) for j in range(DEGREE + 1 - i)] a = np.column_stack(terms) values = z.ravel() keep = np.ones(values.size, dtype=bool) residuals = np.zeros(values.size) for _ in range(5): coeffs = np.linalg.lstsq(a[keep], values[keep], rcond=None)[0] residuals = values - a.dot(coeffs) spread = 1.4826 * np.median( np.abs(residuals[keep] - np.median(residuals[keep]))) keep = np.abs(residuals) < max(3. * spread, 0.01) return residuals.reshape(z.shape) def find_areas(residuals, limit): # Groups of touching points (diagonals too) beyond the limit, as # (peak, row min, row max, column min, column max) ny, nx = residuals.shape over = np.abs(residuals) > limit seen = np.zeros(over.shape, dtype=bool) areas = [] for start in zip(*np.nonzero(over)): if seen[start]: continue seen[start] = True stack = [start] points = [] while stack: j, i = stack.pop() points.append((j, i)) for dj in (-1, 0, 1): for di in (-1, 0, 1): nj, ni = j + dj, i + di if (0 <= nj < ny and 0 <= ni < nx and over[nj, ni] and not seen[nj, ni]): seen[nj, ni] = True stack.append((nj, ni)) peak = max((residuals[p] for p in points), key=abs) rows = [p[0] for p in points] cols = [p[1] for p in points] areas.append((float(peak), min(rows), max(rows), min(cols), max(cols))) areas.sort(key=lambda area: -abs(area[0])) return areas def analyse(matrix, mesh_min, mesh_max, bump_limit, range_limit): # Returns the status dictionary. No Klipper objects, so it can be tested # against saved scans. z = np.array(matrix, dtype=float) if z.ndim != 2 or z.size == 0: return {'result': 'none', 'range': 0., 'worst': 0., 'areas': 0, 'summary': 'no bed mesh loaded'} height_range = float(z.max() - z.min()) ny, nx = z.shape if z.size < MIN_POINTS: return {'result': 'none', 'range': height_range, 'worst': 0., 'areas': 0, 'summary': 'mesh too small to check (%d points)' % (z.size,)} residuals = surface_residuals(z) worst = float(np.abs(residuals).max()) areas = find_areas(residuals, bump_limit) step_x = (mesh_max[0] - mesh_min[0]) / float(nx - 1) step_y = (mesh_max[1] - mesh_min[1]) / float(ny - 1) problems = [] for peak, row0, row1, col0, col1 in areas[:MAX_AREAS]: problems.append("%s %+.2f mm at X%.0f-%.0f Y%.0f-%.0f" % ( "bump" if peak > 0. else "dip", peak, mesh_min[0] + col0 * step_x, mesh_min[0] + col1 * step_x, mesh_min[1] + row0 * step_y, mesh_min[1] + row1 * step_y)) if len(areas) > MAX_AREAS: problems.append("%d more" % (len(areas) - MAX_AREAS,)) too_wide = height_range > range_limit if too_wide: problems.append("range %.2f mm is over the limit of %.2f" % ( height_range, range_limit)) text = "range %.3f mm, worst deviation %.3f mm" % (height_range, worst) if problems: text = "%s: %s" % (text, ", ".join(problems)) return {'result': 'fail' if problems else 'ok', 'range': height_range, 'worst': worst, 'areas': len(areas), 'summary': text} class MeshCheck: def __init__(self, config): self.printer = config.get_printer() self.reactor = self.printer.get_reactor() self.bump_limit = config.getfloat('bump_limit', 0.03, above=0.) self.range_limit = config.getfloat('range_limit', 0.30, above=0.) self.status = {'result': 'not run', 'range': 0., 'worst': 0., 'areas': 0, 'summary': ''} gcode = self.printer.lookup_object('gcode') gcode.register_command('BED_MESH_CHECK', self.cmd_BED_MESH_CHECK, desc="Check the loaded bed mesh for bumps, " "dips and too much height range") def cmd_BED_MESH_CHECK(self, gcmd): bump = gcmd.get_float('BUMP', self.bump_limit, above=0.) height_range = gcmd.get_float('RANGE', self.range_limit, above=0.) # A failing analysis must not stop a print: it reports and goes on try: bed_mesh = self.printer.lookup_object('bed_mesh') mesh = bed_mesh.get_status(self.reactor.monotonic()) self.status = analyse(mesh['probed_matrix'], mesh['mesh_min'], mesh['mesh_max'], bump, height_range) except Exception: logging.exception("mesh_check: analysis failed") self.status = {'result': 'none', 'range': 0., 'worst': 0., 'areas': 0, 'summary': 'check failed, see klippy.log'} msg = "Bed mesh check: %s" % (self.status['summary'],) logging.info("mesh_check: %s (%s)", msg, self.status['result']) gcmd.respond_info(msg) def get_status(self, eventtime): return dict(self.status) def load_config(config): return MeshCheck(config)