forked from BarbourSmith/Calibration-Simulation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1225 lines (1042 loc) · 49.3 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calibration Simulation</title>
<button id="compute-button">Refine Measurments 1x</button>
<button id="compute-1k-button">1,000x</button>
<button id="compute-10k-button">10,000x</button>
<button id="compute-end-button">End</button>
<button id="scroll-up-button">Up</button>
<button id="scroll-down-button">Down</button>
<input type="text" id="partameterField" placeholder="--" value="140" style="width: 50px; height: 20px; font-size: 12px; text-align: center;"/>
<style>
body {
margin: 0;
}
</style>
</head>
<body id= "mainBody">
<---click this button to see the simulation find the corners
<div id = "views">
</div>
<script>
//get bottomTension from input field
var bottomTension = document.getElementById("partameterField").value;
//This is the inital guess for how big the machine is. These numbers are wrong intensionally
const initialWidth = 3048 + 12;
const initialHeight = 2200 - 14;
//These are the true corners of the machine that we want to solve for (only used for simulated measurments)
const trueTLX = -0.6948090610228441;
const trueTLY = 2131.275233532367;
const trueTRX = 3034.4072793128926;
const trueTRY = 2127.1780972406527;
const trueBLX = 0;
const trueBLY = 0;
const trueBRX = 3034.960970894897;
const trueBRY = 0;
/**------------------------------------Intro------------------------------------
*
* If you are reading this code to understand it then I would recommend starting
* at the bottom of the page and working your way up. The code is written in a
* functional style so the function definitions are at the top and the code that
* actually runs is at the bottom. It was also written quickly and modified a lot
* so it is not very clean. I apologize for that.
*
*------------------------------------------------------------------------------
*/
/**
* Simulates a measurement at a given location with random and constant errors.
* @param {number} x - The x-coordinate of the location to measure.
* @param {number} y - The y-coordinate of the location to measure.
* @param {number} randomError - The maximum amount of random error to add to the measurement.
* @param {number} constantError - The constant error to add to the measurement.
* @returns {Object} - An object containing the simulated measurements at the given location.
*/
function takeSimulatedMeasurement(x,y,randomError, constantError){
const tl = distanceBetweenPoints(trueTLX, trueTLY, x, y) + ((Math.random()*randomError*2) - randomError) + constantError;
const tr = distanceBetweenPoints(trueTRX, trueTRY, x, y) + ((Math.random()*randomError*2) - randomError) + constantError;
const bl = distanceBetweenPoints(trueBLX, trueBLY, x, y) + ((Math.random()*randomError*2) - randomError) + constantError;
const br = distanceBetweenPoints(trueBRX, trueBRY, x, y) + ((Math.random()*randomError*2) - randomError) + constantError;
return {tl: tl, tr: tr, bl: bl, br: br};
}
/**
* Computes the distance between two points.
* @param {number} a - The x-coordinate of the first point.
* @param {number} b - The y-coordinate of the first point.
* @param {number} c - The x-coordinate of the second point.
* @param {number} d - The y-coordinate of the second point.
* @returns {number} - The distance between the two points.
*/
function distanceBetweenPoints(a, b, c, d) {
var dx = c - a;
var dy = d - b;
return Math.sqrt(dx * dx + dy * dy);
}
/**
* Computes the end point of a line based on its starting point, angle, and length.
* @param {number} startX - The x-coordinate of the line's starting point.
* @param {number} startY - The y-coordinate of the line's starting point.
* @param {number} angle - The angle of the line in radians.
* @param {number} length - The length of the line.
* @returns {Object} - An object containing the x and y coordinates of the line's end point.
*/
function getEndPoint(startX, startY, angle, length) {
var endX = startX + length * Math.cos(angle);
var endY = startY + length * Math.sin(angle);
return { x: endX, y: endY };
}
/**
* Computes how close all of the line end points are to each other.
* @param {Object} line1 - The first line to compare.
* @param {Object} line2 - The second line to compare.
* @param {Object} line3 - The third line to compare.
* @param {Object} line4 - The fourth line to compare.
* @returns {number} - The fitness value, which is the average distance between all line end points.
*/
/*
function computeEndpointFitness(line1, line2, line3, line4){
const a = distanceBetweenPoints(line1.xEnd, line1.yEnd, line2.xEnd, line2.yEnd);
const b = distanceBetweenPoints(line1.xEnd, line1.yEnd, line3.xEnd, line3.yEnd);
const c = distanceBetweenPoints(line1.xEnd, line1.yEnd, line4.xEnd, line4.yEnd);
const d = distanceBetweenPoints(line2.xEnd, line2.yEnd, line3.xEnd, line3.yEnd);
const e = distanceBetweenPoints(line2.xEnd, line2.yEnd, line4.xEnd, line4.yEnd);
const f = distanceBetweenPoints(line3.xEnd, line3.yEnd, line4.xEnd, line4.yEnd);
const fitness = (a+b+c+d+e+f)/6;
return fitness;
}
*/
//alternative metrics for fitness 1, we find the distance fromn the center of mass of the lines to each line end point and average them
/*
function computeEndpointFitness(line1, line2, line3, line4){
var centerOfMass = _centerOfMass([line1, line2, line3, line4]);
var distances = [];
distances.push( distanceBetweenPoints(centerOfMass.x, centerOfMass.y, line1.xEnd, line1.yEnd) );
distances.push( distanceBetweenPoints(centerOfMass.x, centerOfMass.y, line2.xEnd, line2.yEnd) );
distances.push( distanceBetweenPoints(centerOfMass.x, centerOfMass.y, line3.xEnd, line3.yEnd) );
distances.push( distanceBetweenPoints(centerOfMass.x, centerOfMass.y, line4.xEnd, line4.yEnd) );
var fitness = calculateAverage(distances);
return fitness;
}
*/
//alternative metrics for fitness 2, where we find the distance to the point of intersection of two lines:
//one is between TL and BR endpoints, and another is between TR and BL endpoints
function computeEndpointFitness(line1, line2, line3, line4){
var intersectionPoint = _findIntersectionPoint(line1, line4, line2, line3);
var distances = [];
distances.push( distanceBetweenPoints(intersectionPoint.x, intersectionPoint.y, line1.xEnd, line1.yEnd) );
distances.push( distanceBetweenPoints(intersectionPoint.x, intersectionPoint.y, line2.xEnd, line2.yEnd) );
distances.push( distanceBetweenPoints(intersectionPoint.x, intersectionPoint.y, line3.xEnd, line3.yEnd) );
distances.push( distanceBetweenPoints(intersectionPoint.x, intersectionPoint.y, line4.xEnd, line4.yEnd) );
var fitness = calculateAverage(distances);
return fitness;
}
//function to calculate the coordinates of the intersection point of two lines, between ends of line1 and line4 and line 2 and line 3
function _findIntersectionPoint(line1, line2, line3, line4){
var x1 = line1.xEnd;
var y1 = line1.yEnd;
var x2 = line4.xEnd;
var y2 = line4.yEnd;
var x3 = line2.xEnd;
var y3 = line2.yEnd;
var x4 = line3.xEnd;
var y4 = line3.yEnd;
var x = ((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1-y2)*(x3-x4));
var y = ((x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1-y2)*(x3-x4));
return {x: x, y: y};
}
/**
* Computes the end point of a line based on its starting point, angle, and length.
* @param {Object} line - The line to compute the end point for.
* @returns {Object} - The line with the end point added.
*/
function computeLineEndPoint(line){
const end = getEndPoint(line.xBegin, line.yBegin, line.theta, line.length);
line.xEnd = end.x;
line.yEnd = end.y;
return line;
}
/**
* Walks the four lines in the given set, adjusting their endpoints to minimize the distance between them.
* @param {Object} tlLine - The top-left line in the set.
* @param {Object} trLine - The top-right line in the set.
* @param {Object} blLine - The bottom-left line in the set.
* @param {Object} brLine - The bottom-right line in the set.
* @param {number} stepSize - The amount to adjust the angle of each line by on each iteration.
* @returns {Object} - An object containing the final positions of each line.
*/
function walkLines(tlLine, trLine, blLine, brLine, stepSize) {
let changeMade = true;
let bestFitness = computeEndpointFitness(tlLine, trLine, blLine, brLine);
while (changeMade) {
changeMade = false;
const lines = [tlLine, trLine, blLine, brLine];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
for (let direction of [-1, 1]) {
const newLine = computeLineEndPoint({
xBegin: line.xBegin,
yBegin: line.yBegin,
theta: line.theta + direction * stepSize,
length: line.length
});
const newFitness = computeEndpointFitness(
i === 0 ? newLine : tlLine,
i === 1 ? newLine : trLine,
i === 2 ? newLine : blLine,
i === 3 ? newLine : brLine
);
if (newFitness < bestFitness) {
lines[i] = newLine;
bestFitness = newFitness;
changeMade = true;
}
}
}
tlLine = lines[0];
trLine = lines[1];
blLine = lines[2];
brLine = lines[3];
}
return { tlLine, trLine, blLine, brLine };
}
/**
* Computes the fitness of a set of lines based on how close their endpoints are to each other.
* @param {Object} measurement - An object containing the initial theta values and lengths for each line.
* @param {Object} individual - An object containing the x and y coordinates for each line's starting point.
* @returns {Object} - An object containing the fitness value and the final positions of each line.
*/
function magneticallyAttractedLinesFitness(measurement, individual){
//These set the inital conditions for theta. They don't really mater, they just have to kinda point to the middle of the frame.
if(measurement.tlTheta == undefined){
measurement.tlTheta = -.3;
}
if(measurement.trTheta == undefined){
measurement.trTheta = 3.5;
}
if(measurement.blTheta == undefined){
measurement.blTheta = .5;
}
if(measurement.brTheta == undefined){
measurement.brTheta = 2.6;
}
//Define the four lines with starting points and lengths
var tlLine = computeLineEndPoint({xBegin: individual.tl.x, yBegin: individual.tl.y, theta: measurement.tlTheta, length: measurement.tl});
var trLine = computeLineEndPoint({xBegin: individual.tr.x, yBegin: individual.tr.y, theta: measurement.trTheta, length: measurement.tr});
var blLine = computeLineEndPoint({xBegin: individual.bl.x, yBegin: individual.bl.y, theta: measurement.blTheta, length: measurement.bl});
var brLine = computeLineEndPoint({xBegin: individual.br.x, yBegin: individual.br.y, theta: measurement.brTheta, length: measurement.br});
var {tlLine, trLine, blLine, brLine} = walkLines(tlLine, trLine, blLine, brLine, .1);
var {tlLine, trLine, blLine, brLine} = walkLines(tlLine, trLine, blLine, brLine, .01);
var {tlLine, trLine, blLine, brLine} = walkLines(tlLine, trLine, blLine, brLine, .001);
var {tlLine, trLine, blLine, brLine} = walkLines(tlLine, trLine, blLine, brLine, .0001);
if(secondRun){
var {tlLine, trLine, blLine, brLine} = walkLines(tlLine, trLine, blLine, brLine, .00001);
var {tlLine, trLine, blLine, brLine} = walkLines(tlLine, trLine, blLine, brLine, .000001);
}
//var {tlLine, trLine, blLine, brLine} = walkLines(tlLine, trLine, blLine, brLine, .0000001);
//var {tlLine, trLine, blLine, brLine} = walkLines(tlLine, trLine, blLine, brLine, .00000001);
measurement.tlTheta = tlLine.theta;
measurement.trTheta = trLine.theta;
measurement.blTheta = blLine.theta;
measurement.brTheta = brLine.theta;
//Compute the final fitness
const finalFitness = computeEndpointFitness(tlLine, trLine, blLine, brLine);
//Compute the tension in the two upper belts
const { TL, TR } = calculateTensions(tlLine.xEnd, tlLine.yEnd, individual);
measurement.TLtension = TL;
measurement.TRtension = TR;
return {fitness: finalFitness, lines: {tlLine: tlLine, trLine: trLine, blLine: blLine, brLine: brLine}};
}
/**
* Computes the distance of one line's end point from the center of mass of the other three lines.
* @param {Object} lineToCompare - The line to compute the distance for.
* @param {Object} line2 - The second line to use in computing the center of mass.
* @param {Object} line3 - The third line to use in computing the center of mass.
* @param {Object} line4 - The fourth line to use in computing the center of mass.
* @returns {Object} - An object containing the x and y distances from the center of mass.
*/
function computeDistanceFromCenterOfMass(lineToCompare, line2, line3, line4){
//Compute the center of mass
const x = (line2.xEnd + line3.xEnd + line4.xEnd)/3;
const y = (line2.yEnd + line3.yEnd + line4.yEnd)/3;
return {x: lineToCompare.xEnd - x, y: lineToCompare.yEnd - y};
}
//lines array, any size
function _centerOfMass(lines){
var x = 0;
var y = 0;
for (var i = 0; i < lines.length; i++) {
x += lines[i].xEnd;
y += lines[i].yEnd;
}
return {x: x/lines.length, y: y/lines.length};
}
//find the line index which is the furthest from center of mass and return line index and distance
function _findFurtherestFromCenterOfMass ( lines ){
var centerOfMass = _centerOfMass(lines);
var distances = [];
for (var i = 0; i < lines.length; i++) {
distances.push( distanceBetweenPoints(centerOfMass.x, centerOfMass.y, lines[i].xEnd, lines[i].yEnd) );
}
var maxDistance = Math.max(...distances);
var maxIndex = distances.indexOf(maxDistance);
return {index: maxIndex, distance: maxDistance};
}
//go throught the measurements, find the lines furthest from the center of mass, and change their length value, so the line End is at the center of mass
function _filterOutliers(measurements, individual){
var lines_filtered = 0;
for (var i = 0; i < measurements.length; i++) {
var lines = computeLines(measurements[i], individual);
var {index, distance} = _findFurtherestFromCenterOfMass(lines);
//compute center of mass of the lines without the lines[index]:
var linesWithoutIndex = [];
for (var j = 0; j < lines.length; j++) {
if (j != index){
linesWithoutIndex.push(lines[j]);
}
}
var centerOfMass = _centerOfMass(linesWithoutIndex);
var avgDistance = computeEndpointFitness(lines[0], lines[1], lines[2], lines[3]);
// if distance is more than avgDistance, change the length of the line to make the line end at the center of mass, then adjust the corresponding measurement length:
if ( distance > avgDistance*filteringCoefficient ){
var newLine = computeLineEndPoint({xBegin: lines[index].xBegin, yBegin: lines[index].yBegin, theta: lines[index].theta, length: distance});
lines[index] = newLine;
//adjust the corresponding measurement length:
if (index == 0){
measurements[i].tl = distanceBetweenPoints(centerOfMass.x, centerOfMass.y, lines[index].xBegin, lines[index].yBegin);
}
else if (index == 1){
measurements[i].tr = distanceBetweenPoints(centerOfMass.x, centerOfMass.y, lines[index].xBegin, lines[index].yBegin);
}
else if (index == 2){
measurements[i].bl = distanceBetweenPoints(centerOfMass.x, centerOfMass.y, lines[index].xBegin, lines[index].yBegin);
}
else if (index == 3){
measurements[i].br = distanceBetweenPoints(centerOfMass.x, centerOfMass.y, lines[index].xBegin, lines[index].yBegin);
}
filtered_map[i][index] = 1;
lines_filtered++;
}
}
return lines_filtered;
}
function computeLines(measurement, individual){
var tlLine = computeLineEndPoint({xBegin: individual.tl.x, yBegin: individual.tl.y, theta: measurement.tlTheta, length: measurement.tl});
var trLine = computeLineEndPoint({xBegin: individual.tr.x, yBegin: individual.tr.y, theta: measurement.trTheta, length: measurement.tr});
var blLine = computeLineEndPoint({xBegin: individual.bl.x, yBegin: individual.bl.y, theta: measurement.blTheta, length: measurement.bl});
var brLine = computeLineEndPoint({xBegin: individual.br.x, yBegin: individual.br.y, theta: measurement.brTheta, length: measurement.br});
return [tlLine, trLine, blLine, brLine];
}
/**
* Computes the distances from the center of mass for four lines and converts them into the relevant variables that we can tweak.
* @param {Object} lines - An object containing four lines to compute the distances from the center of mass for.
* @returns {Object} - An object containing the distances from the center of mass for tlX, tlY, trX, trY, and brX.
*/
function generateTweaks(lines){
//We care about the distances for tlX, tlY, trX, trY, brX
const tlX = computeDistanceFromCenterOfMass(lines.tlLine, lines.trLine, lines.blLine, lines.brLine).x;
const tlY = computeDistanceFromCenterOfMass(lines.tlLine, lines.trLine, lines.blLine, lines.brLine).y;
const trX = computeDistanceFromCenterOfMass(lines.trLine, lines.tlLine, lines.blLine, lines.brLine).x;
const trY = computeDistanceFromCenterOfMass(lines.trLine, lines.tlLine, lines.blLine, lines.brLine).y;
const brX = computeDistanceFromCenterOfMass(lines.brLine, lines.tlLine, lines.trLine, lines.blLine).x;
return {tlX: tlX, tly: tlY, trX: trX, trY: trY, brX: brX};
}
/**
* Computes all of the tweaks and summarizes them to move the guess furthest from the center of mass of the lines.
* @param {Array} lines - An array of lines to compute the tweaks for.
* @param {Object} lastGuess - The last guess made by the algorithm.
* @returns {Object} - The updated guess with the furthest tweaks applied.
*/
function computeFurthestFromCenterOfMass(lines, lastGuess){
var tlX = 0;
var tlY = 0;
var trX = 0;
var trY = 0;
var brX = 0;
lines.forEach(line => {
const tweaks = generateTweaks(line);
tlX = tlX + tweaks.tlX;
tlY = tlY + tweaks.tly;
trX = trX + tweaks.trX;
trY = trY + tweaks.trY;
brX = brX + tweaks.brX;
})
tlX = tlX/lines.length;
tlY = tlY/lines.length;
trX = trX/lines.length;
trY = trY/lines.length;
brX = brX/lines.length;
const maxError = Math.max(
Math.abs(tlX),
Math.abs(tlY),
Math.abs(trX),
Math.abs(trY),
Math.abs(brX)
);
var divisor = -10;
if(maxError == Math.abs(tlX)){
//console.log("Move tlY by: " + tlY/divisor);
lastGuess.tl.x = lastGuess.tl.x + tlX/divisor;
}
if(maxError == Math.abs(tlY)){
//console.log("Move tlY by: " + tlY/divisor);
lastGuess.tl.y = lastGuess.tl.y + tlY/divisor;
}
else if(maxError == Math.abs(trX)){
//console.log("Move trX by: " + trX/divisor);
lastGuess.tr.x = lastGuess.tr.x + trX/divisor;
}
else if(maxError == Math.abs(trY)){
//console.log("Move trY by: " + trY/divisor);
lastGuess.tr.y = lastGuess.tr.y + trY/divisor;
}
else if(maxError == Math.abs(brX)){
//console.log("Move brX by: " + brX/divisor);
lastGuess.br.x = lastGuess.br.x + brX/divisor;
}
return lastGuess;
}
/**
* Computes the fitness of a guess for a set of measurements by comparing the guess to magnetically attracted lines.
* @param {Array} measurements - An array of measurements to compare the guess to.
* @param {Object} lastGuess - The last guess made by the algorithm.
* @returns {Object} - An object containing the fitness of the guess and the lines used to calculate the fitness.
*/
function computeLinesFitness(measurements, lastGuess){
var fitnesses = [];
var allLines = [];
//Check each of the measurements against the guess
measurements.forEach(measurement => {
const {fitness, lines} = magneticallyAttractedLinesFitness(measurement, lastGuess);
fitnesses.push(fitness);
allLines.push(lines);
});
//print all of the fitnesses next to each measurement in red color and update canvas in real time
printFitnesses(measurements, lastGuess);
//draw all the lines:
for (var i = 0; i < allLines.length; i++) {
//drawLines(allLines[i].tlLine, allLines[i].trLine, allLines[i].blLine, allLines[i].brLine, lastGuess);
}
//Computes the average fitness of all of the measurements
const fitness = calculateAverage(fitnesses);
//console.log(fitnesses);
//Here is where we need to do the calculation of which corner is the worst and which direction to move it
lastGuess = computeFurthestFromCenterOfMass(allLines, lastGuess);
lastGuess.fitness = fitness;
return lastGuess;
}
/**
* Flips the y-coordinate of a point to account for the canvas having y at the top.
* @param {number} y - The y-coordinate to flip.
* @returns {number} - The flipped y-coordinate.
*/
function flipY(y) {
var canvas = document.getElementById("CursorLayer");
return canvas.height - y;
}
function changeStrokeStyle(inputValue) {
const green = [0, 128, 0]; // RGB values for green
const red = [255, 0, 0]; // RGB values for red
const range = 60 - 20; // Range of input values
const increment = (red.map((value, index) => value - green[index])).map(value => value / range); // Increment for each RGB value
const color = green.map((value, index) => Math.round(value + increment[index] * (inputValue - 20))); // Calculate the color based on the input value
const canvas = document.getElementById("CursorLayer");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = `rgb(${color[0]}, ${color[1]}, ${color[2]})`; // Set the strokeStyle to the calculated color
}
/**
* Draws four lines on a canvas element and adds a circle at the end of each line.
* @param {Object} line1 - An object containing the x and y coordinates of the beginning and end of the first line.
* @param {Object} line2 - An object containing the x and y coordinates of the beginning and end of the second line.
* @param {Object} line3 - An object containing the x and y coordinates of the beginning and end of the third line.
* @param {Object} line4 - An object containing the x and y coordinates of the beginning and end of the fourth line.
* @returns {void}
*/
function drawLines(line1, line2, line3, line4, guess) {
var canvas = document.getElementById("CursorLayer");
var ctx = canvas.getContext("2d");
// Set the stroke color to a lighter grey
ctx.strokeStyle = "#999";
// Draw the four lines
ctx.setLineDash([5, 5]);
//Top left line
ctx.beginPath();
ctx.moveTo(line1.xBegin / 4, flipY(line1.yBegin / 4));
ctx.lineTo(line1.xEnd / 4, flipY(line1.yEnd / 4));
ctx.stroke();
ctx.beginPath();
ctx.arc(line1.xEnd / 4, flipY(line1.yEnd / 4), 2, 0, 2 * Math.PI);
ctx.fill();
//Top right line
ctx.beginPath();
ctx.moveTo(line2.xBegin / 4, flipY(line2.yBegin / 4));
ctx.lineTo(line2.xEnd / 4, flipY(line2.yEnd / 4));
ctx.stroke();
ctx.beginPath();
ctx.arc(line2.xEnd / 4, flipY(line2.yEnd / 4), 2, 0, 2 * Math.PI);
ctx.fill();
ctx.beginPath();
ctx.moveTo(line3.xBegin / 4, flipY(line3.yBegin / 4));
ctx.lineTo(line3.xEnd / 4, flipY(line3.yEnd / 4));
ctx.stroke();
ctx.beginPath();
ctx.arc(line3.xEnd / 4, flipY(line3.yEnd / 4), 2, 0, 2 * Math.PI);
ctx.fill();
ctx.beginPath();
ctx.moveTo(line4.xBegin / 4, flipY(line4.yBegin / 4));
ctx.lineTo(line4.xEnd / 4, flipY(line4.yEnd / 4));
ctx.stroke();
ctx.beginPath();
ctx.arc(line4.xEnd / 4, flipY(line4.yEnd / 4), 2, 0, 2 * Math.PI);
ctx.fill();
// ctx.fillText("TL: " + TL.toFixed(2), line1.xEnd / 4, flipY(line1.yEnd / 4) + 10);
// ctx.fillText("TR: " + TR.toFixed(2), line1.xEnd / 4, flipY(line1.yEnd / 4) + 20);
}
//print all of the fitnesses next to each measurement in red color
/**
* Calculates the average of an array of numbers.
* @param {number[]} array - The array of numbers to calculate the average of.
* @returns {number} - The average of the array.
*/
function calculateAverage(array) {
var total = 0;
var count = 0;
array.forEach(function(item, index) {
total += Math.abs(item);
count++;
});
return total / count;
}
/**
* Prints the difference between the real values and the computed values for the corners. Only useful when using simulated
* measurements.
* @param {Object} guess - An object containing the x and y coordinates of the top left, top right, bottom left, and bottom right corners of a trapazoid.
* @returns {void}
*/
function printResults(guess){
// console.log("tlX error: " + (guess.tl.x - trueTLX) + "mm at: " + guess.tl.x);
// console.log("tlY error: " + (guess.tl.y - trueTLY) + "mm at: " + guess.tl.y);
// console.log("trX error: " + (guess.tr.x - trueTRX) + "mm at: " + guess.tr.x);
// console.log("trY error: " + (guess.tr.y - trueTRY) + "mm at: " + guess.tr.y);
// console.log("brX error: " + (guess.br.x - trueBRX) + "mm at: " + guess.br.x);
console.log("(" + guess.tl.x + ", " + guess.tl.y + "), (" + guess.tr.x + ", " + guess.tr.y + ")\n (" + guess.bl.x + ", " + guess.bl.y + "), (" + guess.br.x + ", " + guess.br.y + ")");
console.log("Fitness: " + 1/guess.fitness);
}
/**
* Projects the measurements to the plane of the machine. This is needed
* because the belts are not parallel to the surface of the machine.
* @param {Object} measurement - An object containing the measurements
* @returns {Object} - An object containing the projected measurements
*/
function projectMeasurement(measurement){
const tlZ = 116;
const trZ = 69;
const blZ = 47;
const brZ = 89;
//back correction for arms lengts
const armLength = 0;// 123.4;
const tl = Math.sqrt(Math.pow(measurement.tl - armLength, 2) - Math.pow(tlZ,2)) + armLength;
const tr = Math.sqrt(Math.pow(measurement.tr - armLength, 2) - Math.pow(trZ,2)) + armLength;
const bl = Math.sqrt(Math.pow(measurement.bl - armLength, 2) - Math.pow(blZ,2)) + armLength;
const br = Math.sqrt(Math.pow(measurement.br - armLength, 2) - Math.pow(brZ,2)) + armLength;
return {tl: tl, tr: tr, bl: bl, br: br};
}
/**
* Projects an array of measurements to the plane of the machine to account for the fact that the start and end point are not in the same plane.
* @param {Object[]} measurements - An array of objects containing the measurements of the top left, top right, bottom left, and bottom right corners of a rectangle.
* @returns {Object[]} - An array of objects containing the projected measurements of the top left, top right, bottom left, and bottom right corners of a rectangle.
*/
function projectMeasurements(measurements){
var projectedMeasurements = [];
measurements.forEach(measurement => {
projectedMeasurements.push(projectMeasurement(measurement));
});
return projectedMeasurements;
}
/**
* Adds a constant to each measurement in an array of measurements.
* @param {Object[]} measurements - An array of objects containing the measurements of the top left, top right, bottom left, and bottom right corners of a rectangle.
* @param {number} offset - The constant to add to each measurement.
* @returns {Object[]} - An array of objects containing the updated measurements of the top left, top right, bottom left, and bottom right corners of a rectangle.
*/
function offsetMeasurements(measurements, offset) {
const newMeasurements = measurements.map(measurement => {
return {
tl: measurement.tl + offset,
tr: measurement.tr + offset,
bl: measurement.bl + offset,
br: measurement.br + offset
};
});
return newMeasurements;
}
/**
* Scales each measurement in an array of measurements by a constant.
* @param {Object[]} measurements - An array of objects containing the measurements of the top left, top right, bottom left, and bottom right corners of a rectangle.
* @param {number} scale - The constant to multiply each measurement by.
* @returns {Object[]} - An array of objects containing the updated measurements of the top left, top right, bottom left, and bottom right corners of a rectangle.
*/
function scaleMeasurements(measurements, scale) {
const newMeasurements = measurements.map(measurement => {
return {
tl: measurement.tl * scale,
tr: measurement.tr * scale,
bl: measurement.bl, // * scale,
br: measurement.br, // * scale
};
});
return newMeasurements;
}
function calculateTensions(x, y, guess) {
let Xtl = guess.tl.x;
let Ytl = guess.tl.y;
let Xtr = guess.tr.x;
let Ytr = guess.tr.y;
let Xbl = guess.bl.x;
let Ybl = guess.bl.y;
let Xbr = guess.br.x;
let Ybr = guess.br.y;
let BL = bottomTension; //say tension in bottom belts is ~14kg
let BR = bottomTension;
let mass = 5.0;
const G_CONSTANT = 9.80665;
let alpha = 0.262;
let TL, TR;
let A, C, sinD, cosD, sinE, cosE;
let Fx, Fy;
A = (Xtl - x) / (Ytl - y);
C = (Xtr - x) / (Ytr - y);
A = Math.abs(A);
C = Math.abs(C);
sinD = x / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
cosD = y / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
sinE = Math.abs(Xbr - x) / Math.sqrt(Math.pow(Xbr - x, 2) + Math.pow(y, 2));
cosE = y / Math.sqrt(Math.pow(Xbr - x, 2) + Math.pow(y, 2));
Fx = BR * sinE - BL * sinD;
Fy = BR * cosE + BL * cosD + mass * G_CONSTANT * Math.cos(alpha);
//console.log(`Fx = ${Fx.toFixed(1)}, Fy = ${Fy.toFixed(1)}`);
let TLy = (Fx + C * Fy) / (A + C);
let TRy = Fy - TLy;
let TRx = C * (Fy - TLy);
let TLx = A * TLy;
//console.log(`TLy = ${TLy.toFixed(1)}, TRy = ${TRy.toFixed(1)}, TRx = ${TRx.toFixed(1)}, TLx = ${TLx.toFixed(1)}`);
TL = Math.sqrt(Math.pow(TLx, 2) + Math.pow(TLy, 2));
TR = Math.sqrt(Math.pow(TRx, 2) + Math.pow(TRy, 2));
//console.log(`TL = ${TL.toFixed(1)}, TR = ${TR.toFixed(1)}`);
return { TL, TR };
}
function scaleMeasurementsBasedOnTension(measurements, guess) {
//const bottomTension = 140;
const spring = guess; //0.01; // mm/N
//const scaleRange = maxScale - minScale;
//const tensionRange = maxTension - minTension;
const newMeasurements = measurements.map(measurement => {
const stretchTL = measurement.TLtension*spring;
const stretchTR = measurement.TRtension*spring;
const stretchBL = bottomTension*spring;
const stretchBR = bottomTension*spring;
//const tensionAdjustedTLScale = (1 - ((measurement.TLtension - minTension) / tensionRange)) * scaleRange + minScale;
//const tensionAdjustedTRScale = (1 - ((measurement.TRtension - minTension) / tensionRange)) * scaleRange + minScale;
console.log( "stretchTL = " + stretchTL + " stretchTR = " + stretchTR);
return {
tl: measurement.tl + stretchTL,
tr: measurement.tr + stretchTR,
bl: measurement.bl + stretchBL, // * scale,
br: measurement.br + stretchBR, // * scale
};
});
return newMeasurements;
}
function findMaxFitness(initialGuess, measurements) {
var maxFitness = -1;
var newFitness = 0;
var stagnantCounter = 0;
while (stagnantCounter < 30) {
maxFitness = newFitness;
var maxFitnessThisRun = 0;
//Run 1,000 steps
for (let i = 0; i < 100; i++) {
clearCanvas();
initialGuess = computeLinesFitness(measurements, initialGuess);
maxFitnessThisRun = Math.max(1 / initialGuess.fitness, maxFitnessThisRun);
}
newFitness = maxFitnessThisRun;
console.log("Fitness: " + newFitness);
if (stagnantCounter > 1) {
console.log("Stagnant Counter: " + stagnantCounter);
}
if (newFitness <= maxFitness+0.0002) {
stagnantCounter++;
} else {
stagnantCounter = 0;
}
}
//console.log("Maxfitness: " + maxFitness);
//console.log("NewFitness: " + newFitness);
return initialGuess;
}
//Creates the canvas on which the pattern will be drawn
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = 1000;
canvas.height = 600;
canvas.style.border = "1px solid";
document.getElementById("views").appendChild(canvas);
//Deletes everything from the canvas
function clearCanvas() {
const canvas = document.getElementById('CursorLayer');
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
}
function printFitnesses(measurements, guess){
var canvas = document.getElementById("CursorLayer");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.font = "14px Arial";
var i = 0;
measurements.forEach(measurement => {
const {fitness, lines} = magneticallyAttractedLinesFitness(measurement, guess);
i++;
ctx.fillText(fitness.toFixed(4), (i/10)*70,(i%10)*30);
});
}
// Attach an event listener to the button
const computeButton = document.getElementById('compute-button');
computeButton.addEventListener('click', () => {
clearCanvas();
initialGuess = computeLinesFitness(measurements, initialGuess);
printResults(initialGuess);
});
//Create the buttons that the user can click
const compute1kButton = document.getElementById('compute-1k-button');
compute1kButton.addEventListener('click', () => {
for(let i = 0; i < 1000; i++){
clearCanvas();
initialGuess = computeLinesFitness(measurements, initialGuess);
console.log("Fitness: " + 1/initialGuess.fitness);
}
printResults(initialGuess);
});
const compute10kButton = document.getElementById('compute-10k-button');
compute10kButton.addEventListener('click', () => {
for(let i = 0; i < 10000; i++){
clearCanvas();
initialGuess = computeLinesFitness(measurements, initialGuess);
console.log("Fitness: " + 1/initialGuess.fitness);
}
printResults(initialGuess);
});
var result_global;
const computeEndButton = document.getElementById('compute-end-button');
computeEndButton.addEventListener('click', () => {
console.log("Initial guess: " + initialGuess.fitness);
bottomTension = 140;
const stretch_guess = 0.03;
computeLinesFitness(measurements, initialGuess);
measurements = scaleMeasurementsBasedOnTension(measurements,stretch_guess);
measurements = projectMeasurements(measurements);
//measure time to compute
var t0 = performance.now();
result = findMaxFitness(initialGuess, measurements);
var t1 = performance.now();
console.log("Call to findMaxFitness took " + (t1 - t0) + " milliseconds.");
printResults(result);
initialGuess = {
tl: {x: 0, y: initialHeight},
tr: {x: initialWidth, y: initialHeight},
bl: {x: 0, y: 0},
br: {x: initialWidth, y: 0},
fitness: 0
}
t0 = performance.now();
var filteredCount = _filterOutliers(measurements,result);
secondRun = true;
result = findMaxFitness(initialGuess, measurements );
t1 = performance.now();
console.log("Call to findMaxFitness took " + (t1 - t0) + " milliseconds.");
console.log("Filtered " + filteredCount + " measurements");
result_global = result;
printResults(result);
drawLineEnds(0);
});
var secondRun = false;
var cursor = 0;
//two buttons for scrolling theought the measurements labeled with up and down arrows
const scrollUpButton = document.getElementById('scroll-up-button');
scrollUpButton.textContent = "⬆";
scrollUpButton.addEventListener('click', () => {
cursor--;
if(cursor < 0){
cursor = measurements.length - 1;
}
drawLineEnds(cursor);
});
const scrollDownButton = document.getElementById('scroll-down-button');
scrollDownButton.textContent = "⬇";
scrollDownButton.addEventListener('click', () => {
cursor++;
if(cursor > measurements.length - 1){
cursor = 0;
}
drawLineEnds(cursor);
});
// on value change in parameter field, redraw current line ends
const parameterField = document.getElementById('partameterField');
parameterField.addEventListener('change', () => {
drawLineEnds(cursor);
});
//func to draw on canvas the ends of the lines scaled to their fitness
function drawLineEnds( measurementID){
clearCanvas();
var canvas = document.getElementById("CursorLayer");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.font = "14px Arial";
var tlLine = computeLineEndPoint({xBegin:result_global.tl.x, yBegin:result_global.tl.y, theta: measurements[measurementID].tlTheta,length: measurements[measurementID].tl});
var trLine = computeLineEndPoint({xBegin:result_global.tr.x, yBegin:result_global.tr.y, theta: measurements[measurementID].trTheta,length: measurements[measurementID].tr});
var blLine = computeLineEndPoint({xBegin:result_global.bl.x, yBegin:result_global.bl.y, theta: measurements[measurementID].blTheta,length: measurements[measurementID].bl});
var brLine = computeLineEndPoint({xBegin:result_global.br.x, yBegin:result_global.br.y, theta: measurements[measurementID].brTheta,length: measurements[measurementID].br});
var size = result_global.fitness;
// computeEndpointFitness(tlLine, trLine, blLine, brLine);
var lines = [tlLine, trLine, blLine, brLine];
var x0 = blLine.xEnd - size*5;
var y0 = blLine.yEnd - size*5;
let scale = document.getElementById("partameterField").value;
//show real scale ruler at the bottom left corner
ctx.fillText("0mm", 10, flipY(10));
//draw a ruller - numbers and strokes for each mm
for(var j = 1; j < 3; j++){
ctx.beginPath();
ctx.moveTo(10, flipY(10 + j*scale -1));
ctx.lineTo(20, flipY(10 + j*scale -1));
ctx.stroke();
ctx.fillText(j + "mm", 10, flipY(10 + j*scale));
}
//draw labeled ends of lines
for (var i = 0; i < lines.length; i++) {
ctx.beginPath();
ctx.arc((lines[i].xEnd - x0)*scale, flipY((lines[i].yEnd - y0)*scale), 2, 0, 2 * Math.PI);
ctx.fill();
//draw half transparent lines towards the theta direction, stroke 5, color blue, length scale, draw the filtered lines in red
ctx.lineWidth = 5;
ctx.beginPath();
if( filtered_map[measurementID][i] == 1){
ctx.strokeStyle = "rgba(255, 0, 0, 0.25)";
}
else{
ctx.strokeStyle = "rgba(0, 0, 255, 0.25)";
}
ctx.moveTo((lines[i].xEnd - x0)*scale, flipY((lines[i].yEnd - y0)*scale));
ctx.lineTo((lines[i].xEnd - x0)*scale + scale*Math.cos(lines[i].theta+3.14), flipY( (lines[i].yEnd - y0)*scale + scale*Math.sin(lines[i].theta+3.14)));
ctx.stroke();
//draw labels for each line end
var label = "";
var offsetX, offsetY;
if(i == 0){
label = "TL";