-
Notifications
You must be signed in to change notification settings - Fork 29
/
probe_accuracy_test_suite.py
992 lines (840 loc) · 30.3 KB
/
probe_accuracy_test_suite.py
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
#!/usr/bin/env python3
# klipper probe accuracy test suite
# Copyright (C) 2023 Foon Wong
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# ------------------------------------------------------------------------------
# Automating probe_accuracy testing
# The following three tests will be done:
# 0) 20 tests, 5 samples at bed center
# - check consistency within normal measurements
# 1) 1 test, 100 samples at bed center - check for drift
# 2) 1 test, 30 samples at each bed mesh corners
# - check if there are issues with individual z drives
# Notes:
# * First probe measurements are dropped
# ------------------------------------------------------------------------------
import argparse
import math
import os
import re
import subprocess
import sys
import requests
from datetime import datetime
from typing import Dict, List, Tuple
from matplotlib import pyplot
import numpy
from numpy.polynomial import Polynomial
import pandas
MOONRAKER_URL = "http://localhost:7125"
KLIPPY_LOG = "~/klipper_logs/klippy.log"
DATA_DIR = "/tmp"
RUNID = datetime.now().strftime("%Y%m%d_%H%M")
CLEAR_LINE = "\033[1A\x1b[2K"
# CLEAR_LINE = "\n\n"
class Probe():
def __init__(self, printer):
self.printer = printer
self.isKlicky = False
self.isKlippain = False
self.isTap = False
self.isBeacon = False
self._detect()
def is_present(self):
return (
self.isKlicky
or self.isKlippain
or self.isTap
or self.isBeacon
)
def lock(self, lock = True):
if self.isKlicky:
self.printer.gcode("ATTACH_PROBE_LOCK")
if self.isKlippain:
if lock:
self.printer.gcode("ACTIVATE_PROBE LOCK=true")
else:
self.printer.gcode("ACTIVATE_PROBE")
def unlock(self, unlock = False):
if self.isKlicky:
self.printer.gcode("DOCK_PROBE_UNLOCK")
elif self.isKlippain:
if unlock:
self.printer.gcode("DEACTIVATE_PROBE UNLOCK=true")
else:
self.printer.gcode("DEACTIVATE_PROBE")
def check_error(msg):
klicky_macro_issue = " ".join([
"!! Error evaluating 'gcode_macro PROBE_ACCURACY:gcode':",
"CommandError:",
"Must perform PROBE_ACCURACY with the probe above the BED!"
])
if klicky_macro_issue == msgs:
print("This issue can be fixed by updating klicky-macros.cfg")
print(
"Reference: https://github.com/jlas1/Klicky-Probe/commit/31a481c843567233c807bb310b6f0e83d60b4fca"
)
return
print("Unknown probe error.")
print("Exiting!")
sys.exit(1)
def _detect(self):
print("Probe type: ..." )
try:
user_variables = self.printer.query("gcode_macro _User_Variables")
if user_variables["docklocation_x"]:
self.isKlicky = True
print(f"{ CLEAR_LINE }Probe type: Klicky mode detected")
return
except:
pass
try:
user_variables = self.printer.query("gcode_macro _USER_VARIABLES")
if user_variables["probe_type_enabled"]:
if user_variables["probe_type_enabled"] == "dockable":
self.isKlippain = True
print(f"{ CLEAR_LINE }Probe type: Klippain mode detected")
return
except:
pass
try:
backlash_comp = self.printer.config["idm"].get("backlash_comp", 0)
#print(backlash_comp)
if backlash_comp:
self.isBeacon = True
print(f"{ CLEAR_LINE }Probe type: IDM probe detected")
except:
try:
backlash_comp = self.printer.config["beacon"].get("backlash_comp", 0)
#print(backlash_comp)
if backlash_comp:
self.isBeacon = True
print(f"{ CLEAR_LINE }Probe type: Beacon probe detected")
except:
try:
backlash_comp = self.printer.config["cartographer"].get("backlash_comp", 0)
#print(backlash_comp)
if backlash_comp:
self.isBeacon = True
print(f"{ CLEAR_LINE }Probe type: Cartographer probe detected")
except:
try:
endstop_pin = self.printer.config["stepper_z"]["endstop_pin"]
#print(endstop_pin)
if re.search("probe:\s*z_virtual_endstop", endstop_pin):
self.isTap = True
print(f"{ CLEAR_LINE }Probe type: Tap mode detected")
except:
pass
class Printer:
def __init__(self, moonraker_url):
self.moonraker_url = moonraker_url
self.config = self.query("configfile", "config")
self.settings = self.query("configfile", "settings")
self.probe = Probe(self)
self.safe_z = None
self.bed_center = self._get_bed_center()
self.bed_corners = self._get_bed_corners()
def get(self, endpoint, params = None):
return requests.get(
f"{ self.moonraker_url }{ endpoint }",
params = params
)
def post(self, endpoint, params = None):
return requests.post(
f"{ self.moonraker_url }{ endpoint }",
params = params
)
def query(self, object, key = None):
"""Query object"""
response = self.get("/printer/objects/query", object).json()
try:
obj = response["result"]["status"][object]
if key:
obj = obj[key]
return obj
except:
print(
f"Warning: {object}.{key} is not configured",
file = sys.stderr
)
return None
def get_gcode_store(self, count = 1000):
response = self.get("/server/gcode_store", { "count": count })
return response.json()["result"]["gcode_store"]
def gcode(self, gcode):
"""Send gcode to printer"""
self.post("/printer/gcode/script", { "script": gcode })
def conditional_home(self):
"""Home if not done already"""
homed_axes = self.query("toolhead", "homed_axes")
if homed_axes != "xyz":
self._home()
def move(
self,
x = None,
y = None,
z = None,
feedrate = 99999,
echo = False
):
if not z:
self._move_to_safe_z()
self._move(x, y, z, feedrate, echo)
def move_center(self):
self.move(*self.bed_center)
def move_random(self, max_range = 50):
self.move(*self._get_random_loc(max_range))
def level_bed(self, force = False):
"""Level bed if not done already or forced"""
ztilt = self.config.get("z_tilt")
qgl = self.config.get("quad_gantry_level")
print("Leveling...")
if ztilt:
gcode_cmd = "z_tilt_adjust"
leveled = self.query("z_tilt", "applied")
elif qgl:
gcode_cmd = "quad_gantry_level"
leveled = self.query("quad_gantry_level", "applied")
else:
print(
"User has no leveling gcode.",
"Please check printer.cfg [z_tilt] or [quad_gantry_level]"
)
print(f"{CLEAR_LINE}Leveling... Skipped")
return
if (not leveled) or force:
self.gcode(gcode_cmd)
print(f"{CLEAR_LINE}Leveling... Done")
def _print(self, msg):
print(msg)
self.gcode(f"M118 { msg }")
def _home(self):
print("Homing")
self.gcode("G28")
def _move(
self,
x = None,
y = None,
z = None,
feedrate = None,
echo = False
):
gcode_cmd = "G0"
if x != None:
gcode_cmd += f" X{ x }"
if y != None:
gcode_cmd += f" Y{ y }"
if z != None:
gcode_cmd += f" Z{ z }"
if feedrate != None:
gcode_cmd += f" F{ feedrate }"
if echo:
self._print(gcode_cmd)
self.gcode("G90")
self.gcode(gcode_cmd)
def _move_to_safe_z(self):
if not self.safe_z:
if self.probe.isKlicky:
self.safe_z = self.query(
"gcode_macro _User_Variables",
"safe_z"
)
elif self.probe.isKlippain:
self.safe_z = self.query(
"gcode_macro _USER_VARIABLES",
"probe_min_z_travel"
)
elif self.probe.isTap:
self.safe_z = (
self.settings
.get("safe_z_home", {})
.get("z_hop", None)
)
elif self.probe.isBeacon:
self.safe_z = 2
if not self.safe_z:
print(
"Safe z has not been set in klicky-variables",
"or in [safe_z_home]"
)
self.safe_z = input("Enter safe z height to avoid crash:")
self._move(z = self.safe_z)
def _get_bed_center(self) -> Tuple:
xmin, ymin, _, _ = self.query("toolhead", "axis_minimum")
xmax, ymax, _, _ = self.query("toolhead", "axis_maximum")
x = numpy.mean([xmin, xmax])
y = numpy.mean([ymin, ymax])
return (x, y)
def _get_random_loc(self, max_range = 50):
xmin, ymin, _, _ = self.query("toolhead", "axis_minimum")
xmax, ymax, _, _ = self.query("toolhead", "axis_maximum")
x = (
numpy.random.random()
* (xmax - xmin - 2 * max_range)
+ max_range + xmin
)
y = (
numpy.random.random()
* (ymax - ymin - 2 * max_range)
+ max_range + ymin
)
return (x, y)
### TODO: if quad gantry level use those points to probe the corners, if not qgl, then calculate the corner probe points
def _get_bed_corners(self) -> List:
# try:
# corners_list = self.config["quad_gantry_level"]["points"]
# #print(f"{corners_list}")
# except:
# pass
try:
x_offset = self.config["probe"].get("x_offset", 0)
y_offset = self.config["probe"].get("y_offset", 0)
except:
try:
x_offset = self.config["idm"].get("x_offset", 0)
y_offset = self.config["idm"].get("y_offset", 0)
except:
try:
x_offset = self.config["cartographer"].get("x_offset", 0)
y_offset = self.config["cartographer"].get("y_offset", 0)
except:
try:
x_offset = self.config["beacon"].get("x_offset", 0)
y_offset = self.config["beacon"].get("y_offset", 0)
except:
pass
# print(f"x_offset{x_offset}\ny_offset{y_offset}")
xmin, ymin = re.findall(r"[\d.]+", self.config["bed_mesh"]["mesh_min"])
xmax, ymax = re.findall(r"[\d.]+", self.config["bed_mesh"]["mesh_max"])
# print(f"xmin{xmin}\nymin{ymin}\nxmax{xmax}\nymax{ymax}")
xmin = float(xmin) - float(x_offset)
ymin = float(ymin) - float(y_offset)
xmax = float(xmax) - float(x_offset)
ymax = float(ymax) - float(y_offset)
return [(xmin, ymax), (xmax, ymax), (xmin, ymin), (xmax, ymin)]
class Test_suite():
def __init__(
self,
printer,
corner,
repeatability,
drift,
speedtest,
force_dock = False,
retract = False,
speed = None,
keep_first = False,
output_dir = "/tmp",
export_csv = False,
**kwargs
):
self.printer = printer
self.corner = corner
self.repeatability = repeatability
self.drift = drift
self.speedtest = speedtest
self.force_dock = force_dock
self.retract = retract
self.speed = speed
self.keep_first = keep_first
self.output_dir = output_dir
self.export_csv = export_csv
self.testframes = []
def run(self):
if self.corner:
self.test_corner()
if self.repeatability:
self.test_repeatability()
if self.drift:
self.test_drift()
if self.speedtest:
self.test_speedtest()
suiteframe = pandas.concat(
self.testframes,
axis = 0,
ignore_index = True
).sort_index()
summary = self._summarize_results(suiteframe, echo = False)
file_nm = f"{ RUNID }_probe_accuracy_test"
if self.export_csv:
suiteframe.to_csv(
f"{ self.output_dir }/{ file_nm }.csv",
index = False
)
summary.to_csv(
f"{ self.output_dir }/{ file_nm }_summary.csv"
)
def test_corner(self):
print("\nCorner test:")
print(
"Test probe around the bed to see if there are issues",
"with individual drives"
)
if self.corner < 10:
print(f"The minimum corner count is 10, updating test count from {self.corner} to 10")
self.corner = 10
self.printer.level_bed(force = True)
if not self.force_dock:
self.printer.probe.lock(lock = True)
print(f"Test number: ", end = "", flush = True)
dataframes = []
for i, xy in enumerate(self.printer.bed_corners):
print(f"{ 4 - i }...", end = "", flush = True)
self.printer.gcode(f"M117 Corner test { i + 1 }/4")
xy_txt = f"({xy[0]:.0f}, {xy[1]:.0f})"
dataframe = self._test_probe(
probe_count = self.corner,
loc = xy,
testname = f"{ i + 1}: corner { self.corner } samples {xy_txt}"
)
dataframe["measurement"] = f"{ i + 1 }: { xy_txt }"
dataframes.append(dataframe)
print("Done")
if not self.force_dock:
self.printer.probe.unlock(unlock = True)
testframe = pandas.concat(dataframes, axis = 0)
self._summarize_results(testframe)
plot_nm = f"{ RUNID } Corner Test\n({ self.corner } samples)"
self._facet_plot(testframe, cols = 2, plot_nm = plot_nm)
self._plot_boxplot(testframe, plot_nm)
self.testframes.append(testframe)
def test_repeatability(self, probe_count = 10):
print("\nRepeatability test:")
print(
f"Take { self.repeatability } probe_accuracy tests",
"to check for repeatability"
)
if not self.force_dock:
self.printer.probe.lock(lock = True)
print("Test number: ", end="", flush=True)
dataframes = []
for i in range(self.repeatability):
print(f"{self.repeatability - i}...", end="", flush=True)
self.printer.gcode(
f"M117 {i+1}/{ self.repeatability } repeatability"
)
for i in range(4):
self.printer.move_random()
dataframe = self._test_probe(
probe_count = probe_count,
testname=f"{i+1:02d}: center {probe_count} samples"
)
dataframe["measurement"] = f"Test #{i+1:02d}"
dataframes.append(dataframe)
print("Done")
if not self.force_dock:
self.printer.probe.unlock(unlock = True)
testframe = pandas.concat(dataframes, axis = 0).sort_index()
self._summarize_results(testframe)
self._summarize_repeatability(testframe)
plot_nm = f"{ RUNID } Repeatability Test\n({ probe_count } samples)"
self._facet_plot(testframe, plot_nm = plot_nm)
self._plot_boxplot(testframe, plot_nm)
self.testframes.append(testframe)
def test_drift(self):
print("\nDrift test:")
print(f"Take { self.drift } samples in a row to check for drift")
testframe = self._test_probe(
probe_count = self.drift,
testname = f"center { self.drift } samples"
)
testframe["measurement"] = ""
self._summarize_results(testframe)
plot_nm = f"{ RUNID } Drift Test\n({ self.drift } samples)"
fig, ax = pyplot.subplots()
self._plot_probes(
testframe["sample_index"].astype(int),
testframe["z"],
"",
ax
)
fig.suptitle(plot_nm)
fig.tight_layout()
file_nm = plot_nm.split("\n")[0].lower().replace(" ", "_")
fig.savefig(f"{ self.output_dir }/{ file_nm }.png")
self.testframes.append(testframe)
def test_speedtest(self):
print("\nZ-Probe speed test:")
print("Test a range of z-probe speed")
try:
print("")
speedrange = {
"start": float(input("Minimum speed? ")),
"stop": float(input("Maximum speed? ")),
"step": float(input("Steps between speeds? ")),
}
print("")
self._speedcheck(speedrange)
speeds = list(numpy.arange(**speedrange))
speeds.append(speedrange["stop"])
except Exception as e:
print("Invalid user input. Exiting...")
print(e)
sys.exit(0)
self.printer.level_bed()
if not self.force_dock:
self.printer.probe.lock(lock = True)
print("Test speeds: ", end="", flush=True)
dataframes = []
for spd in speeds:
print(f"{ spd } mm/s...", end="", flush=True)
self.printer.gcode(f"M117 { spd } mm/s probe speed")
dataframe = self._test_probe(
probe_count = 10,
testname = spd,
speed = spd
)
dataframe["measurement"] = f"Speed {spd: 2.1f}"
dataframes.append(dataframe)
print("Done")
if not self.force_dock:
self.printer.probe.unlock(unlock = True)
testframe = pandas.concat(dataframes, axis = 0)
self._summarize_results(testframe)
plot_nm = f"{ RUNID } Speed Test)"
self._facet_plot(testframe, cols = 5, plot_nm = plot_nm)
self._plot_boxplot(testframe, plot_nm)
self.testframes.append(testframe)
def _speedcheck(self, speeds):
assert speeds["step"] > 0
assert speeds["start"] >= 1
assert speeds["stop"] >= speeds["start"]
if speeds["stop"] >= 35:
print(f"Warning: your maxmimum speeds will be { speeds['stop'] }")
confirm = None
while not (confirm == "y" or confirm == "n"):
confirm = input("confirm? (y/n) ")
if confirm == "n":
assert False
def _test_probe(
self,
probe_count,
loc = None,
testname = "",
keep_first = False,
speed = None
):
"""
Send probe_accuracy command, and retrieve data
from gcod respond cache
"""
if loc:
self.printer.move(*loc)
else:
self.printer.move_center()
start_time = self.printer.get_gcode_store(count = 1)[0]["time"]
gcode_cmd = f"PROBE_ACCURACY SAMPLES={ probe_count }"
if self.retract:
gcode_cmd += f" SAMPLE_RETRACT_DIST={ self.retract }"
if speed:
gcode_cmd += f" PROBE_SPEED={ speed }"
elif self.speed:
gcode_cmd += f" PROBE_SPEED={ self.speed }"
self.printer.gcode(gcode_cmd)
raw = self.printer.get_gcode_store(count = 1000)
gcode_resp = [
x
for x in raw
if x["time"] > start_time
]
err_msgs = [
x["message"]
for x in gcode_resp
if x["message"].startswith("!!")
]
msgs = [
x["message"]
for x in gcode_resp
if x["message"].startswith("// probe at")
]
if len(err_msgs):
print("\nSomething's wrong with probe_accuracy! Klipper response:")
for msg in err_msgs:
print(msg)
self.printer.probe.check_error(msg)
data = []
for i, msg in enumerate(msgs):
coor = re.findall(r"[\d.]+", msg)
# print(f"\n\n {coor}")
if self.printer.probe.isBeacon:
x, y, _, z = [float(k) for k in coor]
else:
x, y, z = [float(k) for k in coor]
data.append({
"test": testname,
"sample_index": i,
"x": x,
"y": y,
"z": z
})
if len(data) == 0:
print("\nNo measurements collected")
print("Exiting!")
sys.exit(1)
try:
printer_config_drop_first = self.printer.config["probe"].get("drop_first_result")
except:
printer_config_drop_first = False
if (
printer_config_drop_first # self.printer.config["probe"].get("drop_first_result") == "True"
and not keep_first
):
data.pop(0)
return pandas.DataFrame(data)
def _summarize_results(self, testframe, echo = True):
summary = testframe.groupby("test")["z"].agg(
["min", "max", "first", "last", "mean", "std", "count"]
)
summary["range"] = summary["max"] - summary["min"]
summary["drift"] = summary["last"] - summary["first"]
if echo:
print("")
print(summary)
return summary
def _summarize_repeatability(self, testframe):
try:
probe_config = self.printer.config["probe"]
agg_method = probe_config.get("samples_result")
agg_method = "mean" if agg_method != "median" else "median"
except:
agg_method = "mean"
n = testframe["sample_index"].drop_duplicates().shape[0]
n_test = testframe["measurement"].drop_duplicates().shape[0]
# If first sample was dropped, need to shift starting index to 1
first_sample_dropped = (
1 if (testframe["sample_index"].min() == 1) else 0
)
tmp = []
for i in range(n):
stats = (
testframe[
testframe["sample_index"] <= (i + first_sample_dropped)
]
.groupby(["measurement"])
.z.agg(agg_method)
.agg(["mean", "min", "max", "std"])
.to_dict()
)
stats.update({
"range": stats["max"] - stats["min"],
"sample_count": i + 1
})
tmp.append(stats)
msg = " ".join([
"\nYour probe config uses",
f'{ agg_method } of { testframe["sample_index"].max() + 1 }',
f"sample(s) over { n_test } tests"
])
if first_sample_dropped:
msg += " with the first sample dropped"
msg += ", ".join([
f"\nBelow is the statistics on your { agg_method } Z values",
"using different probe samples\n"
])
print(msg)
print(pandas.DataFrame(tmp))
def _facet_plot(
self,
testframe,
cols = 5,
plot_nm = None,
):
tf_group = testframe.groupby("measurement")
rows = math.ceil(tf_group.ngroups / cols)
fig, axs = pyplot.subplots(
rows,
cols,
sharex = True,
figsize = (cols * 6, rows * 5 + 3)
)
for (measurement, testframe), ax in zip(tf_group, axs.ravel()):
x, y = testframe["sample_index"].astype(int), testframe["z"]
self._plot_probes(x, y, measurement, ax)
fig.suptitle(plot_nm)
fig.tight_layout()
file_nm = plot_nm.split("\n")[0].lower().replace(" ", "_")
fig.savefig(f"{ self.output_dir }/{ file_nm }.png")
def _plot_probes(self, x, y, measurement, ax):
polynom = Polynomial.fit(x, y, deg=3)
median = y.median()
range = y.max() - y.min()
range50 = y.quantile(0.75) - y.quantile(0.25)
range_flag = "!" * math.floor(range / 0.01)
std_flag = "!" if y.std() > 0.004 else ""
ylim = round(median, 3) - 0.01, round(median, 3) + 0.01
title = f"""
{measurement}
Mean:{y.mean():.4f} Std:{y.std():.4f}{std_flag}
Median:{y.median():.4f} Mid 50% range:{range50:.4f}
Range:{range:.4f}{range_flag} Min:{y.min():.4f} Max:{y.max():.4f}
"""
outofbound = sum(y < median - 0.01) + sum(y > median + 0.01)
if outofbound:
title += " ".join([
f"\n{outofbound} sample{'s are' if outofbound > 1 else ' is'}",
"outside of median±0.01mm range"
])
ax.plot(x, y, ".", x, polynom(x), "-.")
ax.set(xlabel = "probe sample", ylabel = "z")
ax.set_ylim(*ylim)
ax.set_yticks(numpy.arange(ylim[0], ylim[1] + 0.002, 0.002))
ax.fill_between(
x,
y.quantile(0.75),
y.quantile(0.25),
color = (0, 1, 0, 0.3)
)
ax.fill_between(x, median - 0.005, color = (1, 0, 0, 0.1))
ax.fill_between(x, 100, median + 0.005, color = (1, 0, 0, 0.1))
ax.set_title(title, fontsize=9)
def _plot_boxplot(self, testframe, plot_nm = ""):
pyplot.title(plot_nm)
pyplot.suptitle("")
file_nm = plot_nm.split("\n")[0].lower().replace(" ", "_")
ax = testframe.boxplot(column="z", by="measurement", rot=45, fontsize=8)
ax.figure.savefig(f"{ self.output_dir }/{ file_nm }(box).png")
def main(userparams):
if not os.path.exists(userparams['output_dir']):
os.makedirs(userparams['output_dir'], exist_ok=True)
printer = Printer(MOONRAKER_URL)
if not printer.probe.is_present():
print("ERROR: No probe could be found.", file = sys.stderr)
sys.exit(1)
elif not userparams["detect_probe"]:
try:
printer.conditional_home()
printer.move_center()
if (not (
userparams["corner"]
or userparams["repeatability"]
or userparams["drift"]
or userparams["speedtest"]
)):
print("Running all tests")
userparams.update({
"corner": 30,
"repeatability": 20,
"drift": 100
})
printer_test_suite = Test_suite(printer, **userparams)
printer_test_suite.run()
except KeyboardInterrupt:
pass
finally:
printer.probe.unlock()
printer.move_center()
def fetch_repo():
script_path = os.path.realpath(__file__)
repo_path = os.path.dirname(script_path)
wd = os.getcwd()
print(f"Changing directory to {repo_path}")
os.chdir(repo_path)
output = subprocess.run(["git", "pull"], capture_output=True)
print(output.stdout.decode("utf-8"))
print(f"Changing directory to {wd}. Please re-run without the --update flag")
os.chdir(wd)
pass
if __name__ == "__main__":
ap = argparse.ArgumentParser(
description = """
Automated probe testing.
All three tests will run at default values unless individual tests are specified
"""
)
ap.add_argument(
"-c",
"--corner",
nargs = "?",
type = int,
const = 30,
help = "Enable corner test. Number of probe samples at each corner can be optionally provided. Default 30.",
)
ap.add_argument(
"-r",
"--repeatability",
nargs = "?",
type = int,
const = 20,
help = "Enable repeatability test. Number of probe_accuracy tests can be optionally provided. Default 20.",
)
ap.add_argument(
"-d",
"--drift",
nargs = "?",
type = int,
const = 100,
help = "Enable drift test. Number of probe_accuracy samples can be optionally provided. Default 100.",
)
ap.add_argument(
"--speedtest",
action = "store_true",
help = "Enable probe speed test. Requires user input for speed parameters.",
)
ap.add_argument(
"--export_csv",
action = "store_true",
help = "export data as csv",
)
ap.add_argument(
"--force_dock",
action = "store_true",
help = "Force docking between tests. Default False",
)
ap.add_argument(
"--keep_first",
action = "store_true",
help = "Keep first probe measurement",
)
ap.add_argument(
"-s",
"--speed",
nargs = 1,
type = float,
help = "probe speed",
)
ap.add_argument(
"--retract",
nargs = 1,
type = float,
help = "probe sample retract distance",
)
ap.add_argument(
"-o",
"--output_dir",
type = str,
help = "Output folder for testresults",
)
ap.add_argument(
"-u",
"--update",
action = "store_true",
help = "Updates the script with git",
)
ap.add_argument(
"-t",
"--detect_probe",
action = "store_true",
help = "Simple test probe mode",
)
args = vars(ap.parse_args())
if args["update"]:
fetch_repo()
sys.exit(0)
if not args["output_dir"]:
args["output_dir"] = DATA_DIR
else:
args["output_dir"] = str(args["output_dir"]).rstrip("/")
main(args)