-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracks.py
More file actions
2502 lines (2155 loc) · 134 KB
/
Copy pathtracks.py
File metadata and controls
2502 lines (2155 loc) · 134 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
#######################################
# Final Code to populate simulated data
#######################################
#######################################
# Imports
#######################################
import sys
from ROOT import TFile, TH1F, TSpectrum, TF1, TH2F
import ROOT as root
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.widgets import Button
import matplotlib.patches as patches
from matplotlib import cm, colors
from matplotlib.colorbar import Colorbar
from mpl_toolkits.axes_grid1 import make_axes_locatable
from collections import namedtuple
import math
from ransac import find_multiple_lines_ransac, find_iterative_lines_ransac, iterative_ransac_with_suppression
from sklearn.linear_model import LinearRegression
from sklearn.mixture import GaussianMixture
from sklearn.decomposition import PCA
from itertools import chain
from merger import calculate_cluster_metrics
import json
import os
import traceback
from sklearn.metrics import adjusted_rand_score
from write import create_tree_and_branches, fill_event_data_to_tree
import pickle
from enum import Enum
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import DBSCAN
import hdbscan
from kneed import KneeLocator
from regularize import Regularize
from libraries import DataArray, RunParameters, VolumeBoundaries, SCAN, Optimize, FileNames, Reference, ConversionFactors, RansacParameters
from collections import defaultdict
import warnings
from energy import Energy
import pandas as pd
from scipy import interpolate
import time
import math
def truncate(number, digits):
factor = 10.0 ** digits
return math.trunc(number * factor) / factor
np.random.seed(42)
#######################################
# Input arguments
#######################################
arguments = sys.argv
input_string = arguments[1]
split_strings = input_string.split('@')
excitation_energies=[split_strings[0]]
cm_angles=[split_strings[1]]
path = "/home2/user/u0100486/linux/doctorate/github/tracker_sim/DATA/simulation/5000/"
event_start = int(split_strings[2])
event_end = int(split_strings[3])
suppression_factor_index = int(split_strings[4])
suppression_values = np.linspace(0, 1, 32)
suppression_factor = suppression_values[suppression_factor_index]
plots = RunParameters.plots.value
sim = RunParameters.sim.value
debug = RunParameters.debug.value
final_plots_flag = RunParameters.final_plots_flag.value
save_final_data = RunParameters.save_final_data.value
with_missing_pads = RunParameters.with_missing_pads.value
batch_mode = RunParameters.batch_mode.value
save_to_root = RunParameters.save_to_root.value
save_python_figures = RunParameters.save_python_figures.value
np.set_printoptions(threshold=np.inf)
if batch_mode:
os.environ["DISPLAY"] = ""
root.gROOT.SetBatch(True)
# Check for display environment (for headless mode on servers, for example)
if os.getenv("DISPLAY") is None:
plt.switch_backend('Agg') # Use a non-interactive backend to silence display
#######################################
# Configuration
#######################################
NB_COBO = 16
NB_ASAD = 4
NB_AGET = 4
NB_CHANNEL = 68
beam_entrance_time = 8.96 # units [ns]
beam_center_time = 10970.0 - beam_entrance_time # units[ns], 7076.0
beam_center_peak_find_low = 8000 # units[ns]
beam_center_peak_find_high = 14000 # units[ns]
sig_beam_center = 70.0 # units [ns]
time_per_sample = 0.08 # units [us]
drift_velocity_volume = ConversionFactors.DRIFT_VELOCITY.value # units [cm/us]
table = np.loadtxt(FileNames.CONVERSION_TABLE.value)
z_conversion_factor = ConversionFactors.Z_CONVERSION_FACTOR.value
x_conversion_factor = ConversionFactors.X_CONVERSION_FACTOR.value # units[mm]
y_conversion_factor = ConversionFactors.Y_CONVERSION_FACTOR.value # units[mm]
missing_pads_info = FileNames.MISSING_PADS.value
missed_pads = np.loadtxt(missing_pads_info)
x_pos_raw = missed_pads[:, 0]
y_pos_raw = missed_pads[:, 1]
nbins_x = ConversionFactors.NBINS_X.value
x_start_bin = ConversionFactors.X_START_BIN.value
x_end_bin = ConversionFactors.X_END_BIN.value
nbins_y = ConversionFactors.NBINS_Y.value
y_start_bin = ConversionFactors.Y_START_BIN.value
y_end_bin = ConversionFactors.Y_END_BIN.value
nbins_z = ConversionFactors.NBINS_Z.value
z_start_bin = ConversionFactors.Z_START_BIN.value
z_end_bin = ConversionFactors.Z_END_BIN.value
pixel_size_mm = 2
line_length = 100
transparency = 0.7
calibration_table = pd.read_csv(FileNames.CALIBRATION_PADS.value, sep=" ", header=None)
calibration_table.columns = ["chno", "xx", "yy", "par0", "par1", "chi"]
range_lookup_table = FileNames.CONFIG_FILE_EXCEL.value
sheet_ = FileNames.RANGE_ENERGY_CONVERSION_SHEET.value
excel_data_df = pd.read_excel(range_lookup_table, sheet_name=sheet_)
_TABLE = np.array(excel_data_df[['Range(mm)', 'Energy(keV)']])
_TABLE = _TABLE[_TABLE[:, 0].argsort()]
_TABLE_REVERSED = _TABLE[:, [1, 0]] # Now it's [Energy, Range]
# Optional: sort by energy just in case
_TABLE_REVERSED = _TABLE_REVERSED[_TABLE_REVERSED[:, 0].argsort()]
#######################################
# Graphics
#######################################
fig, axs = plt.subplots(4, 4, figsize=(20, 10))
ax1 = axs[0,0]
ax2 = axs[0,1]
ax3 = axs[0,2]
ax4 = axs[0,3]
ax5 = axs[1,0]
ax6 = axs[1,1]
ax7 = axs[1,2]
ax8 = axs[2,0]
ax9 = axs[2,1]
ax10 = axs[2,2]
ax11 = axs[3,0]
ax12 = axs[3,1]
ax13 = axs[3,2]
ax14 = axs[1,3]
ax15 = axs[2,3]
ax16 = axs[3,3]
# Function to add rectangle patches for each point
def add_rectangles(ax, xyz_data, labels, cmap, proj, colorbarFlag, discrete=False):
unique_labels = np.unique(labels)
if discrete:
label_mapping = {label: idx for idx, label in enumerate(unique_labels)}
mapped_labels = np.array([label_mapping[label] for label in labels])
labels = mapped_labels
for (x, y, z), label in zip(xyz_data, labels):
color = cmap(int(label) % cmap.N)
if proj == 'yz':
x = y
y = z
if proj == 'xz':
x = x
y = z
rect = patches.Rectangle((x, y), pixel_size_mm, pixel_size_mm, linewidth=0.5,
edgecolor='none', facecolor=color, alpha=0.7)
ax.add_patch(rect)
if colorbarFlag:
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
if fig.get_axes().count(cax): # Check if cax exists in figure axes
cax.cla() # Clear the colorbar axis to reset it
norm = colors.Normalize(vmin=0, vmax=len(unique_labels) - 1) # Update normalization
sm = cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([]) # Avoid warnings
colorbar = fig.colorbar(sm, cax=cax, orientation='vertical', label='Intensity')
if discrete:
colorbar.set_ticks(np.arange(len(unique_labels)))
colorbar.set_ticklabels(unique_labels) # Set original label values
return colorbar
else:
return None
# Function to set custom grid and sparse Y-axis tick labels
def set_custom_grid(ax):
x_limits = (0, 256)
y_limits = (0, 256)
ax.set_xlim(x_limits)
ax.set_ylim(y_limits)
# Set grid ticks every 2 mm on both axes
ax.set_xticks(np.arange(x_limits[0], x_limits[1] + 1, 20), minor=False)
ax.set_yticks(np.arange(y_limits[0], y_limits[1] + 1, pixel_size_mm), minor=True)
ax.set_xticks(np.arange(x_limits[0], x_limits[1] + 1, pixel_size_mm), minor=True)
ax.set_yticks(np.arange(y_limits[0], y_limits[1] + 1, 20), minor=False)
# Display grid
ax.grid(which="both", color="lightgray", linestyle="--", linewidth=0.5)
# Label Y-axis major ticks every 20 mm
y_labels = np.arange(y_limits[0], y_limits[1] + 1, 20)
ax.set_yticklabels(y_labels)
# Label X-axis major ticks every 20 mm
x_labels = np.arange(x_limits[0], x_limits[1] + 1, 20)
ax.set_xticklabels(x_labels)
# Function to clear and update axes
def update_clear(ax):
ax.clear()
if ax in [ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10, ax11, ax12, ax13]:
set_custom_grid(ax)
if ax in [ax2, ax5, ax8, ax11]:
xlabel = 'X [mm]'
ylabel = 'Y [mm]'
if ax in [ax3, ax6, ax9, ax12]:
xlabel = 'Y [mm]'
ylabel = 'Z [mm]'
if ax in [ax4, ax7, ax10, ax13]:
xlabel = 'X [mm]'
ylabel = 'Z [mm]'
ax.set_xlabel(xlabel, fontsize=12, fontweight='bold')
ax.set_ylabel(ylabel, fontsize=12, fontweight='bold')
if ax in [ax1]:
ax.set_xlabel('Z', fontsize=12, fontweight='bold')
ax.set_ylabel('Counts', fontsize=12, fontweight='bold')
if ax in [ax15, ax16]:
ax.set_xlabel('Position', fontsize=12, fontweight='bold')
ax.set_ylabel('Charge', fontsize=12, fontweight='bold')
ax.grid(True)
update_clear(ax1)
update_clear(ax2)
update_clear(ax3)
update_clear(ax4)
update_clear(ax5)
update_clear(ax6)
update_clear(ax7)
update_clear(ax8)
update_clear(ax9)
update_clear(ax10)
update_clear(ax11)
update_clear(ax12)
update_clear(ax13)
update_clear(ax14)
update_clear(ax15)
update_clear(ax16)
next_pressed = False
# Create a button for going to the next entry
ax_next = plt.axes([0.45, 0.01, 0.1, 0.05]) # Button position and size
button_next = Button(ax_next, 'Next')
# Callback function to handle button clicks
def next_button_callback(event):
global next_pressed
next_pressed = True # Set the flag to True when the button is pressed
# Attach the callback to the button
button_next.on_clicked(next_button_callback)
#######################################
# Supporting Functions
#######################################
def get_yz_min_max(data):
"""
Returns the minimum and maximum values for Y and Z from the data array.
Args:
data (np.ndarray): A NumPy array where columns represent X, Y, and Z.
Returns:
dict: A dictionary containing min/max values of Y and Z.
"""
if data.shape[1] < 3:
raise ValueError("Data must have at least three columns (X, Y, Z).")
# Extract Y and Z columns
y_values = data[:, DataArray.Y.value]
z_values = data[:, DataArray.Z.value]
# Compute min and max
y_min, y_max = np.min(y_values), np.max(y_values)
z_min, z_max = np.min(z_values), np.max(z_values)
return {
"y_min": y_min,
"y_max": y_max,
"z_min": z_min,
"z_max": z_max
}
def angle_between(v1, v2, event_id=None):
"""
Calculate the angle (in degrees) between two vectors.
Parameters:
v1 (array-like): The first vector.
v2 (array-like): The second vector.
Returns:
float: The angle between the two vectors in degrees.
"""
# Compute cosine of the angle
try:
with warnings.catch_warnings():
warnings.filterwarnings("error", category=RuntimeWarning)
cos_theta = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
except ZeroDivisionError: # Handle zero-length vectors
if event_id is not None:
print(f"Warning: Zero-length vector encountered in event {event_id}. Returning angle as 0.")
return 0.0
except RuntimeWarning:
if event_id is not None:
print(f"Warning: Invalid value encountered in event {event_id}. Returning angle as 0.")
return 0.0
# Ensure cosine is within valid range
cos_theta = np.clip(cos_theta, -1.0, 1.0)
# Return angle in degrees
return np.degrees(np.arccos(cos_theta))
def calculate_phi_angle(v, beam_v):
"""
Calculate the angle (in degrees) of a single vector in the YZ plane
relative to the positive Y-axis.
Parameters:
v (array-like): The vector (3D).
Returns:
float: The signed angle of the vector in the YZ plane in degrees.
Returns 400 if the vector has no magnitude in the YZ plane.
"""
# Project the vector onto the YZ plane (ignore x-component)
v_yz = np.array([v[1], v[2]])
# Compute the norm of the projected vector
norm_v = np.linalg.norm(v_yz)
# Handle zero-magnitude vector
if norm_v == 0:
return 400 # Return 400 for zero magnitude in YZ plane
# Reference direction is along the positive Y-axis
ref_vector = np.array([1, 0]) # Positive Y-axis in YZ plane
# Compute the dot product and angle
dot_product = np.dot(v_yz, ref_vector)
cos_theta = dot_product / norm_v
cos_theta = np.clip(cos_theta, -1.0, 1.0) # Ensure valid range for arccos
angle = np.degrees(np.arccos(cos_theta))
# Compute the cross product to determine the sign of the angle
cross_product_z = v_yz[0] * ref_vector[1] - v_yz[1] * ref_vector[0]
# Determine the sign of the angle
if cross_product_z < 0:
angle = -angle # Negative direction
return angle
def get_gpeaks(h, lrange, sigma, opt, thres, niter):
s = TSpectrum(niter)
h.GetXaxis().SetRange(lrange[0], lrange[1])
try:
s.Search(h, sigma, opt, thres)
bufX, bufY = s.GetPositionX(), s.GetPositionY()
pos = []
for i in range(s.GetNPeaks()):
pos.append([bufX[i], bufY[i]])
pos.sort()
return pos
except:
return [[beam_center_time, 10]]
def get_beam_center(entries):
z_proj = TH1F('z_proj', 'z_proj', 20000, 0, 20000)
z_proj.Reset()
length = entries.data.CoboAsad.size()
z_proj_arr = []
for xq in range(length):
co = entries.data.CoboAsad[xq].globalchannelid >> 11
if co != 31 and co != 16:
asad = (entries.data.CoboAsad[xq].globalchannelid - (co << 11)) >> 9
ag = (entries.data.CoboAsad[xq].globalchannelid - (co << 11) - (asad << 9)) >> 7
ch = entries.data.CoboAsad[xq].globalchannelid - (co << 11) - (asad << 9) - (ag << 7)
where = co * NB_ASAD * NB_AGET * NB_CHANNEL + asad * NB_AGET * NB_CHANNEL + ag * NB_CHANNEL + ch
hitlength = entries.data.CoboAsad[int(xq)].peakheight.size()
for yq in range(0, hitlength):
posZ = entries.data.CoboAsad[int(xq)].peaktime[int(yq)]
if not entries.data.CoboAsad[xq].hasSaturation:
z_proj.Fill(entries.data.CoboAsad[int(xq)].peaktime[int(yq)])
z_proj_arr.append([entries.data.CoboAsad[int(xq)].peaktime[int(yq)]])
peaks = get_gpeaks(z_proj,[beam_center_peak_find_low, beam_center_peak_find_high], 2, "",0.5, 10)
xpeaks = np.array(peaks)
try:
if len(xpeaks[:, 0]) > 1:
max_index = np.argmax(xpeaks[:, 1])
max_location = xpeaks[max_index, 0]
fit_gaus = TF1("fit_gaus", "gaus", max_location - 1000, max_location + 1000)
z_proj.Fit(fit_gaus, "RQN0", "NOM", max_location - 4 * sig_beam_center,
max_location + 4 * sig_beam_center)
beam_c = fit_gaus.GetParameter(1) - beam_entrance_time
# print('Center of Z->', beam_c)
else:
beam_c = beam_center_time - beam_entrance_time
except:
beam_c = beam_center_time - beam_entrance_time
if plots:
z_proj_nparr = np.array(z_proj_arr)
update_clear(ax1)
ax1.hist(z_proj_nparr, bins=50, range=(beam_center_time-1000,beam_center_time+1000), color='skyblue', alpha=0.7, label="Time")
ax1.text(0.95, 0.95, f'Beam Center: {beam_c}',
horizontalalignment='right',
verticalalignment='top',
transform=ax1.transAxes, # Use axes coordinates
fontsize=12,
bbox=dict(facecolor='white', alpha=0.5))
plt.draw()
return beam_c
def get_data_array(beam_center, entries, event_info):
global axs
data_points = []
incoming_labels = []
# print("Getting Data Array")
length = entries.data.CoboAsad.size()
for x in range(length):
co = entries.data.CoboAsad[x].globalchannelid >> 11
if co != 31 and co != 16:
asad = (entries.data.CoboAsad[x].globalchannelid - (co << 11)) >> 9
ag = (entries.data.CoboAsad[x].globalchannelid - (co << 11) - (asad << 9)) >> 7
ch = entries.data.CoboAsad[x].globalchannelid - (co << 11) - (asad << 9) - (ag << 7)
where = co * NB_ASAD * NB_AGET * NB_CHANNEL + asad * NB_AGET * NB_CHANNEL + ag * NB_CHANNEL + ch
posX = (table[where][4] * x_conversion_factor)
posY = (table[where][5] * y_conversion_factor)
missing_pad_check = False
posX_raw = table[where][4]
posY_raw = table[where][5]
t = missed_pads[(missed_pads[:, 0] == posX_raw) & (missed_pads[:, 1] == posY_raw)]
if len(t) >= 1:
if with_missing_pads:
missing_pad_check = True
else:
missing_pad_check = False
hitlength = entries.data.CoboAsad[int(x)].peakheight.size()
for y in range(0, hitlength):
if entries.data.input_ejectile_mom_dirY >=0:
posZ = (beam_center + (beam_center - entries.data.CoboAsad[int(x)].peaktime[int(y)])) * z_conversion_factor
else:
posZ = (beam_center - (entries.data.CoboAsad[int(x)].peaktime[int(y)]-beam_center)) * z_conversion_factor
posZ = entries.data.CoboAsad[int(x)].peaktime[int(y)]* z_conversion_factor
Qvox = entries.data.CoboAsad[int(x)].peakheight[int(y)]
if not entries.data.CoboAsad[x].hasSaturation and not missing_pad_check:
data_points.append([posX, posY, posZ, Qvox])
incoming_labels.append(entries.data.CoboAsad[int(x)].trackID[int(y)])
data = np.array(data_points)
true_labels_sim = assign_beam_or_scattered(data, incoming_labels)
if plots:
# charge = data[:, DataArray.Q.value]
charge = np.array(true_labels_sim)
cmap = plt.cm.get_cmap("Dark2", len(np.unique(charge)))
update_clear(ax2)
update_clear(ax3)
update_clear(ax4)
colorbar1 = add_rectangles(ax2, data[:, DataArray.X.value:DataArray.Z.value + 1], charge, cmap, proj = 'xy', colorbarFlag=False, discrete=True)
colorbar2 = add_rectangles(ax3, data[:, DataArray.X.value:DataArray.Z.value + 1], charge, cmap, proj = 'yz', colorbarFlag=False, discrete=True)
colorbar3 = add_rectangles(ax4, data[:, DataArray.X.value:DataArray.Z.value + 1], charge, cmap, proj = 'xz', colorbarFlag=False, discrete=True)
num_data_points = len(data[:, DataArray.X.value])
ax2.plot([event_info.verX, event_info.verX + line_length * event_info.dirX],[event_info.verY, event_info.verY + line_length * event_info.dirY],
color='blue', alpha=transparency)
ax2.scatter(event_info.verX, event_info.verY, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
# Place the number of data points in the top right corner
ax2.text(0.95, 0.95, f'Count: {num_data_points}, E: {event_info.Eenergy}, L: {event_info.Elab}',
horizontalalignment='right',
verticalalignment='top',
transform=ax2.transAxes, # Use axes coordinates
fontsize=12,
bbox=dict(facecolor='white', alpha=0.5))
ax3.plot([event_info.verY, event_info.verY + line_length * event_info.dirY],[event_info.verZ, event_info.verZ + line_length * event_info.dirZ],
color='blue', alpha=transparency)
ax3.scatter(event_info.verY, event_info.verZ, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
ax3.text(0.95, 0.95, f'Count: {num_data_points}, E: {event_info.Eenergy}, L: {event_info.Elab}',
horizontalalignment='right',
verticalalignment='top',
transform=ax3.transAxes, # Use axes coordinates
fontsize=12,
bbox=dict(facecolor='white', alpha=0.5))
ax4.plot([event_info.verX, event_info.verX + line_length * event_info.dirX],[event_info.verZ, event_info.verZ + line_length * event_info.dirZ],
color='blue', alpha=transparency)
ax4.scatter(event_info.verX, event_info.verZ, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
ax4.text(0.95, 0.95, f'Count: {num_data_points}, E: {event_info.Eenergy}, L: {event_info.Elab}',
horizontalalignment='right',
verticalalignment='top',
transform=ax4.transAxes, # Use axes coordinates
fontsize=12,
bbox=dict(facecolor='white', alpha=0.5))
plt.draw()
return data, incoming_labels, [colorbar1, colorbar2, colorbar3]
# print('Checking plot return')
return data, incoming_labels
def generate_true_labels(data_array, event_info):
y_values = data_array[:, DataArray.Y.value]
labels = np.where((y_values >= VolumeBoundaries.BEAM_ZONE_MIN.value) & (y_values < VolumeBoundaries.BEAM_ZONE_MAX.value), 0, 1)
data_array = np.column_stack((data_array, labels))
if plots:
cmap = plt.cm.get_cmap("Dark2", len(np.unique(labels)))
update_clear(ax5)
update_clear(ax6)
update_clear(ax7)
colorbar4 = add_rectangles(ax5, data_array[:, DataArray.X.value:DataArray.Z.value + 1], labels, cmap, proj = 'xy', colorbarFlag=False, discrete=True)
colorbar5 = add_rectangles(ax6, data_array[:, DataArray.X.value:DataArray.Z.value + 1], labels, cmap, proj = 'yz', colorbarFlag=False, discrete=True)
colorbar6 = add_rectangles(ax7, data_array[:, DataArray.X.value:DataArray.Z.value + 1], labels, cmap, proj = 'xz', colorbarFlag=False, discrete=True)
num_data_points = len(data_array[:, DataArray.X.value])
# Place the number of data points in the top right corner
ax5.plot([event_info.verX, event_info.verX + line_length * event_info.dirX],[event_info.verY, event_info.verY + line_length * event_info.dirY],
color='blue', alpha=transparency)
ax5.scatter(event_info.verX, event_info.verY, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
ax5.text(0.95, 0.95, f'Count: {num_data_points}, E: {event_info.Eenergy}, L: {event_info.Elab}',
horizontalalignment='right',
verticalalignment='top',
transform=ax5.transAxes, # Use axes coordinates
fontsize=12,
bbox=dict(facecolor='white', alpha=0.5))
ax6.plot([event_info.verY, event_info.verY + line_length * event_info.dirY],[event_info.verZ, event_info.verZ + line_length * event_info.dirZ],
color='blue', alpha=transparency)
ax6.scatter(event_info.verY, event_info.verZ, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
ax6.text(0.95, 0.95, f'Count: {num_data_points}, E: {event_info.Eenergy}, L: {event_info.Elab}',
horizontalalignment='right',
verticalalignment='top',
transform=ax6.transAxes, # Use axes coordinates
fontsize=12,
bbox=dict(facecolor='white', alpha=0.5))
ax7.plot([event_info.verX, event_info.verX + line_length * event_info.dirX],[event_info.verZ, event_info.verZ + line_length * event_info.dirZ],
color='blue', alpha=transparency)
ax7.scatter(event_info.verX, event_info.verZ, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
ax7.text(0.95, 0.95, f'Count: {num_data_points}, E: {event_info.Eenergy}, L: {event_info.Elab}',
horizontalalignment='right',
verticalalignment='top',
transform=ax7.transAxes, # Use axes coordinates
fontsize=12,
bbox=dict(facecolor='white', alpha=0.5))
plt.draw()
return data_array
def plot_ransac(data_array, event_info, vertex=None, endpoint=None, end_point_geom=None, orl=None):
labels = data_array[:, DataArray.ransac_labels.value]
# labels = orl
cmap = plt.cm.get_cmap("Dark2", len(np.unique(labels)))
update_clear(ax8)
update_clear(ax9)
update_clear(ax10)
colorbar4 = add_rectangles(ax8, data_array[:, DataArray.X.value:DataArray.Z.value + 1], labels, cmap, proj = 'xy', colorbarFlag=True, discrete=True)
colorbar5 = add_rectangles(ax9, data_array[:, DataArray.X.value:DataArray.Z.value + 1], labels, cmap, proj = 'yz', colorbarFlag=True, discrete=True)
colorbar6 = add_rectangles(ax10, data_array[:, DataArray.X.value:DataArray.Z.value + 1], labels, cmap, proj = 'xz', colorbarFlag=True, discrete=True)
# Place the number of data points in the top right corner
ax8.plot([event_info.verX, event_info.verX + line_length * event_info.dirX],[event_info.verY, event_info.verY + line_length * event_info.dirY],
color='blue', alpha=transparency)
ax8.scatter(event_info.verX, event_info.verY, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
ax8.set_xlim(vertex[0]-RunParameters.zoom_in_length.value, end_point_geom[0]+RunParameters.zoom_in_length.value)
if event_info.dirY >=0:
ax8.set_ylim(vertex[1]-RunParameters.zoom_in_length.value, end_point_geom[1]+RunParameters.zoom_in_length.value)
if event_info.dirY <0:
ax8.set_ylim(end_point_geom[1]-RunParameters.zoom_in_length.value, vertex[1]+RunParameters.zoom_in_length.value)
ax9.plot([event_info.verY, event_info.verY + line_length * event_info.dirY],[event_info.verZ, event_info.verZ - line_length * event_info.dirZ],
color='blue', alpha=transparency)
ax9.scatter(event_info.verY, event_info.verZ, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
if event_info.dirY >=0:
ax9.set_xlim(vertex[1]-RunParameters.zoom_in_length.value, end_point_geom[1]+RunParameters.zoom_in_length.value)
if event_info.dirY <0:
ax9.set_xlim(end_point_geom[1]-RunParameters.zoom_in_length.value, vertex[1]+RunParameters.zoom_in_length.value)
if event_info.dirZ >=0:
ax9.set_ylim(end_point_geom[2]-RunParameters.zoom_in_length.value, vertex[2]+RunParameters.zoom_in_length.value)
if event_info.dirZ <0:
ax9.set_ylim(vertex[2]-RunParameters.zoom_in_length.value, end_point_geom[2]+RunParameters.zoom_in_length.value)
ax10.plot([event_info.verX, event_info.verX + line_length * event_info.dirX],[event_info.verZ, event_info.verZ - line_length * event_info.dirZ],
color='blue', alpha=transparency)
ax10.scatter(event_info.verX, event_info.verZ, color='red', edgecolor='black', s=50, zorder=3) # Circle for vertex
ax10.set_xlim(vertex[0]-RunParameters.zoom_in_length.value, end_point_geom[0]+RunParameters.zoom_in_length.value)
if event_info.dirZ >=0:
ax10.set_ylim(end_point_geom[2]-RunParameters.zoom_in_length.value, vertex[2]+RunParameters.zoom_in_length.value)
if event_info.dirZ <0:
ax10.set_ylim(vertex[2]-RunParameters.zoom_in_length.value, end_point_geom[2]+RunParameters.zoom_in_length.value)
plt.draw()
return [colorbar4, colorbar5, colorbar6]
def return_threshold_lines(start_point, direction_vector):
# Normalize the direction vector
direction_vector_normalized = direction_vector / np.linalg.norm(direction_vector)
# Threshold distance (5 mm) perpendicular to the line
threshold_distance = 5
# Generate points along the fitted line for plotting
t_values = np.linspace(-50, 50, 100) # Adjust range as needed
fitted_line_points = start_point + t_values[:, None] * direction_vector_normalized
# Create perpendicular vectors in the plane perpendicular to the direction vector
# Find any vector orthogonal to the direction vector
arbitrary_vector = np.array([1, 0, 0]) if direction_vector_normalized[0] == 0 else np.array([0, 1, 0])
perpendicular_vector1 = np.cross(direction_vector_normalized, arbitrary_vector)
perpendicular_vector1 /= np.linalg.norm(perpendicular_vector1)
# Create another perpendicular vector orthogonal to both direction_vector and perpendicular_vector1
perpendicular_vector2 = np.cross(direction_vector_normalized, perpendicular_vector1)
perpendicular_vector2 /= np.linalg.norm(perpendicular_vector2)
# Calculate points at threshold distances in both perpendicular directions
threshold_line_above1 = fitted_line_points + threshold_distance * perpendicular_vector1
threshold_line_below1 = fitted_line_points - threshold_distance * perpendicular_vector1
threshold_line_above2 = fitted_line_points + threshold_distance * perpendicular_vector2
threshold_line_below2 = fitted_line_points - threshold_distance * perpendicular_vector2
return threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2
def extend_line_based_on_reference(start_point, end_point, start_point_full, end_point_full, inter, extra_start: float = float(Reference.RANGE_EXTEND.value), event_info=None):
"""
Extends a 3D line segment:
- The start point moves back by `extra_start` mm.
- The end point moves forward so that the new total length is at least `20 mm` longer than the reference line.
Parameters:
- start_point (numpy array): Start point of the primary line (x, y, z).
- end_point (numpy array): End point of the primary line (x, y, z).
- start_point_full (numpy array): Start point of the reference line (x, y, z).
- end_point_full (numpy array): End point of the reference line (x, y, z).
- extra_start (float): Fixed extension length for the start point (default is 20 mm).
Returns:
- numpy array: A (2,3) array with the new extended start and end points.
"""
# Convert to numpy arrays
start_point = np.array(start_point)
end_point = np.array(end_point)
start_point_full = np.array(start_point_full)
end_point_full = np.array(end_point_full)
# Compute the direction vector and normalize
direction = end_point - start_point
original_length = np.linalg.norm(direction)
if original_length == 0:
raise ValueError("Start and end points are the same. Cannot define a line. event_info: {}".format(event_info.event_id if event_info else "N/A"))
unit_direction = direction / original_length
# Compute the reference line length
reference_length = np.linalg.norm(end_point_full - start_point_full)
# Compute new total length (at least 20mm longer than reference)
new_total_length = reference_length + extra_start
extra_end = new_total_length - original_length # Remaining extension for the end
if extra_end < 0:
raise ValueError("Reference line is too short to extend properly.")
# Extend start and end points
extended_start = start_point - extra_start * unit_direction
extended_end = end_point + extra_end * unit_direction
# Return as a (2,3) array
return np.vstack((inter, extended_end))
def plot_energy_distributions(ax, r2d, sd, ran_end_, en_end_, ran_max_, en_max_,
charge_profile_x, charge_profile_y,
charge_profile_x_s, charge_profile_y_s):
"""
Plots the smoothed and unsmoothed energy distributions as a function of position on the given Axes object.
Adds horizontal lines at the position of the maximum energy and the last intersection point.
Parameters:
ax (matplotlib.axes.Axes): The Axes object on which to plot.
r2d (float): 2D distance of the final bin or peak from the start of the line.
sd (float): Vertical (Z-axis) distance of the final bin or peak from the start of the line.
ran_end_ (float): Position of the last intersection point between the energy curve and threshold.
en_end_ (float): Energy value at the last intersection point.
ran_max_ (float): Position of the maximum energy value in the interpolated distribution.
en_max_ (float): Maximum energy value in the interpolated distribution.
charge_profile_x (numpy array): Positions of the unsmoothed energy bins.
charge_profile_y (numpy array): Unsmoothed energy values.
charge_profile_x_s (numpy array): Positions of the smoothed energy bins.
charge_profile_y_s (numpy array): Smoothed energy values.
"""
update_clear(ax)
# Plot the unsmoothed energy distribution
ax.plot(charge_profile_x, charge_profile_y, 'b-', label="Unsmoothed Energy", alpha=0.6)
# Plot the smoothed energy distribution
ax.plot(charge_profile_x_s, charge_profile_y_s, 'r-', label="Smoothed Energy", linewidth=2)
# Add horizontal lines for key positions
ax.axvline(x=ran_max_, color='g', linestyle='--', label=f"Max Energy Position: {ran_max_:.2f}")
ax.axvline(x=ran_end_, color='m', linestyle='--', label=f"Last Intersection Position: {ran_end_:.2f}")
def filter_track_data(cut_data_charge, track_above):
"""
Filters the cut_data_charge array based on track position.
Parameters:
cut_data_charge (numpy.ndarray): 2D NumPy array containing the data.
Returns:
numpy.ndarray: Filtered array based on track position.
"""
if track_above:
filtered_data = cut_data_charge[cut_data_charge[:, DataArray.Y.value] > VolumeBoundaries.BEAM_ZONE_MAX.value]
else:
filtered_data = cut_data_charge[cut_data_charge[:, DataArray.Y.value] < VolumeBoundaries.BEAM_ZONE_MIN.value]
return filtered_data
def segment_beta(cluster_data, mask, fraction_beta, model = 'gmm'):
if model == 'ransac':
old_label = DataArray.old_ransac_labels.value
if model == 'gmm':
old_label = DataArray.merge_p_val.value
beam_start = np.array([0.0, 128.0, 128.0])
beam_end = np.array([256.0, 128.0, 128.0])
beam_dir = beam_end - beam_start
pts_cdist = cluster_data[mask, :]
segments = []
for gmm_label_pval in np.unique(pts_cdist[:, old_label]):
pts_pval = pts_cdist[pts_cdist[:, old_label] == gmm_label_pval, 0:3]
if len(pts_pval) < 2:
continue
end_point_pval, start_point_pval, _, _, _, closest_points_pval = get_directions(pts_pval)
segments.append({'pval_label': gmm_label_pval, 'start': start_point_pval, 'end':end_point_pval, 'length':np.linalg.norm(end_point_pval-start_point_pval), 'closest_points': closest_points_pval, 'points': pts_pval})
for segment in segments:
segment['d_beam'] = point_to_line_distance(segment['start'], beam_start, beam_dir)
segments.sort(key=lambda s: s['d_beam'])
total_len = sum(s['length'] for s in segments)
cutoff = fraction_beta * total_len
cum_len = 0.0
selected_points = []
for segment in segments:
segment_length = segment['length']
direction = segment['end'] - segment['start']
direction_unit = direction / segment_length
if cum_len + segment['length'] < cutoff:
selected_points.append(segment['points'])
cum_len += segment['length']
else:
remain = cutoff - cum_len
distances_from_start = np.linalg.norm(segment['closest_points'] - segment['start'], axis=1)
mask_beta_fraction = (distances_from_start >= 0) & (distances_from_start <= remain)
selected_points.append(segment['points'][mask_beta_fraction])
break
# Concatenate selected points
if selected_points:
selected_pts_array = np.vstack(selected_points)
filtered_data_beta = selected_pts_array
return filtered_data_beta
def kinematics_ransac(data_initial, fitted_models, useLineModelND, orl = None, event_info=None):
# Define the beam line endpoints
data_arr = add_filters(data_initial, model= int(DataArray.ransac_labels.value))
data_in = np.column_stack((data_arr, orl))
data = data_in[data_in[:, DataArray.ransac_labels.value] != 20]
lab_angles_initial = {}
intersections_initial = {}
phi_angles_initial = {}
start_point_initial = {}
end_point_initial = {}
ranges_initial = {}
ranges_final = {}
energy_initial = {}
ransac_labels = np.unique(data[:, DataArray.ransac_labels.value])
for label in ransac_labels:
# Get the points corresponding to the current label
cluster_data = data[data[:, DataArray.ransac_labels.value] == label]
# Check if the cluster size is greater than 10
if cluster_data.shape[0] < 10:
continue # Skip this cluster if it has fewer than 10 points
# Calculate the mean y of the cluster
mean_y = np.mean(cluster_data[:, DataArray.Y.value])
# Process clusters either above or below the beam line
if (mean_y >= VolumeBoundaries.BEAM_ZONE_MAX.value or mean_y < VolumeBoundaries.BEAM_ZONE_MIN.value) and cluster_data.shape[0] >= 10:
# mask = (
# (cluster_data[:, DataArray.scattered_track.value] == 1) &
# (cluster_data[:, DataArray.track_inside_volume.value] == 1) &
# (cluster_data[:, DataArray.vertex_inside_volume.value] == 1) &
# ((cluster_data[:, DataArray.side_of_track.value] == 1) | (cluster_data[:, DataArray.side_of_track.value] == -1)) & # Column : (side_flag_col) = 1 or -1
# ((cluster_data[:, DataArray.closest_track.value] == 1) | (cluster_data[:, DataArray.closest_track.value] == -1)) & # Column: (proximity_flag_col) = 1 or -1
# (cluster_data[:, DataArray.end_point_above_beam_zone.value] == 1) # Column 12: Track End point above the beam zone
# )
mask1 = cluster_data[:, DataArray.scattered_track.value] == 1
if mean_y >= VolumeBoundaries.BEAM_ZONE_MAX.value:
track_position = 'above'
mask2 = cluster_data[:, DataArray.Y.value] > 128
else:
track_position = 'below'
mask2 = cluster_data[:, DataArray.Y.value] < 128
mask = mask1
cut_data = cluster_data[mask, :3]
cut_data_charge = cluster_data[mask, :4]
if cut_data.size > 2:
# Fill the lab angles and intersections based on first PCA fit.
end_point_full, start_point_full, beam_vector_full, dirVecTrackNorm_full, track_mean_full, closest_points_full = get_directions(cut_data)
track_vector_full = end_point_full - start_point_full
print('RANSAC Fit', label, start_point_full, end_point_full)
intersection_point_full = closest_point_on_line1(start_point_full, track_vector_full, np.array([0,128,128]), beam_vector_full)
filtered_data_beta = np.array([])
if RunParameters.use_beta_fraction.value:
beam_start = np.array([0.0, 128.0, 128.0])
beam_end = np.array([256.0, 128.0, 128.0])
beam_dir = beam_end - beam_start
# Applying Segment fit here.
pts_cdist = cluster_data[mask, :]
segments = []
for gmm_label_pval in np.unique(pts_cdist[:, DataArray.old_ransac_labels.value]):
pts_pval = pts_cdist[pts_cdist[:, DataArray.old_ransac_labels.value] == gmm_label_pval, 0:3]
if len(pts_pval) < 2:
continue
end_point_pval, start_point_pval, _, _, _, closest_points_pval = get_directions(pts_pval)
segments.append({'pval_label': gmm_label_pval, 'start': start_point_pval, 'end':end_point_pval, 'length':np.linalg.norm(end_point_pval-start_point_pval), 'closest_points': closest_points_pval, 'points': pts_pval})
for segment in segments:
segment['d_beam'] = point_to_line_distance(segment['start'], beam_start, beam_dir)
segments.sort(key=lambda s: s['d_beam'])
total_len = sum(s['length'] for s in segments)
cutoff = Optimize.BETA_FRACTION.value * total_len
cum_len = 0.0
selected_points = []
for segment in segments:
segment_length = segment['length']
direction = segment['end'] - segment['start']
direction_unit = direction / segment_length
if cum_len + segment['length'] < cutoff:
selected_points.append(segment['points'])
cum_len += segment['length']
else:
remain = cutoff - cum_len
distances_from_start = np.linalg.norm(segment['closest_points'] - segment['start'], axis=1)
mask_beta_fraction = (distances_from_start >= 0) & (distances_from_start <= remain)
selected_points.append(segment['points'][mask_beta_fraction])
break
# Concatenate selected points
if selected_points:
selected_pts_array = np.vstack(selected_points)
filtered_data_beta = selected_pts_array
else:
distances_from_start = np.linalg.norm(closest_points_full - start_point_full, axis=1)
mask_beta = (distances_from_start >= 0) & (distances_from_start <= Optimize.BETA.value)
filtered_data_beta = cut_data[mask_beta, :]
if plots:
plot_lines(track_mean_full, dirVecTrackNorm_full, start_point_full, end_point_full, intersection_point_full, closest_points_full, ax8, ax9, ax10, color='blue', s=400)
if len(filtered_data_beta) > 2:
end_point_beta, start_point_beta, beam_vector_beta, dirVecTrackNorm_beta, track_mean_beta, closest_points_beta = get_directions(filtered_data_beta)
track_vector_beta = end_point_beta - start_point_beta
lab_angle_beta = angle_between(track_vector_beta, beam_vector_beta, event_info.event_id)
phi_angle_beta = calculate_phi_angle(track_vector_beta, beam_vector_beta)
intersection_point_beta = closest_point_on_line1(start_point_beta, track_vector_beta, np.array([0,128,128]), beam_vector_beta)
lab_angles_initial[label] = round(lab_angle_beta, 2)
intersections_initial[label] = intersection_point_beta
# start_point_initial[label] = start_point_beta
# end_point_initial[label] = end_point_beta
phi_angles_initial[label] = phi_angle_beta
end_point_full, start_point_full, beam_vector_full, dirVecTrackNorm_full, track_mean_full, closest_points_full = get_directions(cut_data)
start_point_initial[label] = start_point_full
end_point_initial[label] = end_point_full
endpts = extend_line_based_on_reference(start_point_beta, end_point_beta, start_point_full, end_point_full, intersection_point_beta, extra_start=float(Reference.RANGE_EXTEND.value), event_info=event_info)
en = Energy(cut_data_charge, endpts, calibration_table)
new_position, fit_energy_, line_vector_start_3d, unit_vector_3d, line_length_2d, line_vector_end_3d, histogram_array_new = en.calculate_profiles()
if RunParameters.optimize_alpha.value:
ranges = {}
alpha_values = np.linspace(Optimize.ALPHA_RANGE_LOW.value, Optimize.ALPHA_RANGE_HIGH.value, Optimize.ALPHA_STEPS.value)
for alpha in alpha_values:
_, _, ran_end_, _, ran_max_, _, _, _, _, _ = en.energy_weighted(alpha, new_position, fit_energy_, line_vector_start_3d, unit_vector_3d, line_length_2d, line_vector_end_3d, histogram_array_new)
ranges[alpha] = (ran_end_, ran_max_)
ranges_initial[label] = ranges
r2d, sd, ran_end_, en_end_, ran_max_, en_max_, charge_profile_x, charge_profile_y, charge_profile_x_s, charge_profile_y_s = en.energy_weighted(Optimize.ALPHA.value, new_position, fit_energy_, line_vector_start_3d, unit_vector_3d, line_length_2d, line_vector_end_3d, histogram_array_new)
ranges_final[label] = ran_end_
if plots:
plot_lines(track_mean_beta, dirVecTrackNorm_beta, start_point_beta, end_point_beta, intersection_point_beta, closest_points_beta, ax8, ax9, ax10, color='green', s=200)
plot_lines(track_mean_beta, dirVecTrackNorm_beta, endpts[0, :], endpts[1, :], intersection_point_beta, closest_points_beta, ax8, ax9, ax10, color='red', s=100)
plot_energy_distributions(ax15, r2d, sd, ran_end_, en_end_, ran_max_, en_max_,
charge_profile_x, charge_profile_y,
charge_profile_x_s, charge_profile_y_s)
if not useLineModelND:
threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2 = return_threshold_lines(track_mean_full, dirVecTrackNorm_full)
plot_threshold_lines(track_mean_full, dirVecTrackNorm_full, threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2)
else:
model_params = fitted_models[label].params
threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2 = return_threshold_lines(np.array(model_params[0]), np.array(model_params[1]))
plot_threshold_lines(np.array(model_params[0]), np.array(model_params[1]), threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2)
else:
end_point, start_point, beam_vector, dirVecTrackNorm, track_mean, closest_points = get_directions(cluster_data[:, :3])
track_vector = end_point - start_point
intersection_point = closest_point_on_line1(start_point, track_vector, np.array([0,128,128]), beam_vector)
if plots:
plot_lines(track_mean, dirVecTrackNorm, start_point, end_point, intersection_point, closest_points, ax8, ax9, ax10, color='black', s = 500)
if not useLineModelND:
threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2 = return_threshold_lines(track_mean, dirVecTrackNorm)
plot_threshold_lines(track_mean, dirVecTrackNorm, threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2)
else:
model_params = fitted_models[label].params
threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2 = return_threshold_lines(np.array(model_params[0]), np.array(model_params[1]))
plot_threshold_lines(np.array(model_params[0]), np.array(model_params[1]), threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2)
return lab_angles_initial, intersections_initial, start_point_initial, end_point_initial, phi_angles_initial, ranges_initial, ranges_final
# Function to plot RANSAC threshold lines
def plot_threshold_lines(start_point, direction_vector, threshold_line_above1, threshold_line_below1, threshold_line_above2, threshold_line_below2):
line_start = start_point - 50 * direction_vector
line_end = start_point + 50 * direction_vector
# Threshold line projections for the first perpendicular vector
xy_threshold_above1 = threshold_line_above1[:, [0, 1]]
yz_threshold_above1 = threshold_line_above1[:, [1, 2]]
xz_threshold_above1 = threshold_line_above1[:, [0, 2]]
xy_threshold_below1 = threshold_line_below1[:, [0, 1]]
yz_threshold_below1 = threshold_line_below1[:, [1, 2]]
xz_threshold_below1 = threshold_line_below1[:, [0, 2]]
# Threshold line projections for the second perpendicular vector
xy_threshold_above2 = threshold_line_above2[:, [0, 1]]
yz_threshold_above2 = threshold_line_above2[:, [1, 2]]
xz_threshold_above2 = threshold_line_above2[:, [0, 2]]
xy_threshold_below2 = threshold_line_below2[:, [0, 1]]
yz_threshold_below2 = threshold_line_below2[:, [1, 2]]
xz_threshold_below2 = threshold_line_below2[:, [0, 2]]
ax8.plot([line_start[0], line_end[0]],
[line_start[1], line_end[1]],
linestyle="--")
ax8.plot(xy_threshold_above1[:, 0], xy_threshold_above1[:, 1], 'r--', label='Threshold +5mm')
ax8.plot(xy_threshold_below1[:, 0], xy_threshold_below1[:, 1], 'g--', label='Threshold -5mm')
ax8.plot(xy_threshold_above2[:, 0], xy_threshold_above2[:, 1], 'r--')
ax8.plot(xy_threshold_below2[:, 0], xy_threshold_below2[:, 1], 'g--')
ax9.plot([line_start[1], line_end[1]],
[line_start[2], line_end[2]],
linestyle="--")
ax9.plot(yz_threshold_above1[:, 0], yz_threshold_above1[:, 1], 'r--', label='Threshold +5mm')
ax9.plot(yz_threshold_below1[:, 0], yz_threshold_below1[:, 1], 'g--', label='Threshold -5mm')
ax9.plot(yz_threshold_above2[:, 0], yz_threshold_above2[:, 1], 'r--')
ax9.plot(yz_threshold_below2[:, 0], yz_threshold_below2[:, 1], 'g--')
ax10.plot([line_start[0], line_end[0]],
[line_start[2], line_end[2]],
linestyle="--")
ax10.plot(xz_threshold_above1[:, 0], xz_threshold_above1[:, 1], 'r--', label='Threshold +5mm')
ax10.plot(xz_threshold_below1[:, 0], xz_threshold_below1[:, 1], 'g--', label='Threshold -5mm')
ax10.plot(xz_threshold_above2[:, 0], xz_threshold_above2[:, 1], 'r--')
ax10.plot(xz_threshold_below2[:, 0], xz_threshold_below2[:, 1], 'g--')
plt.draw
# Function to do the GMM Fitting
def fit_gmm_with_bic(data, max_components=10):
"""
Fit Gaussian Mixture Model using BIC to select optimal components.
Parameters:
- data (np.ndarray): Input data array with shape (n_samples, 6) where columns are x, y, z, q, true labels, ransac labels, gmm labels.
- max_components (int): Maximum number of GMM components to evaluate for BIC score.
Returns: