-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
2086 lines (1736 loc) · 74.9 KB
/
functions.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
993
994
995
996
997
998
999
1000
"""
Functions.
Functions for Magnet Referencing Code.
Author: Jana Barker
Date: Created on Fri Jul 28 13:54:12 2023
Description:
------------
This is a file containing all functions necessary in orther to fit circles into
measured 3D or 2D points.
This file also contains functions to read in a Spatial Analyzer output file
and pars it into needed dictionaries.
Note:
----
- made together with ChatGPT, but tested by human.
"""
import numpy as np
from scipy.optimize import least_squares
import datetime
import inspect
import os
import matplotlib.pyplot as plt
import random
from itertools import combinations
# from mpl_toolkits.mplot3d import Axes3D
from typing import Union
def gon_to_radians(gon):
"""
Convert an angle in gradians (gons) to radians.
This function takes an angle in gradians and returns its equivalent
angle in radians.
Parameters
----------
gon (float): Angle in gradians (gons) to be converted to radians.
Returns
-------
float: Angle in radians equivalent to the input angle in gradians.
Examples
--------
>>> gon_to_radians(200)
3.141592653589793
>>> gon_to_radians(100)
1.5707963267948966
"""
return gon * (2 * np.pi / 400)
def degrees_to_radians(degrees):
"""
Convert an angle in degrees to radians.
This function takes an angle in degrees and returns its equivalent
angle in radians.
Parameters
----------
degrees (float): Angle in degrees to be converted to radians.
Returns
-------
float: Angle in radians equivalent to the input angle in degrees.
Examples
--------
>>> degrees_to_radians(180)
3.141592653589793
>>> degrees_to_radians(90)
1.5707963267948966
"""
return degrees * (np.pi / 180.0)
def cartesian_to_spherical(x, y, z):
"""
Convert Cartesian coordinates to spherical coordinates.
Converts the given Cartesian coordinates (x, y, z) to spherical coordinates
(r, theta, phi).
r represents the radial distance from the origin to the point.
theta represents the inclination angle measured from the positive z-axis.
phi represents the azimuthal angle measured from the positive x-axis.
Parameters
----------
x (float): x-coordinate in Cartesian space.
y (float): y-coordinate in Cartesian space.
z (float): z-coordinate in Cartesian space.
Returns
-------
tuple: A tuple containing (r, theta, phi) in spherical coordinates.
Examples
--------
>>> cartesian_to_spherical(1, 1, 1)
(1.7320508075688772, 0.9553166181245093, 0.7853981633974483)
>>> cartesian_to_spherical(0, 0, 2)
(2.0, 1.5707963267948966, 0.0)
"""
r = np.sqrt(x**2 + y**2 + z**2)
theta = np.arccos(z / r)
phi = np.arctan2(y, x)
return r, theta, phi
def spherical_to_cartesian(d, Hz, V):
"""
Convert spherical coordinates to 3D Cartesian coordinates.
Converts the given spherical coordinates (d, Hz, V) to 3D Cartesian
coordinates (X, Y, Z).
d represents the radial distance from the origin to the point.
Hz represents the horizontal angle measured from the positive x-axis.
V represents the zenithal angle measured from the positive z-axis.
Parameters
----------
d (float): Radial distance in spherical coordinates.
Hz (float): Horizontal angle in radians.
V (float): Zenithal angle in radians.
Returns
-------
tuple: A tuple containing (X, Y, Z) in 3D Cartesian coordinates.
Examples
--------
>>> spherical_to_cartesian(1.0, 0.7853981633974483, 0.7853981633974483)
(0.5000000000000001, 0.5000000000000001, 0.49999999999999994)
>>> spherical_to_cartesian(2.0, 1.5707963267948966, 0.0)
(1.2246467991473532e-16, 2.0, 0.0)
"""
X = d * np.cos(-Hz) * np.sin(V)
Y = d * np.sin(-Hz) * np.sin(V)
Z = d * np.cos(V)
return X, Y, Z
def spherical_to_cartesian_unit(d, d_unit, angle_unit, Hz, V):
"""
Convert Spherical to Cartesian coordinates with specified units.
Converts the given spherical coordinates (d, Hz, V) to 3D Cartesian
coordinates (x, y, z) in the specified units.
Parameters
----------
d (float): Radial distance in spherical coordinates.
angle_unit (str): Unit of the angles. Choose from 'rad', 'gon', or 'deg'.
Hz (float): Horizontal angle.
V (float): Zenithal angle.
d_unit (str): Unit of the radial distance.
Choose from 'um', 'mm', 'cm', or 'm'.
Returns
-------
tuple: A tuple containing (x, y, z) Cartesian coordinates in the specified
units.
Raises
------
ValueError: If an invalid angle unit or radial distance unit is specified.
Examples
--------
>>> spherical_to_cartesian_unit(1.0, 'rad', 0.7853981633974483,
0.7853981633974483, 'mm')
(0.5000000000000001, 0.5000000000000001, 0.49999999999999994)
>>> spherical_to_cartesian_unit(2.0, 'deg', 90, 0.0, 'cm')
(1.2246467991473532e-16, 200.0, 0.0, 'mm')
"""
# Convert the angle to radians if needed
if angle_unit == 'gon':
Hz = gon_to_radians(Hz)
V = gon_to_radians(V)
elif angle_unit == 'deg':
Hz = degrees_to_radians(Hz)
V = degrees_to_radians(V)
# Convert d to millimeters
if d_unit == 'um':
d *= 0.001
elif d_unit == 'mm':
d *= 1.0
elif d_unit == 'cm':
d *= 10.0
elif d_unit == 'm':
d *= 1000.0
else:
raise ValueError("Invalid d unit specified.")
# Calculate Cartesian coordinates in millimeters
x = d * np.sin(V) * np.cos(-Hz)
y = d * np.sin(V) * np.sin(-Hz)
z = d * np.cos(V)
return x, y, z, 'mm'
def get_variable_name(variable):
"""
Get the name of a variable.
This function takes a variable and returns its name as a string. It does
so by examining the calling frame's locals and globals dictionaries.
Parameters
----------
variable : any
The variable for which the name is to be retrieved.
Returns
-------
str
The name of the given variable as a string.
Examples
--------
Example usage:
>>> name = "John"
>>> age = 30
>>> variable_name_as_string = get_variable_name(name)
>>> print(variable_name_as_string)
'name'
"""
# Get the calling frame
frame = inspect.currentframe().f_back
# Find the variable name by checking the locals and globals dictionaries
for name, value in frame.f_locals.items():
if value is variable:
return name
for name, value in frame.f_globals.items():
if value is variable:
return name
def generate_noisy_ellipse_points(a, b, center_x, center_y, num_points,
std_dev):
"""Generate points along a noisy ellipse.
Parameters
----------
a : float
Semi-major axis of the ellipse.
b : float
Semi-minor axis of the ellipse.
center_x : float
x-coordinate of the center of the ellipse.
center_y : float
y-coordinate of the center of the ellipse.
num_points : int
Number of points to generate.
std_dev : float
Standard deviation for the noise added to the points.
Returns
-------
x : numpy.ndarray
Array of x-coordinates of the generated points.
y : numpy.ndarray
Array of y-coordinates of the generated points.
Example
-------
a = 3.0
b = 1.5
center_x = 2.0
center_y = 1.0
num_points = 100
std_dev = 0.1
x, y = generate_noisy_ellipse_points(a, b, center_x, center_y,
num_points, std_dev)
"""
# Generate angles evenly spaced around the ellipse (0 to 2*pi)
angles = np.linspace(0, 2*np.pi, num_points)
# Parametric equations of the ellipse
x = center_x + a * np.cos(angles)
y = center_y + b * np.sin(angles)
# Add noise from a standard normal distribution
noise_x = np.random.normal(0, std_dev, num_points)
noise_y = np.random.normal(0, std_dev, num_points)
x += noise_x
y += noise_y
return x, y
def read_data_from_file(file_path):
"""
Read data from a file and return it as a dictionary.
Parameters
----------
file_path : str
The path to the file containing the data.
Returns
-------
dict
A dictionary containing the parsed data with PointIDs as keys and
associated values including azimuth, zenith angle, distance, Cartesian
coordinates, and units.
Raises
------
ValueError
If duplicate PointIDs are found in the data or an invalid data format
is specified in the header.
Example
-------
file_path = "data.txt"
data_dict, file_path = read_data_from_file(file_path)
"""
data_dict = {}
with open(file_path, 'r') as file:
lines = file.readlines()
# Get the data format from the header
data_format_line = lines[1].split(':')
data_format = data_format_line[1].strip().lower()
# Get the units from the header
units_line = lines[2].split(':')
units = units_line[1].strip().split()
if data_format == 'spherical':
angle_unit = units[0]
d_unit = units[1]
coordinate_unit = None
elif data_format == 'cartesian':
angle_unit = None
d_unit = None
coordinate_unit = units[0]
elif data_format == 'cartesian2d': # New format for 2D Cartesian data
angle_unit = None
d_unit = None
coordinate_unit = units[0]
else:
raise ValueError("Invalid data format specified in the header.")
# Process the data lines
line_number = 0
for line in lines:
line_number += 1
if not line.startswith('#'):
line = line.strip().split()
# Skip empty lines
if not line:
continue
PointID = line[0]
if data_format == 'spherical':
azimuth = float(line[1].replace(',', '.'))
zenith_angle = float(line[2].replace(',', '.'))
distance = float(line[3].replace(',', '.'))
# Convert spherical to Cartesian
x, y, z, coordinate_unit = spherical_to_cartesian_unit(
distance, d_unit, angle_unit, azimuth, zenith_angle)
elif data_format == 'cartesian' or \
data_format == 'cartesian2d':
x = float(line[1].replace(',', '.'))
y = float(line[2].replace(',', '.'))
z = None if len(line) < 4 else float(line[3].replace(
',', '.')) # Z for Cartesian 3D, None for 2D
# Check for duplicate PointIDs
if PointID in data_dict:
raise ValueError(f"Duplicate PointID '{PointID}'"
f"found in line {line_number}.")
# Store data in the dictionary
data_dict[PointID] = {
'Hz': azimuth if data_format == 'spherical' else None,
'V': zenith_angle if data_format == 'spherical' else None,
'd': distance if data_format == 'spherical' else None,
'X': x,
'Y': y,
'Z': z,
'angle_unit': angle_unit if data_format == 'spherical'
else None, # belongs to previous line, just was too long
'd_unit': d_unit if data_format == 'spherical' else None,
'coordinate_unit': coordinate_unit,
}
return data_dict, file_path
def dict_for_Helmert(source_dict):
result_dict = {}
for point_name, values in source_dict.items():
x = values.get('X')
y = values.get('Y')
z = values.get('Z')
# Check if 'X' and 'Y' are available
if x is not None and y is not None:
result_dict[point_name] = (x, y, z) if z is not None else (x, y)
return result_dict
def distance_to_mm(unit):
"""
Convert a coordinate unit to millimeters.
Converts a coordinate unit to its equivalent value in millimeters.
Parameters
----------
unit : str
The coordinate unit to be converted. Should be one of "um", "mm", "cm",
or "m".
Returns
-------
float
The equivalent value of the coordinate unit in millimeters.
Raises
------
ValueError
If the input coordinate unit is not one of "um", "mm", "cm", or "m".
Examples
--------
>>> distance_to_mm("mm")
1.0
>>> distance_to_mm("cm")
10.0
>>> distance_to_mm("m")
1000.0
"""
if unit == "um":
return 0.001
elif unit == "mm":
return 1.0
elif unit == "cm":
return 10.0
elif unit == "m":
return 1000.0
else:
raise ValueError("Invalid coordinate unit specified.")
def get_angle_scale(output_units):
"""
Calculate the scaler to convert angles to rads based on the output_units.
Parameters
----------
output_units : dict
A dictionary containing units for different quantities.
Example: {"angles": "deg"} for degrees.
Returns
-------
float
The scaling factor to convert angles to radians.
"""
if output_units["angles"] == "gon":
return np.pi / 200.0 # Convert gon to radians
elif output_units["angles"] == "rad":
return 1.0
elif output_units["angles"] == "mrad":
return 0.001
elif output_units["angles"] == "deg":
return np.pi / 180.0 # Convert degrees to radians
else:
raise ValueError(f"Invalid angle unit '{output_units['angles']}' "
f"specified.")
def get_angle_scale_unit(unit):
if unit == "gon":
return 200 / np.pi
elif unit == "rad":
return 1.0
elif unit == "mrad":
return 0.001
elif unit == "deg":
return 180.0 / np.pi
else:
raise ValueError("Invalid angle unit specified in the header.")
def make_residual_stats(residuals: Union[np.ndarray, list, tuple]):
"""
Calculate various statistical measures from a set of residuals.
Parameters
----------
residuals : numpy.ndarray or list or tuple
The residuals to compute statistics for.
Returns
-------
dict
A dictionary containing the following statistical measures:
- "Standard Deviation": Standard deviation of the residuals.
- "Maximum |Residual|": Maximum absolute value of the residuals.
- "Minimum |Residual|": Minimum absolute value of the residuals.
- "RMS": Root Mean Square (RMS) of the residuals.
- "Mean": Mean value of the residuals.
- "Median": Median value of the residuals.
"""
if not isinstance(residuals, np.ndarray):
residuals = np.array(residuals)
statistics = {
"Standard Deviation": np.std(residuals),
"Maximum |Residual|": np.max(abs(residuals)),
"Minimum |Residual|": np.min(abs(residuals)),
"RMS": np.sqrt(np.mean(residuals**2)),
"Mean": np.mean(residuals),
"Median": np.median(residuals)
}
return statistics
def fit_circle_2d(data_tuple, output_units, log=False,
log_statistics=False):
"""
Fit a circle to 2D data points using least squares optimization.
Parameters
----------
data_tuple : tuple
A tuple containing a dictionary of data points and the file path
associated with the data.
output_units : dict
A dictionary specifying the desired output units for the circle's
parameters.
log_file_path : str, optional
Path to a log file for recording fit details (default is None).
Returns
-------
dict or None
A dictionary containing information about the fitted circle if
successful:
- "name": Name of the fitted circle.
- "center": Tuple containing (center_x, center_y) coordinates of the
circle's center.
- "radius": Radius of the fitted circle.
- "statistics": Dictionary containing statistics about the radial
offsets.
- "point_radial_offsets": Dictionary containing radial offsets for
each data point.
Returns None if the circle fitting fails.
Note
----
This function fits a circle in 2D using least squares optimization. It
extracts data from the input dictionary,
fits a circle, scales the output based on the specified output units,
calculates radial offsets,
and provides various statistics about the fitting results.
"""
data_dict, file_path = data_tuple
circle_name = os.path.splitext(os.path.basename(file_path))[0]
# Extract data from the dictionary
x, y = [], []
# Create a list to store point names
point_names = []
for point_name, point_data in data_dict.items():
# Parse data in Cartesian format
x.append(point_data['X'] * distance_to_mm(point_data[
'coordinate_unit']))
y.append(point_data['Y'] * distance_to_mm(point_data[
'coordinate_unit']))
# Store the point name
point_names.append(point_name)
# Fit a circle in 2D using least squares optimization
initial_guess = np.array([np.mean(x), np.mean(y),
np.mean(np.sqrt((x - np.mean(x))**2 +
(y - np.mean(y))**2))])
result = least_squares(circle_residuals_2d, initial_guess, args=(x, y))
# Check if the optimization succeeded
if result.success:
center_x, center_y, radius = result.x
else:
print("No circle could be fit to the data of {circle_name}.")
return None
# Scale the output based on output_units from config.py
result_scale = get_distance_scale(output_units)
# Scale the output
center_x, center_y, radius = center_x * result_scale, center_y * \
result_scale, radius * result_scale
x = np.array(x) * result_scale
y = np.array(y) * result_scale
# Calculate radial offsets
radial_offsets = np.sqrt((x - center_x)**2 + (y - center_y)**2) - radius
# Create a dictionary to store radial offsets for each point
point_radial_offsets = {point_name: offset for point_name,
offset in zip(point_names, radial_offsets)}
# Prepare statistics if requested
statistics = make_residual_stats(radial_offsets)
result_dict = {"name": circle_name, "center": (center_x,
center_y),
"radius": radius, "circle_statistics": statistics,
"radial_offsets": point_radial_offsets}
if log and not log_statistics:
write_2D_circle_fit_log(result_dict, output_units, log)
else:
write_2D_circle_fit_log(result_dict, output_units, log,
log_statistics)
return result_dict
def circle_residuals_2d(params, x, y):
"""
Calculate the residuals for 2D circle fitting.
Parameters
----------
params : numpy.ndarray
Array containing the parameters of the circle: center_x, center_y, and
radius.
x : numpy.ndarray
Array of x-coordinates of data points.
y : numpy.ndarray
Array of y-coordinates of data points.
Returns
-------
numpy.ndarray
Array of residuals representing the difference between the distances
of data points from the circle's circumference and the circle's radius.
Note
----
This function calculates the residuals for 2D circle fitting. It takes the
center coordinates (center_x, center_y) and radius of the circle as
parameters, along with arrays of x and y coordinates of data points. The
residuals are the differences between the distances of data points from the
circle's circumference and the circle's radius.
"""
center_x, center_y, radius = params
return np.sqrt((x - center_x)**2 + (y - center_y)**2) - radius
def get_distance_scale(output_units):
"""
Get the scaling factor for distance units.
Parameters
----------
output_units : dict
Dictionary containing the desired output units, including 'distances'.
Returns
-------
float
Scaling factor for converting distances from the specified
output units to millimeters.
Raises
------
ValueError
If an invalid distance unit is specified in the 'distances'
field of the output_units dictionary.
Note
----
This function calculates and returns the scaling factor to convert
distances from the specified output units to millimeters. The valid
distance units are "m" (meters), "cm" (centimeters), "mm"
(millimeters), and "um" (micrometers). If an invalid distance unit
is specified, a ValueError is raised.
"""
if output_units["distances"] == "m":
return 0.001
elif output_units["distances"] == "cm":
return 0.01
elif output_units["distances"] == "mm":
return 1.0
elif output_units["distances"] == "um":
return 1000.0
else:
raise ValueError(f"Invalid distance unit '{output_units['distances']}'"
f" specified.")
def fit_plane(data_tuple, output_units, log_details=False,
log_statistics=False):
"""
Fit a plane through 3D data points and calculate residual offsets.
Parameters
----------
data_tuple : tuple
Tuple containing the data dictionary and the file path.
output_units : dict
Dictionary specifying the desired output units.
log_statistics : str, optional
Whether to log statistics, by default 'False'.
Returns
-------
tuple
Tuple containing the plane parameters and a dictionary with
plane offsets and statistics.
Raises
------
ValueError
If the input data does not contain sufficient 3D points for
plane fitting.
Note
----
This function fits a plane through 3D data points and calculates the
residual offsets of each point from the fitted plane. The input data
is expected to be in the form of a data dictionary containing 'X', 'Y',
and 'Z' coordinates. The function returns the plane parameters as
(a, b, c, d) coefficients of the plane equation: ax + by + cz + d = 0.
Additionally, it returns a dictionary containing point names as keys
and their residual offsets from the fitted plane as values, along with
statistics calculated from the residuals.
"""
data_dict, file_path = data_tuple
plane_name = os.path.splitext(os.path.basename(file_path))[0]
# Check if 3D points are available
if not any('Z' in point_data for point_data in data_dict.values()):
raise ValueError(f"The input data are not in 3D, a {plane_name} plane "
f"cannot be fit through those points.")
# Extract 3D points from the dictionary
x, y, z = [], [], []
for point_data in data_dict.values():
if 'X' in point_data and 'Y' in point_data and 'Z' in point_data:
x.append(point_data['X'] * distance_to_mm(
point_data['coordinate_unit']))
y.append(point_data['Y'] * distance_to_mm(
point_data['coordinate_unit']))
z.append(point_data['Z'] * distance_to_mm(
point_data['coordinate_unit']))
if len(x) < 3:
raise ValueError(f"Insufficient 3D points available to fit a plane in "
f"{plane_name}. At least three 3D points (X, Y, Z) "
f"are required for plane fitting.")
# Calculate the centroid of the points
centroid_x, centroid_y, centroid_z = np.mean(x), np.mean(y), np.mean(z)
# Shift the points to the centroid
x_shifted = x - centroid_x
y_shifted = y - centroid_y
z_shifted = z - centroid_z
# Stack the coordinates as a matrix
A = np.column_stack((x_shifted, y_shifted, z_shifted))
# Use Singular Value Decomposition (SVD) to fit the plane
_, _, V = np.linalg.svd(A, full_matrices=False)
normal = V[-1] # The normal vector of the plane is the last column of V
# Extract coefficients from the normal vector
a, b, c = normal
# Calculate d coefficient
d = -(a * centroid_x + b * centroid_y + c * centroid_z)
# Calculate the angle of the plane with respect to coordinate axes
angles = get_plane_angles(normal, output_units)
# Calculate residuals
plane_params = (a, b, c, d)
residual_dict = {point_name: point_to_plane_distance(X, Y, Z, plane_params)
for point_name, X, Y, Z in zip(list(
data_dict.keys()), x, y, z)
}
# Prepare statistics if requested
statistics = make_residual_stats(np.array(list(residual_dict.values())))
result_dict = {'plane_parameters': plane_params,
'planar_offsets': residual_dict,
'plane_statistics': statistics,
'angles_from_axis': {'Rx': angles[0],
'Ry': angles[1],
'Rz': angles[2]
}
}
if log_details:
write_plane_fit_log(result_dict, output_units, log_details, log_statistics)
return result_dict
def get_plane_angles(normal_vector, output_units):
"""
Calculate the angles of a plane's normal vector to CS' axes.
Parameters
----------
normal_vector : np.ndarray
Normal vector of the plane.
output_units : dict
Dictionary specifying the desired output units.
Returns
-------
tuple
Tuple containing the angles in radians or converted output units.
Note
----
This function calculates the angles of a plane's normal vector
with respect to the coordinate axes. The normal vector should be
provided as a NumPy ndarray. The function returns a tuple containing
the angles calculated for the X, Y, and Z axes. The angles are
expressed in radians by default or can be converted to the desired
output units specified in the `output_units` dictionary.
"""
normal_vector = normal_vector / np.linalg.norm(normal_vector)
Rx = np.arccos(normal_vector[0])
Ry = np.arccos(normal_vector[1])
Rz = np.arccos(normal_vector[2])
# Convert angles to the desired output units
angle_scale = 1/get_angle_scale(output_units)
Rx *= angle_scale
Ry *= angle_scale
Rz *= angle_scale
return Rx, Ry, Rz
def write_circle_fit_log(log_file_path, file_path, data_dict, center, radius,
output_units, statistics, log_statistics=False):
"""
Write fitting results and statistics of a circle fit to a log file.
Parameters
----------
log_file_path : str
Path to the log file.
file_path : str
Path to the source file.
data_dict : dict
Dictionary containing the data points used for circle fitting.
center : dict
Dictionary containing the center coordinates of the fitted circle.
radius : float
Radius of the fitted circle.
output_units : dict
Dictionary specifying the units used for output.
statistics : dict
Dictionary containing statistics related to the circle fit.
log_statistics : bool, optional
Flag indicating whether to log the statistics, by default False.
Returns
-------
bool
Returns True if the log file was successfully written.
Note
----
This function writes the results of a circle fitting operation and
associated statistics to a log file. It receives parameters including
the path to the log file, the source file, data points, circle center,
radius, units, and statistics. The function also accepts a flag to
determine whether to log the statistics or not. The log file is
formatted with date and time information, as well as fitting details
and optional statistics if requested.
"""
if not log_file_path:
return
with open(log_file_path, 'a+') as log_file:
circle_name = os.path.basename(file_path)
# Write header with date and time of calculation
log_file.write("_" * 100)
log_file.write("\nCircle {} Fitting Results:\n".format(circle_name))
log_file.write("Calculation Date: {}\n".format(
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
log_file.write("Source File: {}\n".format(file_path))
log_file.write("Units: {}\n".format(output_units["distances"]))
log_file.write("\n")
# Write circle fitting results
if "center_z" in center:
log_file.write("Center: {},{},{}\n".format(center["center_x"],
center["center_y"],
center["center_z"]))
else:
log_file.write("Center: {},{}\n".format(center["center_x"],
center["center_y"]))
log_file.write("Radius: {}\n".format(radius))
log_file.write("\n")
# Write statistics if available and log_statistics is True
if log_statistics:
log_file.write("Best-fit Statistics:\n")
for key, value in statistics.items():
log_file.write("{}: {}\n".format(key, value))
log_file.write("\n")
return
def check_plane_projection(points, center, normal_vector, tolerance):
"""
Check if the points lie on fitted plane or need to be projected onto it.
Parameters
----------
points : list of tuples
List of (x, y, z) points to be checked.
center : tuple
Center of the fitted plane in (x, y, z) coordinates.
normal_vector : tuple
Normal vector of the fitted plane in (a, b, c) form.
tolerance : float
Maximum allowable residual to consider points lying on the plane.
Returns
-------
bool
True if points lie on the plane, False if points need to be projected
onto the plane.
Note
----
This function checks whether a list of given points lies on the fitted
plane, based on their residuals from the plane. The parameters include the
points to be checked, the center and normal vector of the fitted plane, and
a tolerance value for residuals. The function calculates the residuals of
each point from the plane and checks if the maximum residual is within the
specified tolerance. If the maximum residual is below the tolerance, the
function returns True, indicating that the points lie on the plane.
Otherwise, it returns False, indicating that the points need to be
projected onto the plane.
"""
# Calculate the residuals of the points from the fitted circle
residuals = [np.dot(np.array(point) - np.array(center),
np.array(normal_vector)) for point in points]
# Check if the maximum residual is within the tolerance
if max(residuals) <= tolerance:
return True
else:
return False
def point_to_plane_distance(x, y, z, plane_params):
"""
Calculate perpendicular distance from a 3D point to a plane.
Given (X, Y, Z) coords of a 3D point and plane coeffs (a, b, c, d), where
a, b, c are plane's normal vector components, d is the plane offset,
this function computes perpendicular distance from point to the plane.
Parameters
----------
x : float
X-coordinate of the 3D point.
y : float
Y-coordinate of the 3D point.
z : float
Z-coordinate of the 3D point.
plane_params : tuple
Coefficients of the plane as (a, b, c, d).