-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_Scan_TopCamera_Rectangle.js
More file actions
4170 lines (3860 loc) · 177 KB
/
Copy path01_Scan_TopCamera_Rectangle.js
File metadata and controls
4170 lines (3860 loc) · 177 KB
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
993
994
995
996
997
998
999
1000
/**
* 01: Scan the predefined rectangle with the Top camera and save images.
*
* Area:
* X 361 to 411
* Y 208 to 319
*
* Output:
* <OpenPnP config>/scans/<scan_id>/
* frames/*.png
* manifest.jsonl
*
* Cooperative pause/resume/halt:
* If <OpenPnP config>/control/pause.flag exists, the
* scan pauses before the next move. Clearing the flag resumes the same run.
* If <OpenPnP config>/control/stop.flag exists, the
* scan exits before the next move.
* The halt control GUI is launched automatically at scan start.
*/
load(scripting.getScriptsDirectory().toString() + '/Examples/JavaScript/Utility.js');
var imports = new JavaImporter(org.openpnp.model, java.io, javax.imageio, javax.swing, java.awt);
with (imports) {
var scriptsRootDir = new File(scripting.getScriptsDirectory().toString());
var scriptsDir = scriptsRootDir.getName() === 'BugPicker'
? scriptsRootDir
: new File(scriptsRootDir, 'BugPicker');
if (!scriptsDir.exists()) {
scriptsDir = scriptsRootDir;
}
var projectDir = scriptsRootDir.getName() === 'BugPicker'
&& scriptsRootDir.getParentFile() !== null
&& scriptsRootDir.getParentFile().getName() === 'scripts'
? scriptsRootDir.getParentFile().getParentFile()
: scriptsRootDir.getParentFile();
var localPython = new File(projectDir, '.venv/bin/python');
var previousPython = new File('/home/sean/Documents/OpenInvert-PnP/.venv/bin/python');
var python = localPython.exists()
? localPython.getAbsolutePath()
: previousPython.exists()
? previousPython.getAbsolutePath()
: 'python3';
var currentCoordinateTransformVersion = 'image_y_inverted_v2';
function pad(number, width) {
var text = String(number);
while (text.length < width) {
text = '0' + text;
}
return text;
}
function timestamp() {
var now = new Date();
return now.getFullYear()
+ pad(now.getMonth() + 1, 2)
+ pad(now.getDate(), 2)
+ '_'
+ pad(now.getHours(), 2)
+ pad(now.getMinutes(), 2)
+ pad(now.getSeconds(), 2);
}
function positions(start, stop, step, descending) {
var values = [];
var epsilon = 0.000001;
if (descending) {
for (var value = start; value >= stop + epsilon; value -= step) {
values.push(value);
}
if (values.length === 0 || Math.abs(values[values.length - 1] - stop) > epsilon) {
values.push(stop);
}
}
else {
for (var value = start; value <= stop - epsilon; value += step) {
values.push(value);
}
if (values.length === 0 || Math.abs(values[values.length - 1] - stop) > epsilon) {
values.push(stop);
}
}
return values;
}
function jsonLine(frameIndex, fileName, x, y, requestedX, requestedY, width, height, unitsPerPixel) {
var record = {
frame_index: frameIndex,
file_name: fileName,
camera: 'Top',
x_mm: x,
y_mm: y,
requested_x_mm: requestedX,
requested_y_mm: requestedY,
image_width_px: width,
image_height_px: height,
units_per_pixel_x_mm: unitsPerPixel.x,
units_per_pixel_y_mm: unitsPerPixel.y
};
return JSON.stringify(record) + '\n';
}
function formatLocation(location) {
return 'X=' + location.x.toFixed(3)
+ ' Y=' + location.y.toFixed(3)
+ ' Z=' + location.z.toFixed(3)
+ ' R=' + location.rotation.toFixed(3);
}
function getUnitsPerPixelForCurrentZ(camera) {
try {
return camera.getUnitsPerPixelAtZ();
}
catch (error) {
return camera.getUnitsPerPixel();
}
}
function findCameraByName(name) {
function cameraMatches(camera) {
return camera && String(camera.getName()) === name;
}
try {
if (cameraMatches(machine.defaultHead.defaultCamera)) {
return machine.defaultHead.defaultCamera;
}
}
catch (defaultError) {
print('Could not check default head camera for ' + name + ': ' + defaultError);
}
try {
var headCameras = machine.defaultHead.getCameras();
for (var headIndex = 0; headIndex < headCameras.size(); headIndex++) {
var headCamera = headCameras.get(headIndex);
if (cameraMatches(headCamera)) {
return headCamera;
}
}
}
catch (headError) {
print('Could not enumerate head cameras while looking for ' + name + ': ' + headError);
}
try {
var machineCameras = machine.getCameras();
for (var machineIndex = 0; machineIndex < machineCameras.size(); machineIndex++) {
var machineCamera = machineCameras.get(machineIndex);
if (cameraMatches(machineCamera)) {
return machineCamera;
}
}
}
catch (machineError) {
print('Could not enumerate machine cameras while looking for ' + name + ': ' + machineError);
}
throw new Error('Camera not found: ' + name);
}
function writeText(file, text) {
var writer = new FileWriter(file);
try {
writer.write(text);
}
finally {
writer.close();
}
}
function readText(file) {
var reader = new BufferedReader(new FileReader(file));
var lines = [];
try {
var line = reader.readLine();
while (line !== null) {
lines.push(String(line));
line = reader.readLine();
}
}
finally {
reader.close();
}
return lines.join('\n');
}
function readNumber(record, key, fallback) {
if (record[key] === undefined || record[key] === null || record[key] === '') {
return fallback;
}
var value = Number(record[key]);
if (isNaN(value)) {
throw new Error('Calibration value is not numeric: ' + key + '=' + record[key]);
}
return value;
}
function trayHeightPresets() {
return [
{
label: '12.5 mm tray - medium insects',
trayHeightMm: 12.5,
sizeClass: 'medium',
pickZMm: -43.3
},
{
label: 'Small insects',
trayHeightMm: 12.5,
sizeClass: 'small',
pickZMm: -43.6
},
{
label: 'Large insects',
trayHeightMm: 12.5,
sizeClass: 'large',
pickZMm: -42.8
}
];
}
function defaultTrayHeightPreset() {
return trayHeightPresets()[0];
}
function findTrayHeightPresetIndex(calibration) {
var presets = trayHeightPresets();
for (var i = 0; i < presets.length; i++) {
if (Math.abs(Number(calibration.pickZMm) - Number(presets[i].pickZMm)) < 0.001
&& String(calibration.sizeClass) === String(presets[i].sizeClass)) {
return i;
}
}
return 0;
}
function defaultTrainingTrayCalibrationValues() {
return {
xLeft: 361.0,
xRight: 411.0,
yTop: 208.0,
yBottom: 319.0,
cameraXOffsetMm: -23.0,
cameraYOffsetMm: 64.0,
scanBoundsAreCameraCoordinates: false,
xStepMm: 8.0,
yStepMm: 5.0,
plateA1X: 72.4,
plateA1Y: 238.6,
plateWellPitchMm: 9.0
};
}
function loadTrainingTrayCalibration(defaults) {
var localCalibrationFile = new File(scriptsDir, 'training_tray_calibration.json');
var controlCalibrationFile = new File(projectDir, 'control/training_tray_calibration.json');
var calibrationFile = localCalibrationFile.exists() ? localCalibrationFile : controlCalibrationFile;
var defaultPreset = defaultTrayHeightPreset();
var calibration = {
xLeft: defaults.xLeft,
xRight: defaults.xRight,
yTop: defaults.yTop,
yBottom: defaults.yBottom,
cameraXOffsetMm: defaults.cameraXOffsetMm,
cameraYOffsetMm: defaults.cameraYOffsetMm,
scanBoundsAreCameraCoordinates: defaults.scanBoundsAreCameraCoordinates,
xStepMm: defaults.xStepMm,
yStepMm: defaults.yStepMm,
trayHeightMm: defaultPreset.trayHeightMm,
sizeClass: defaultPreset.sizeClass,
pickZMm: defaultPreset.pickZMm,
plateA1X: defaults.plateA1X,
plateA1Y: defaults.plateA1Y,
plateWellPitchMm: defaults.plateWellPitchMm,
source: 'built-in defaults'
};
if (!calibrationFile.exists()) {
return calibration;
}
var record = JSON.parse(readText(calibrationFile));
calibration.xLeft = readNumber(record, 'x_left_mm', calibration.xLeft);
calibration.xRight = readNumber(record, 'x_right_mm', calibration.xRight);
calibration.yTop = readNumber(record, 'y_top_mm', calibration.yTop);
calibration.yBottom = readNumber(record, 'y_bottom_mm', calibration.yBottom);
calibration.cameraXOffsetMm = readNumber(record, 'camera_x_offset_mm', calibration.cameraXOffsetMm);
calibration.cameraYOffsetMm = readNumber(record, 'camera_y_offset_mm', calibration.cameraYOffsetMm);
calibration.scanBoundsAreCameraCoordinates = record.scan_bounds_are_camera_coordinates === undefined
? calibration.scanBoundsAreCameraCoordinates
: Boolean(record.scan_bounds_are_camera_coordinates);
calibration.xStepMm = readNumber(record, 'x_step_mm', calibration.xStepMm);
calibration.yStepMm = readNumber(record, 'y_step_mm', calibration.yStepMm);
calibration.trayHeightMm = readNumber(record, 'tray_height_mm', calibration.trayHeightMm);
calibration.sizeClass = record.size_class === undefined ? calibration.sizeClass : String(record.size_class);
calibration.pickZMm = readNumber(record, 'pick_z_mm', calibration.pickZMm);
calibration.plateA1X = readNumber(record, 'plate_a1_x_mm', calibration.plateA1X);
calibration.plateA1Y = readNumber(record, 'plate_a1_y_mm', calibration.plateA1Y);
calibration.plateWellPitchMm = readNumber(record, 'plate_well_pitch_mm', calibration.plateWellPitchMm);
calibration.source = calibrationFile.getAbsolutePath();
return calibration;
}
function trainingTrayCalibrationFile() {
return new File(scriptsDir, 'training_tray_calibration.json');
}
function writeTrainingTrayCalibration(calibration) {
var record = {
x_left_mm: calibration.xLeft,
x_right_mm: calibration.xRight,
y_top_mm: calibration.yTop,
y_bottom_mm: calibration.yBottom,
camera_x_offset_mm: calibration.cameraXOffsetMm,
camera_y_offset_mm: calibration.cameraYOffsetMm,
scan_bounds_are_camera_coordinates: calibration.scanBoundsAreCameraCoordinates,
x_step_mm: calibration.xStepMm,
y_step_mm: calibration.yStepMm,
tray_height_mm: calibration.trayHeightMm,
size_class: calibration.sizeClass,
pick_z_mm: calibration.pickZMm,
plate_a1_x_mm: calibration.plateA1X,
plate_a1_y_mm: calibration.plateA1Y,
plate_well_pitch_mm: calibration.plateWellPitchMm
};
var file = trainingTrayCalibrationFile();
writeText(file, JSON.stringify(record, null, 2) + '\n');
calibration.source = file.getAbsolutePath();
print('Saved training tray calibration: ' + calibration.source);
}
function numberFieldValue(field, name) {
var value = Number(String(field.getText()).trim());
if (isNaN(value)) {
throw new Error(name + ' must be a number.');
}
return value;
}
function raisePickerToCalibrationTravelZ(nozzle, travelZ, context) {
if (nozzle === null || travelZ === null || isNaN(Number(travelZ))) {
return;
}
print('Raising picker to calibration travel Z=' + Number(travelZ).toFixed(3)
+ ' before ' + context);
moveNozzleToXyAtZ(nozzle, nozzle.location.x, nozzle.location.y, Number(travelZ));
}
function commandCameraToTrayPoint(camera, calibration, xField, yField, label, nozzle, calibrationTravelZ) {
var requestedX = numberFieldValue(xField, label + ' X');
var requestedY = numberFieldValue(yField, label + ' Y');
var cameraX = calibration.scanBoundsAreCameraCoordinates
? requestedX
: requestedX + calibration.cameraXOffsetMm;
var cameraY = calibration.scanBoundsAreCameraCoordinates
? requestedY
: requestedY + calibration.cameraYOffsetMm;
raisePickerToCalibrationTravelZ(nozzle, calibrationTravelZ, label + ' tray camera move');
print('Moving Top camera to ' + label
+ ' tray point X=' + requestedX.toFixed(3)
+ ' Y=' + requestedY.toFixed(3)
+ ' commanded camera X=' + cameraX.toFixed(3)
+ ' Y=' + cameraY.toFixed(3));
moveCameraToXy(camera, cameraX, cameraY);
print('Top camera after ' + label + ' move: ' + formatLocation(camera.getLocation()));
}
function commandPickerToPlateA1(nozzle, xField, yField, calibrationTravelZ) {
if (nozzle === null) {
throw new Error('Picker nozzle is not available.');
}
var x = numberFieldValue(xField, 'plate_a1_x_mm');
var y = numberFieldValue(yField, 'plate_a1_y_mm');
var travelZ = Number(calibrationTravelZ);
var dropZ = -33.5;
print('Moving picker to plate A1 candidate X=' + x.toFixed(3)
+ ' Y=' + y.toFixed(3)
+ ' at current travel Z=' + travelZ.toFixed(3)
+ ', then drop Z=' + dropZ.toFixed(3));
raisePickerToCalibrationTravelZ(nozzle, travelZ, 'plate A1 calibration move');
moveNozzleToXyAtZ(nozzle, x, y, travelZ);
warnDualNozzleZClearance(dropZ, 'plate A1 calibration descent');
moveNozzleToXyAtZ(nozzle, x, y, dropZ);
print('Picker after plate A1 move: ' + formatLocation(nozzle.location));
}
function promptForTrainingTrayBounds(calibration, camera, nozzle) {
var calibrationTravelZ = nozzle === null ? null : Number(nozzle.location.z);
while (true) {
var ActionListener = Packages.java.awt.event.ActionListener;
var JComboBox = Packages.javax.swing.JComboBox;
var DefaultComboBoxModel = Packages.javax.swing.DefaultComboBoxModel;
var panel = new JPanel(new GridLayout(3, 2, 12, 6));
var startPanel = new JPanel(new GridLayout(0, 2, 8, 6));
var endPanel = new JPanel(new GridLayout(0, 2, 8, 6));
var heightPanel = new JPanel(new GridLayout(0, 2, 8, 6));
var platePanel = new JPanel(new GridLayout(0, 2, 8, 6));
var runPanel = new JPanel(new GridLayout(0, 2, 8, 6));
var xLeftField = new JTextField(calibration.xLeft.toFixed(3), 10);
var xRightField = new JTextField(calibration.xRight.toFixed(3), 10);
var yTopField = new JTextField(calibration.yTop.toFixed(3), 10);
var yBottomField = new JTextField(calibration.yBottom.toFixed(3), 10);
var plateA1XField = new JTextField(Number(calibration.plateA1X).toFixed(3), 10);
var plateA1YField = new JTextField(Number(calibration.plateA1Y).toFixed(3), 10);
var platePitchField = new JTextField(Number(calibration.plateWellPitchMm).toFixed(3), 10);
var startWellField = new JTextField('A1', 10);
var plateNumberField = new JTextField('AA0001', 10);
var collectionCodeField = new JTextField('', 10);
var trayHeightField = new JTextField(Number(calibration.trayHeightMm).toFixed(3), 10);
var sizeClassField = new JTextField(String(calibration.sizeClass), 10);
var pickZField = new JTextField(Number(calibration.pickZMm).toFixed(3), 10);
var trayPresetModel = new DefaultComboBoxModel();
var presets = trayHeightPresets();
for (var presetIndex = 0; presetIndex < presets.length; presetIndex++) {
trayPresetModel.addElement(presets[presetIndex].label);
}
var trayPresetBox = new JComboBox(trayPresetModel);
trayPresetBox.setSelectedIndex(findTrayHeightPresetIndex(calibration));
var startMoveButton = new JButton('Move camera');
var endMoveButton = new JButton('Move camera');
var plateA1MoveButton = new JButton('Move picker to drop Z');
startPanel.setBorder(BorderFactory.createTitledBorder('Starting position'));
startPanel.add(new JLabel('X (x_left_mm)'));
startPanel.add(xLeftField);
startPanel.add(new JLabel('Y (y_top_mm)'));
startPanel.add(yTopField);
startPanel.add(new JLabel(''));
startPanel.add(startMoveButton);
endPanel.setBorder(BorderFactory.createTitledBorder('Ending position'));
endPanel.add(new JLabel('X (x_right_mm)'));
endPanel.add(xRightField);
endPanel.add(new JLabel('Y (y_bottom_mm)'));
endPanel.add(yBottomField);
endPanel.add(new JLabel(''));
endPanel.add(endMoveButton);
heightPanel.setBorder(BorderFactory.createTitledBorder('Tray height / pick Z'));
heightPanel.add(new JLabel('Preset'));
heightPanel.add(trayPresetBox);
heightPanel.add(new JLabel('Tray height mm'));
heightPanel.add(trayHeightField);
heightPanel.add(new JLabel('Size class'));
heightPanel.add(sizeClassField);
heightPanel.add(new JLabel('Pick Z mm'));
heightPanel.add(pickZField);
platePanel.setBorder(BorderFactory.createTitledBorder('96-well plate'));
platePanel.add(new JLabel('A1 X mm'));
platePanel.add(plateA1XField);
platePanel.add(new JLabel('A1 Y mm'));
platePanel.add(plateA1YField);
platePanel.add(new JLabel('Well pitch mm'));
platePanel.add(platePitchField);
platePanel.add(new JLabel(''));
platePanel.add(plateA1MoveButton);
runPanel.setBorder(BorderFactory.createTitledBorder('Plating run'));
runPanel.add(new JLabel('Begin plating in well'));
runPanel.add(startWellField);
runPanel.add(new JLabel('Plate number'));
runPanel.add(plateNumberField);
runPanel.add(new JLabel('Collection code'));
runPanel.add(collectionCodeField);
plateNumberField.addActionListener(new ActionListener({
actionPerformed: function(event) {
try {
var normalized = normalizePlateNumber(plateNumberField.getText());
plateNumberField.setText(normalized);
}
catch (error) {
JOptionPane.showMessageDialog(
null,
String(error.message || error),
'Invalid plate number',
JOptionPane.ERROR_MESSAGE
);
}
}
}));
function applyTrayPreset(index) {
var preset = presets[Math.max(0, Math.min(index, presets.length - 1))];
trayHeightField.setText(Number(preset.trayHeightMm).toFixed(3));
sizeClassField.setText(String(preset.sizeClass));
pickZField.setText(Number(preset.pickZMm).toFixed(3));
}
trayPresetBox.addActionListener(new ActionListener({
actionPerformed: function(event) {
applyTrayPreset(trayPresetBox.getSelectedIndex());
}
}));
startMoveButton.addActionListener(new ActionListener({
actionPerformed: function(event) {
try {
commandCameraToTrayPoint(
camera,
calibration,
xLeftField,
yTopField,
'starting',
nozzle,
calibrationTravelZ
);
}
catch (error) {
JOptionPane.showMessageDialog(
null,
String(error.message || error),
'Could not move camera',
JOptionPane.ERROR_MESSAGE
);
}
}
}));
endMoveButton.addActionListener(new ActionListener({
actionPerformed: function(event) {
try {
commandCameraToTrayPoint(
camera,
calibration,
xRightField,
yBottomField,
'ending',
nozzle,
calibrationTravelZ
);
}
catch (error) {
JOptionPane.showMessageDialog(
null,
String(error.message || error),
'Could not move camera',
JOptionPane.ERROR_MESSAGE
);
}
}
}));
plateA1MoveButton.addActionListener(new ActionListener({
actionPerformed: function(event) {
try {
commandPickerToPlateA1(nozzle, plateA1XField, plateA1YField, calibrationTravelZ);
}
catch (error) {
JOptionPane.showMessageDialog(
null,
String(error.message || error),
'Could not move picker',
JOptionPane.ERROR_MESSAGE
);
}
}
}));
panel.add(startPanel);
panel.add(endPanel);
panel.add(heightPanel);
panel.add(platePanel);
panel.add(runPanel);
var result = JOptionPane.showConfirmDialog(
null,
panel,
'Tray scan bounds',
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE
);
if (result !== JOptionPane.OK_OPTION) {
throw new Error('Scan cancelled before tray scan bounds were accepted.');
}
try {
var updated = {
xLeft: numberFieldValue(xLeftField, 'x_left_mm'),
xRight: numberFieldValue(xRightField, 'x_right_mm'),
yTop: numberFieldValue(yTopField, 'y_top_mm'),
yBottom: numberFieldValue(yBottomField, 'y_bottom_mm'),
cameraXOffsetMm: calibration.cameraXOffsetMm,
cameraYOffsetMm: calibration.cameraYOffsetMm,
scanBoundsAreCameraCoordinates: calibration.scanBoundsAreCameraCoordinates,
xStepMm: calibration.xStepMm,
yStepMm: calibration.yStepMm,
trayHeightMm: numberFieldValue(trayHeightField, 'tray_height_mm'),
sizeClass: String(sizeClassField.getText()).trim(),
pickZMm: numberFieldValue(pickZField, 'pick_z_mm'),
plateA1X: numberFieldValue(plateA1XField, 'plate_a1_x_mm'),
plateA1Y: numberFieldValue(plateA1YField, 'plate_a1_y_mm'),
plateWellPitchMm: numberFieldValue(platePitchField, 'plate_well_pitch_mm'),
source: calibration.source
};
var plateNumber = normalizePlateNumber(plateNumberField.getText());
var startWell = normalizeWellName(startWellField.getText());
var plateId = 'P-' + plateNumber;
var collectionCode = String(collectionCodeField.getText()).trim();
if (updated.xLeft === updated.xRight || updated.yTop === updated.yBottom) {
throw new Error('Tray scan bounds must span a non-zero X and Y range.');
}
if (updated.sizeClass.length === 0) {
throw new Error('Size class must not be blank.');
}
if (updated.plateWellPitchMm <= 0) {
throw new Error('Plate well pitch must be greater than zero.');
}
if (collectionCode.length === 0) {
throw new Error('Collection code must not be blank.');
}
if (updated.xLeft > updated.xRight) {
var swapX = updated.xLeft;
updated.xLeft = updated.xRight;
updated.xRight = swapX;
}
if (updated.yTop > updated.yBottom) {
var swapY = updated.yTop;
updated.yTop = updated.yBottom;
updated.yBottom = swapY;
}
if (plateCsvFile(plateNumber).exists()) {
var continueResult = JOptionPane.showConfirmDialog(
null,
'A spreadsheet already exists for plate ' + plateNumber
+ '. Continue plating onto this existing plate and editing its CSV?',
'Existing plate warning',
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (continueResult !== JOptionPane.YES_OPTION) {
throw new Error('Choose a new plate number or confirm that this is an existing plate.');
}
}
writeTrainingTrayCalibration(updated);
updated.plateContext = {
plateNumber: plateNumber,
plateId: plateId,
collectionCode: collectionCode,
startWell: startWell
};
return updated;
}
catch (validationError) {
JOptionPane.showMessageDialog(
null,
String(validationError.message || validationError),
'Invalid tray bounds',
JOptionPane.ERROR_MESSAGE
);
}
}
}
function appendText(file, text) {
var writer = new FileWriter(file, true);
try {
writer.write(text);
}
finally {
writer.close();
}
}
function writeStatus(statusFile, status, scanId, frameIndex, totalFrames, message) {
var record = {
status: status,
scan_id: scanId,
frame_index: frameIndex,
total_frames: totalFrames,
message: message,
updated_at: new Date().toISOString()
};
writeText(statusFile, JSON.stringify(record, null, 2) + '\n');
}
function plateSpreadsheetRoot() {
var dir = new File(projectDir, 'Plate_spreadsheets');
dir.mkdirs();
return dir;
}
function plateImageRoot() {
var dir = new File(projectDir, 'Plate_insect_images');
dir.mkdirs();
return dir;
}
function normalizePlateNumber(text) {
var value = String(text || '').trim().toUpperCase();
value = value.replace(/[^A-Z0-9_-]/g, '');
if (value.length === 0) {
throw new Error('Plate number must not be blank.');
}
return value;
}
function normalizeWellName(text) {
var value = String(text || '').trim().toUpperCase();
var match = /^([A-H])([1-9]|1[0-2])$/.exec(value);
if (match === null) {
throw new Error('Starting well must be A1 through H12.');
}
return match[1] + String(Number(match[2]));
}
function wellIndexForName(wellName) {
var normalized = normalizeWellName(wellName);
var rowIndex = normalized.charCodeAt(0) - 'A'.charCodeAt(0);
var columnIndex = Number(normalized.substring(1)) - 1;
return (rowIndex * 12) + columnIndex;
}
function plateCsvFile(plateNumber) {
return new File(plateSpreadsheetRoot(), normalizePlateNumber(plateNumber) + '.csv');
}
function plateCsvHeaders() {
return [
'no.',
'Plate number',
'Plate ID',
'Well Number',
'Extract ID',
'Collection Code',
'Image Code',
'Order',
'Current Status',
'DNA concentration (ng/\u00b5l)',
'Extract volume (\u00b5l)',
'quantified volume',
'Vol remaining',
'Gel Results',
'COI, ONT Sequencing Results',
'Link to ELN PCR page'
];
}
function csvEscape(value) {
var text = value === null || value === undefined ? '' : String(value);
if (text.indexOf('"') >= 0 || text.indexOf(',') >= 0 || text.indexOf('\n') >= 0 || text.indexOf('\r') >= 0) {
return '"' + text.replace(/"/g, '""') + '"';
}
return text;
}
function csvLine(values) {
var escaped = [];
for (var i = 0; i < values.length; i++) {
escaped.push(csvEscape(values[i]));
}
return escaped.join(',') + '\n';
}
function splitCsvLine(line) {
var values = [];
var current = '';
var quoted = false;
for (var i = 0; i < line.length; i++) {
var ch = line.charAt(i);
if (quoted) {
if (ch === '"') {
if (i + 1 < line.length && line.charAt(i + 1) === '"') {
current += '"';
i++;
}
else {
quoted = false;
}
}
else {
current += ch;
}
}
else if (ch === '"') {
quoted = true;
}
else if (ch === ',') {
values.push(current);
current = '';
}
else {
current += ch;
}
}
values.push(current);
return values;
}
function readPlateRows(plateNumber) {
var file = plateCsvFile(plateNumber);
var rows = [];
if (!file.exists()) {
return rows;
}
var reader = new BufferedReader(new FileReader(file));
try {
var line = reader.readLine();
var first = true;
while (line !== null) {
if (first) {
first = false;
}
else if (String(line).trim().length > 0) {
rows.push(splitCsvLine(String(line)));
}
line = reader.readLine();
}
}
finally {
reader.close();
}
return rows;
}
function occupiedWellSet(plateNumber) {
var rows = readPlateRows(plateNumber);
var occupied = {};
for (var i = 0; i < rows.length; i++) {
if (rows[i].length >= 4 && rows[i][3]) {
occupied[normalizeWellName(rows[i][3])] = true;
}
}
return occupied;
}
function imageCodeForWell(plateNumber, wellName) {
return 'IMG-DNA-' + normalizePlateNumber(plateNumber) + '-' + normalizeWellName(wellName);
}
function copyPlateWellImage(plateContext, well, sourceImageFile) {
if (sourceImageFile === null || sourceImageFile === undefined || !sourceImageFile.exists()) {
return null;
}
var imageCode = imageCodeForWell(plateContext.plateNumber, well.name);
var destination = new File(plateImageRoot(), imageCode + '.png');
Packages.java.nio.file.Files.copy(
sourceImageFile.toPath(),
destination.toPath(),
Packages.java.nio.file.StandardCopyOption.REPLACE_EXISTING
);
print('Copied plate well image to ' + destination.getAbsolutePath());
return destination;
}
function ensurePlateSpreadsheetHeader(plateContext) {
var file = plateCsvFile(plateContext.plateNumber);
if (!file.exists()) {
writeText(file, csvLine(plateCsvHeaders()));
print('Created plate spreadsheet CSV: ' + file.getAbsolutePath());
}
return file;
}
function appendPlateSpreadsheetRow(plateContext, well) {
var occupied = occupiedWellSet(plateContext.plateNumber);
if (occupied[well.name]) {
print('Plate spreadsheet already has well ' + well.name + '; not adding a duplicate row.');
return;
}
var file = ensurePlateSpreadsheetHeader(plateContext);
var nextNumber = readPlateRows(plateContext.plateNumber).length + 1;
var plateNumber = normalizePlateNumber(plateContext.plateNumber);
var row = [
nextNumber,
plateNumber,
plateContext.plateId,
well.name,
'DNA-' + plateNumber + '-' + well.name,
plateContext.collectionCode,
imageCodeForWell(plateNumber, well.name),
'',
'',
'',
'',
'',
'',
'',
'',
''
];
appendText(file, csvLine(row));
print('Recorded plated specimen in ' + file.getAbsolutePath() + ' well ' + well.name);
}
function wellQueueFromStart(plateContext) {
var startIndex = wellIndexForName(plateContext.startWell);
var occupied = occupiedWellSet(plateContext.plateNumber);
var wells = [];
for (var i = startIndex; i < 96; i++) {
var name = wellNameForIndex(i);
if (!occupied[name]) {
wells.push(i);
}
}
return wells;
}
function promptRetryEmptyWells(emptyWells) {
if (!emptyWells || emptyWells.length === 0) {
return [];
}
var panel = new JPanel(new BorderLayout(8, 8));
var listPanel = new JPanel(new GridLayout(0, 1, 6, 6));
var checkboxes = [];
for (var i = 0; i < emptyWells.length; i++) {
var row = new JPanel(new BorderLayout(6, 6));
var checkbox = new JCheckBox(
'Refill ' + emptyWells[i].name + ' - ' + String(emptyWells[i].reason || 'empty'),
true
);
checkboxes.push(checkbox);
row.add(checkbox, BorderLayout.NORTH);
if (emptyWells[i].imageFile !== null && emptyWells[i].imageFile.exists()) {
var icon = scaledIconForFile(emptyWells[i].imageFile, Packages.javax.swing.ImageIcon, Packages.java.awt.Image, 360, 220);
if (icon !== null) {
var imageLabel = new JLabel(icon);
row.add(imageLabel, BorderLayout.CENTER);
}
}
listPanel.add(row);
}
panel.add(
new JLabel('Review wells not confirmed occupied. Uncheck any well that already contains a specimen.'),
BorderLayout.NORTH
);
var scroll = new JScrollPane(listPanel);
scroll.setPreferredSize(new Dimension(520, Math.min(640, 120 + (emptyWells.length * 90))));
panel.add(scroll, BorderLayout.CENTER);
var result = JOptionPane.showConfirmDialog(
null,
panel,
'Empty well review',
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (result !== JOptionPane.OK_OPTION) {
return [];
}
var selectedWells = [];
for (var selectedIndex = 0; selectedIndex < emptyWells.length; selectedIndex++) {
if (checkboxes[selectedIndex].isSelected()) {
selectedWells.push(emptyWells[selectedIndex]);
}
}
return selectedWells;
}
function writePickingPreview(scanDir, scanId, target, targetIndex, totalTargets, moveX, moveY, extraFields) {
var detectionStatusFile = new File(projectDir, 'control/detection_status.json');
var previewFile = target.overlayFile && target.overlayFile.length > 0
? new File(scanDir, target.overlayFile)
: target.contextFile && target.contextFile.length > 0
? new File(scanDir, target.contextFile)
: new File(scanDir, target.cropFile);
var record = {
status: 'detected',
scan_dir: scanDir.getAbsolutePath(),
updated_at: new Date().toISOString(),
frame_index: target.frameIndex,
source_file: target.sourceFile,
overlay_file: target.overlayFile,
preview_file: previewFile.getAbsolutePath(),
detections_in_frame: 1,
duplicates_in_frame: 0,
unique_object_count: totalTargets,
duplicate_count: 0,
label: 'Picking Target ' + (targetIndex + 1),
centroid_x_px: target.centroidX,
centroid_y_px: target.centroidY,
score: target.score,
pick_x_mm: moveX,
pick_y_mm: moveY
};
if (extraFields) {
for (var key in extraFields) {
if (extraFields.hasOwnProperty(key)) {
record[key] = extraFields[key];
}
}
}
writeText(detectionStatusFile, JSON.stringify(record, null, 2) + '\n');
}
function writeInspectionPreview(scanDir, scanId, target, targetIndex, totalTargets, imageFile, x, y, z) {
var detectionStatusFile = new File(projectDir, 'control/detection_status.json');
var record = {
status: 'detected',
scan_dir: scanDir.getAbsolutePath(),