-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils_evaluation.py
More file actions
1731 lines (1287 loc) · 69 KB
/
utils_evaluation.py
File metadata and controls
1731 lines (1287 loc) · 69 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
import numpy as np
import os
import datetime
from skimage.morphology import disk
from scipy import ndimage
from skimage.measure import label
from skimage import morphology
import astropy.io.fits as fits
from astropy import wcs
from astropy.wcs import FITSFixedWarning
import warnings
import sys
from PIL import Image
import json
from pycocotools import coco
warnings.simplefilter('ignore', category=FITSFixedWarning)
from collections import defaultdict
import glob
import copy
from collections import namedtuple
import pandas as pd
from scipy.optimize import linear_sum_assignment
from skimage.segmentation import find_boundaries
from skimage.filters import gaussian
from plantcv import plantcv as pcv
def load_results(path, load_gt=False):
print('Loading results...')
results = np.load(path)
filenames = results['filenames']
pred = results['masks']
if load_gt:
gt = results['gt']
return filenames, pred, gt
else:
return filenames, pred
def post_processing(pred_final, t=0.45, return_labeled=True):
# print('Post-processing...')
images_proc_thresh = pred_final.copy().astype(float)
if return_labeled:
labeled_clusters_connected = np.zeros_like(images_proc_thresh)
# Label the connected components in the binary image (using skimage.clusters label)
for i in range(len(images_proc_thresh)):
# Pre-processing
images_proc_thresh[i] = np.where(images_proc_thresh[i] > t, 1, 0)
images_proc_thresh[i] = morphology.remove_small_objects(images_proc_thresh[i].astype(bool), min_size=64, connectivity=2)
images_proc_thresh[i] = morphology.remove_small_holes(images_proc_thresh[i].astype(bool), area_threshold=50, connectivity=2)
images_proc_thresh[i] = images_proc_thresh[i].astype(float)
if return_labeled:
labeled_clusters_connected[i] = label(images_proc_thresh[i])
if return_labeled:
return images_proc_thresh, labeled_clusters_connected.astype(np.uint8)
else:
return images_proc_thresh
def clean_cme_elongation_tracks(
cme_dictionary,
pa_tolerance=0.1,
dip_thresh_deg=0.5,
dip_thresh_count=3
):
cme_dictionary_final = copy.deepcopy(cme_dictionary)
for cme_key, cme_data in cme_dictionary_final.items():
time_list = cme_data['times']
wcs_list = cme_data['cme_front_wcs']
pixel_list = cme_data['cme_front_pixels']
# Collect elongation data per PA across time
pa_time_series = {}
for t_idx, (time, wcs_data) in enumerate(zip(time_list, wcs_list)):
pa_values, elong_values = wcs_data
for pa, elong in zip(pa_values, elong_values):
# Match to existing PA bin within tolerance
matched = False
for existing_pa in pa_time_series.keys():
if abs(existing_pa - pa) <= pa_tolerance:
pa_time_series[existing_pa].append((t_idx, elong))
matched = True
break
if not matched:
pa_time_series[pa] = [(t_idx, elong)]
# Clean elongation sequences
cleaned_pa_data = {}
for pa, series in pa_time_series.items():
series.sort() # Sort by time index
cleaned_series = []
max_elong = -np.inf
dip_buffer = []
discard_mode = False
for idx, elong in series:
if elong >= max_elong:
if dip_buffer:
# Check dip criteria
max_dip = max(max_elong - e for _, e in dip_buffer)
if len(dip_buffer) <= dip_thresh_count and max_dip <= dip_thresh_deg:
# Interpolate over dip_buffer
cleaned_series.extend(dip_buffer)
# Else: Discard them (do nothing)
dip_buffer = []
max_elong = elong
cleaned_series.append((idx, elong))
else:
dip_buffer.append((idx, elong))
if len(dip_buffer) > dip_thresh_count or (max_elong - elong) > dip_thresh_deg:
# Too deep or too long dip → discard from here
break
cleaned_pa_data[pa] = dict(cleaned_series) # map: time_index → elong
# Rebuild cleaned data
new_wcs_list = []
new_pixel_list = []
for t_idx, (wcs_data, pixel_data) in enumerate(zip(wcs_list, pixel_list)):
pa_values = wcs_data[0]
elong_values = wcs_data[1]
x_values = pixel_data[0]
y_values = pixel_data[1]
cleaned_pa = []
cleaned_elong = []
cleaned_x = []
cleaned_y = []
for pa, elong, x, y in zip(pa_values, elong_values, x_values, y_values):
for cleaned_pa_key, time_elong_map in cleaned_pa_data.items():
if abs(pa - cleaned_pa_key) <= pa_tolerance:
if t_idx in time_elong_map:
cleaned_pa.append(pa)
cleaned_elong.append(elong)
cleaned_x.append(x)
cleaned_y.append(y)
break # matched
# Sort by PA again
sorted_entries = sorted(zip(cleaned_pa, cleaned_elong, cleaned_x, cleaned_y), key=lambda item: item[0])
if sorted_entries:
pa_sorted, elong_sorted, x_sorted, y_sorted = zip(*sorted_entries)
new_wcs_list.append([np.array(pa_sorted), np.array(elong_sorted)])
new_pixel_list.append([np.array(x_sorted), np.array(y_sorted)])
else:
new_wcs_list.append([np.array([]), np.array([])])
new_pixel_list.append([np.array([]), np.array([])])
# Replace data in dictionary
cme_data['cme_front_wcs'] = new_wcs_list
cme_data['cme_front_pixels'] = new_pixel_list
cme_dictionary_final[cme_key] = cme_data
return cme_dictionary_final
def get_fitsfiles(input_days_set, input_dates):
print('Getting fits files...')
rundif_paths = ['/media/DATA_DRIVE/stereo_processed/reduced/data/A/' + day + '/science/hi_1/' for day in input_days_set]
# Import all fts files in ordered list
fts_files = []
for path in rundif_paths:
temp_files = []
for day in input_dates:
temp_files.extend([path + file for file in os.listdir(path) if file.endswith('.fts') and day in file])
fts_files.append(temp_files)
fits_headers = []
for files in fts_files:
for file in files:
with fits.open(file) as hdul:
fits_headers.append(hdul[0].header)
return fits_headers
def get_outline(image_outlines, fits_headers):
print('Getting outline...')
image_outlines_wcs = []
image_outline_pixels = []
for i, cent in enumerate(image_outlines):
current_header = fits_headers[i]
wcoord = wcs.WCS(current_header)
temp_coords = []
temp_pixels = []
for c in cent:
xv, yv = c
thetax, thetay = wcoord.all_pix2world(yv*8, xv*8, 0)
tx = thetax*np.pi/180
ty = thetay*np.pi/180
pa_reg = np.arctan2(-np.cos(ty)*np.sin(tx), np.sin(ty))
elon_reg = np.arctan2(np.sqrt((np.cos(ty)**2)*(np.sin(tx)**2)+(np.sin(ty)**2)), np.cos(ty)*np.cos(tx))
temp_coords.append([pa_reg*180/np.pi, elon_reg*180/np.pi])
temp_pixels.append([xv, yv])
image_outlines_wcs.append(temp_coords)
image_outline_pixels.append(temp_pixels)
return image_outlines_wcs, image_outline_pixels
def order_points(points, ind):
### other solutions for that https://stackoverflow.com/questions/58377015/counterclockwise-sorting-of-x-y-data
points_new = [ points.pop(ind) ] # initialize a new list of points with the known first point
pcurr = points_new[-1] # initialize the current point (as the known point)
while len(points)>0:
d = np.linalg.norm(np.array(points) - np.array(pcurr), axis=1) # distances between pcurr and all other remaining points
ind = d.argmin() # index of the closest point
points_new.append( points.pop(ind) ) # append the closest point to points_new
pcurr = points_new[-1] # update the current point
return points_new
def getwcords_new(header, xv, yv):
wcoord = wcs.WCS(header)
thetax, thetay = wcoord.all_pix2world(yv, xv, 0)
tx = thetax*np.pi/180
ty = thetay*np.pi/180
pa_reg = np.arctan2(-np.cos(ty)*np.sin(tx), np.sin(ty))
elon_reg = np.arctan2(np.sqrt((np.cos(ty)**2)*(np.sin(tx)**2)+(np.sin(ty)**2)), np.cos(ty)*np.cos(tx))
return elon_reg,pa_reg
def getwcords_pix(header, pa_rad, elon_rad):
wcoord = wcs.WCS(header)
tx = np.rad2deg(np.arctan2(-np.sin(elon_rad)*np.sin(pa_rad), np.cos(elon_rad)))
ty = np.rad2deg(np.arcsin(np.sin(elon_rad)*np.cos(pa_rad)))
pix_y_from_img, pix_x_from_img = wcoord.all_world2pix(tx,ty, 0)
return pix_x_from_img,pix_y_from_img
def bin_pa(pas, elongs):
bin_bin = np.linspace(min(pas)-1,max(pas)+1,10)
bins = np.digitize(pas,bin_bin)
A = np.vstack( ( np.digitize(pas,bin_bin), elongs)).T
average = [np.mean(elongs[bins==i]) for i in np.unique(bins)]
return np.deg2rad(bin_bin[np.unique(bins)]),np.deg2rad(average)
def get_front(image_outlines_wcs, image_outline_pixels, fits_headers, image_areas=None):
print('Getting front...')
img_front_wcs = []
img_front_pixels = []
if image_areas is not None:
img_front_areas = []
for out_num, outline in enumerate(image_outlines_wcs):
temp_coords = []
temp_pixels = []
if image_areas is not None:
temp_areas = []
if(len(image_outline_pixels[out_num])>0):
indices = copy.deepcopy(image_outline_pixels[out_num])
for i,idx in enumerate(indices):
img = np.zeros((128,128))
idx_arr = np.array(copy.deepcopy(idx))
if len(idx_arr[0]) == 0:
continue
img[idx_arr[0,:],idx_arr[1,:]] = 1.0
points = [(xx,yy) for xx,yy in zip(idx_arr[0,:],idx_arr[1,:])]
area = copy.deepcopy(image_areas[out_num][i])
header = copy.deepcopy(fits_headers[out_num])
if(len(points)>3):
skeleton = morphology.skeletonize(area)
pruned_skeleton, _, _ = pcv.morphology.prune(skel_img=skeleton.astype(np.uint8), size=10)
pruned_coordinates = np.where(pruned_skeleton == 1)
skeleton_x = pruned_coordinates[0]
skeleton_y = pruned_coordinates[1]
elongs_skeleton, pas_skeleton = getwcords_new(header, skeleton_x*8, skeleton_y*8)
center_pa_skeleton_deg = np.rad2deg(pas_skeleton)
center_elong_skeleton_deg = np.rad2deg(elongs_skeleton)
temp_coords.append([center_pa_skeleton_deg, center_elong_skeleton_deg])
temp_pixels.append([np.clip(np.round(skeleton_x,0),0,127).astype(np.uint32), np.clip(np.round(skeleton_y,0),0,127).astype(np.uint32)])
if image_areas is not None:
temp_areas.append(area)
img_front_wcs.append(temp_coords)
img_front_pixels.append(temp_pixels)
if image_areas is not None:
img_front_areas.append(temp_areas)
if image_areas is not None:
return img_front_wcs, img_front_pixels, img_front_areas
else:
return img_front_wcs, img_front_pixels
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # Path compression
return self.parent[x]
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
self.parent[root_y] = root_x
def aggregate_fronts_sequential(fronts, fronts_pixels, max_diff_elon=3, areas=None):
n = len(fronts)
if n <= 1:
if areas is not None:
return fronts, fronts_pixels, areas
else:
return fronts, fronts_pixels
max_elons = [np.max(f[1]) if len(f[1]) > 0 else -999 for f in fronts]
sorted_indices = np.argsort(max_elons)[::-1] # Descending order
used = set()
discarded = set()
groups = []
for i in sorted_indices:
if i in used or i in discarded:
continue
if len(fronts[i][1]) == 0:
# print(f"Front {i} has no elongation data, skipping.")
discarded.add(i)
continue
# Start a new group with front i
group = [i]
used.add(i)
# Aggregate data for matching
combined_elon = fronts[i][1].copy()
combined_pa = fronts[i][0].copy()
changed = True
while changed:
changed = False
for j in range(n):
if j in used or j in discarded:
continue
if len(fronts[j][1]) == 0:
# print(f"Front {j} has no elongation data, skipping.")
discarded.add(j)
continue
# diff = np.abs(np.max(fronts[j][1]) - np.max(combined_elon))
diff = np.abs(np.mean(fronts[j][1]) - np.mean(combined_elon))
if diff <= max_diff_elon:
# Add to group
group.append(j)
used.add(j)
combined_elon = np.concatenate((combined_elon, fronts[j][1]))
combined_pa = np.concatenate((combined_pa, fronts[j][0]))
changed = True
groups.append(group)
# Now build the aggregated outputs
img_fronts_agg = []
img_fronts_pixels_agg = []
img_fronts_areas_agg = [] if areas is not None else None
for group in groups:
elon_group = []
pa_group = []
x_pix_group = []
y_pix_group = []
areas_group = []
for idx in group:
elon_group.append(fronts[idx][1])
pa_group.append(fronts[idx][0])
x_pix_group.append(fronts_pixels[idx][0])
y_pix_group.append(fronts_pixels[idx][1])
if areas is not None:
areas_group.append(areas[idx])
elon_group = np.concatenate(elon_group)
pa_group = np.concatenate(pa_group)
x_pix_group = np.concatenate(x_pix_group)
y_pix_group = np.concatenate(y_pix_group)
# Keep only largest elongation per PA
keep_indices = []
unique_pas = np.unique(pa_group)
for pa in unique_pas:
indices = np.where(pa_group == pa)[0]
if len(indices) == 1:
keep_indices.append(indices[0])
else:
max_idx = indices[np.argmax(elon_group[indices])]
keep_indices.append(max_idx)
keep_indices = np.array(keep_indices)
elon_group = elon_group[keep_indices]
pa_group = pa_group[keep_indices]
x_pix_group = x_pix_group[keep_indices]
y_pix_group = y_pix_group[keep_indices]
# Sort by PA
sort_idx = np.argsort(pa_group)
elon_group = elon_group[sort_idx]
pa_group = pa_group[sort_idx]
x_pix_group = x_pix_group[sort_idx]
y_pix_group = y_pix_group[sort_idx]
img_fronts_agg.append([pa_group, elon_group])
img_fronts_pixels_agg.append([x_pix_group, y_pix_group])
if areas is not None:
total_area = np.sum(areas_group, axis=0)
img_fronts_areas_agg.append(total_area)
if areas is not None:
return img_fronts_agg, img_fronts_pixels_agg, img_fronts_areas_agg
else:
return img_fronts_agg, img_fronts_pixels_agg
def aggregate_fronts(fronts, fronts_pixels, max_diff_elon=3, areas=None):
"""
Groups CME fronts that likely belong to the same CME.
Args:
fronts (list of arrays): List of CME fronts. Each front is an Nx2 array of (elongation, PA) coordinates.
fronts_pixels (list of arrays): List of pixel coordinates corresponding to the CME fronts.
max_diff (float): Maximum allowed difference in mean elongation for association.
areas (list of arrays): List of areas corresponding to the CME fronts (optional).
Returns:
list of lists: Grouped fronts, where each group is a list of original front indices.
"""
n = len(fronts)
if n <= 1:
# return [[i] for i in range(n)] # No aggregation needed
if areas != None:
return fronts,fronts_pixels,areas # No aggregation needed
else:
return fronts,fronts_pixels
mean_elongations = [np.mean(front[1]) for front in fronts]
uf = UnionFind(n)
for i in range(n):
diffs = []
for j in range(n):
if i == j: # Don't take difference between front and itself
continue
diff_elon = abs(mean_elongations[i] - mean_elongations[j])
if diff_elon >= max_diff_elon:
continue # No point checking PA overlap if elongation is too different
diffs.append((j, diff_elon))
# # Compute PA overlap
# pa_i = set(fronts[i][0])
# pa_j = set(fronts[j][0])
# overlap = len(pa_i & pa_j)
# pa_overlap_ratio = overlap / min(len(pa_i), len(pa_j))
# if pa_overlap_ratio <= max_overlap_pa:
# diffs.append((j, diff_elon))
# Find the one with the minimum difference
if diffs:
best_match = min(diffs, key=lambda x: x[1])[0]
uf.union(i, best_match)
# Group by root parent
groups = {}
for i in range(n):
root = uf.find(i)
if root not in groups:
groups[root] = []
groups[root].append(i)
agg_groups = list(groups.values())
img_fronts_agg = [[]]*len(agg_groups)
img_fronts_pixels_agg = [[]]*len(agg_groups)
if areas != None:
img_fronts_areas_agg = [[]]*len(agg_groups)
for group_id,group in enumerate(agg_groups):
elon_group = []
pa_group = []
x_pix_group = []
y_pix_group = []
if areas != None:
areas_group = []
for index in group:
elon_group.append(fronts[index][1])
pa_group.append(fronts[index][0])
x_pix_group.append(fronts_pixels[index][0])
y_pix_group.append(fronts_pixels[index][1])
if areas != None:
areas_group.append(areas[index])
elon_group = np.concatenate(elon_group)
pa_group = np.concatenate(pa_group)
x_pix_group = np.concatenate(x_pix_group)
y_pix_group = np.concatenate(y_pix_group)
# Create a mask that keeps only the largest elongation per PA
keep_indices = []
unique_pas = np.unique(pa_group)
for pa in unique_pas:
indices = np.where(pa_group == pa)[0]
if len(indices) == 1:
keep_indices.append(indices[0])
else:
# Pick index of max elongation
max_idx = indices[np.argmax(elon_group[indices])]
keep_indices.append(max_idx)
# Apply the mask to both WCS and pixel data
keep_indices = np.array(keep_indices)
pa_group = pa_group[keep_indices]
elon_group = elon_group[keep_indices]
x_pix_group = x_pix_group[keep_indices]
y_pix_group = y_pix_group[keep_indices]
if areas != None:
areas_group = np.sum(areas_group,axis=0)
elon_group = np.array([y for (y,x) in sorted(zip(elon_group,pa_group), key=lambda pair: pair[1])])
x_pix_group = np.array([y for (y,x) in sorted(zip(x_pix_group,pa_group), key=lambda pair: pair[1])])
y_pix_group = np.array([y for (y,x) in sorted(zip(y_pix_group,pa_group), key=lambda pair: pair[1])])
pa_group = np.array(sorted(pa_group))
img_fronts_agg[group_id] = [pa_group, elon_group]
img_fronts_pixels_agg[group_id] = [x_pix_group, y_pix_group]
if areas != None:
img_fronts_areas_agg[group_id] = areas_group
if areas != None:
return img_fronts_agg, img_fronts_pixels_agg, img_fronts_areas_agg
else:
return img_fronts_agg, img_fronts_pixels_agg
def identify_new_cme(associated_fronts, threshold_elon=8):
"""
Identifies which CME fronts could be the start of a new CME based on mean elongation.
Args:
associated_fronts (list): List of fronts (each a [PA, elongation] 2-array).
threshold_elon (float): Maximum mean elongation for a front to be flagged as a potential new CME.
Returns:
list: Binary flags (1 = could be new CME, 0 = not) for each front.
"""
flags = []
for front in associated_fronts:
pa, elon = front
mean_elon = np.mean(elon)
if mean_elon < threshold_elon:
flags.append(1)
else:
flags.append(0)
return flags
def connect_cmes_new(input_imgs, input_dates, img_front_wcs, img_front_pixels, input_dates_obs, labeled_areas=None, max_time_gap=140, max_start_elon=7.3, min_elon_end=12.9, elon_diff_thresholds=[-3.2,6.7], min_total_duration=None):
previous_date = input_dates[0]
previous_fronts = []
cme_counter = -1
cme_dictionary = {}
previous_cme_keys = [] # tracks which CME string each previous front belongs to
for idx in range(len(input_imgs)):
matched_previous_fronts = []
current_date = input_dates[idx]
delta_t = (current_date - previous_date).total_seconds()/60
skip_val = 0
for frnt in img_front_wcs[idx]:
if len(frnt[0]) == 0 or len(frnt[1]) == 0:
skip_val += 1
if skip_val == len(img_front_wcs[idx]):
print(f"Skipping {current_date} due to no fronts detected")
continue
if labeled_areas != None:
current_fronts, current_fronts_pix, current_areas = aggregate_fronts(img_front_wcs[idx], img_front_pixels[idx], max_diff_elon=3, areas=labeled_areas[idx])
else:
current_fronts, current_fronts_pix = aggregate_fronts(img_front_wcs[idx], img_front_pixels[idx], max_diff_elon=3)
new_cme_flag = identify_new_cme(current_fronts, threshold_elon=max_start_elon)
current_cme_keys = []
#print('delta_t', delta_t)
if len(current_fronts) > 0 and len(previous_fronts) > 0 and delta_t < max_time_gap:
#print(f"CME continues from {previous_date} to {current_date}")
elongation_differences = [[] for _ in range(len(current_fronts))]
for i, current in enumerate(current_fronts):
pa_current, elon_current = current
pa_current = np.round(pa_current).astype(int)
elon_current = np.array(elon_current)
for j, previous in enumerate(previous_fronts):
pa_previous, elon_previous = previous
pa_previous = np.round(pa_previous).astype(int)
elon_previous = np.array(elon_previous)
# Build common PA grid
all_pas = np.union1d(pa_current, pa_previous)
elon_current_grid = np.full_like(all_pas, np.nan, dtype=np.float32)
elon_previous_grid = np.full_like(all_pas, np.nan, dtype=np.float32)
current_map = dict(zip(pa_current, elon_current))
previous_map = dict(zip(pa_previous, elon_previous))
for k, pa in enumerate(all_pas):
if pa in current_map:
elon_current_grid[k] = current_map[pa]
if pa in previous_map:
elon_previous_grid[k] = previous_map[pa]
shared_mask = ~np.isnan(elon_current_grid) & ~np.isnan(elon_previous_grid)
if np.any(shared_mask):
diff_vector = elon_current_grid[shared_mask] - elon_previous_grid[shared_mask]
mean_diff = np.mean(diff_vector)
abs_mean_diff = np.mean(np.abs(diff_vector))
weight = np.sum(shared_mask) / len(all_pas)
weighted_diff = abs_mean_diff * (1 - weight)
if elon_diff_thresholds[0] <= mean_diff <= elon_diff_thresholds[1]:
elongation_differences[i].append((j, weighted_diff))
best_matches = []
for diffs in elongation_differences:
if diffs:
best_match = min(diffs, key=lambda x: x[1]) # minimum absolute mean difference
best_matches.append(best_match[0])
else:
best_matches.append(None)
for i, match in enumerate(best_matches):
if match is not None:
#print(f"Front {i} continues")
cme_key = previous_cme_keys[match]
cme_dictionary[cme_key]['cme_front_wcs'].append(current_fronts[i])
cme_dictionary[cme_key]['cme_front_pixels'].append(current_fronts_pix[i])
cme_dictionary[cme_key]['times'].append(input_dates[idx])
cme_dictionary[cme_key]['times_obs'].append(input_dates_obs[idx])
if labeled_areas != None:
cme_dictionary[cme_key]['areas'].append(current_areas[i])
current_cme_keys.append(cme_key)
matched_previous_fronts.append(current_fronts[i])
elif new_cme_flag[i] == 1:
#print(f"Front {i} is a new CME")
cme_counter += 1
new_key = f"CME_{cme_counter}"
if labeled_areas != None:
cme_dictionary[new_key] = {
'cme_front_wcs': [current_fronts[i]],
'cme_front_pixels': [current_fronts_pix[i]],
'times': [input_dates[idx]],
'times_obs': [input_dates_obs[idx]],
'areas': [current_areas[i]]
}
else:
cme_dictionary[new_key] = {
'cme_front_wcs': [current_fronts[i]],
'cme_front_pixels': [current_fronts_pix[i]],
'times': [input_dates[idx]],
'times_obs': [input_dates_obs[idx]]
}
current_cme_keys.append(new_key)
matched_previous_fronts.append(current_fronts[i])
previous_date = current_date
previous_fronts = matched_previous_fronts.copy()
previous_cme_keys = current_cme_keys
elif len(previous_fronts) == 0:
#print(f'New sequence at {current_date}')
for i in range(len(current_fronts)):
if new_cme_flag[i] == 1:
#print(f'Front {i} is new CME')
cme_counter += 1
new_key = f"CME_{cme_counter}"
if labeled_areas != None:
cme_dictionary[new_key] = {
'cme_front_wcs': [current_fronts[i]],
'cme_front_pixels': [current_fronts_pix[i]],
'times': [input_dates[idx]],
'times_obs': [input_dates_obs[idx]],
'areas': [current_areas[i]]
}
else:
cme_dictionary[new_key] = {
'cme_front_wcs': [current_fronts[i]],
'cme_front_pixels': [current_fronts_pix[i]],
'times': [input_dates[idx]],
'times_obs': [input_dates_obs[idx]]
}
current_cme_keys.append(new_key)
matched_previous_fronts.append(current_fronts[i])
previous_date = current_date
previous_fronts = matched_previous_fronts.copy()
previous_cme_keys = current_cme_keys
else:
previous_date = current_date
previous_fronts = []
current_fronts = []
previous_cme_keys = []
if min_total_duration is not None:
for entry in list(cme_dictionary):
time_beginning = sorted(list(set(cme_dictionary[entry]['times'])))[0]
time_end = sorted(list(set(cme_dictionary[entry]['times'])))[-1]
time_diff = (time_end - time_beginning).total_seconds()/3600 # total duration of CME in hours
if time_diff < min_total_duration:
del cme_dictionary[entry]
for entry in list(cme_dictionary):
if np.nanmax(cme_dictionary[entry]['cme_front_wcs'][-1][1]) < min_elon_end: #if maximum elongation reached is below threshold
del cme_dictionary[entry]
# Merge duplicate timestep entries
for cme_key, cme_data in cme_dictionary.items():
merged_data = defaultdict(lambda: {'wcs': [], 'pixels': [], 'areas': []})
for i, time in enumerate(cme_data['times']):
merged_data[time]['wcs'].append(cme_data['cme_front_wcs'][i])
merged_data[time]['pixels'].append(cme_data['cme_front_pixels'][i])
if 'areas' in cme_data:
merged_data[time]['areas'].append(cme_data['areas'][i])
# Sort times
sorted_times = sorted(merged_data.keys())
cme_data['times'] = sorted_times
cme_data['times_obs'] = [cme_data['times_obs'][cme_data['times'].index(t)] for t in sorted_times]
cme_data['cme_front_wcs'] = []
cme_data['cme_front_pixels'] = []
if 'areas' in cme_data:
cme_data['areas'] = []
for t in sorted_times:
cme_data['cme_front_wcs'].append(np.concatenate(merged_data[t]['wcs'], axis=1))
cme_data['cme_front_pixels'].append(np.concatenate(merged_data[t]['pixels'], axis=1))
if 'areas' in cme_data:
cme_data['areas'].append(np.sum(merged_data[t]['areas'], axis=0))
# Sort by PA value
for cme_key, cme_data in cme_dictionary.items():
for i, time in enumerate(cme_data['times']):
# Extract current WCS and pixel data
wcs_data = cme_data['cme_front_wcs'][i]
pixel_data = cme_data['cme_front_pixels'][i]
# Shape is (2, N) with [PA, elongation]
pa_values = wcs_data[0]
elongations = wcs_data[1]
x_pix_values = pixel_data[0]
y_pix_values = pixel_data[1]
elongations = np.array([e for _, e in sorted(zip(pa_values, elongations), key=lambda pair: pair[0])])
x_pix_values = np.array([x for _, x in sorted(zip(pa_values, x_pix_values), key=lambda pair: pair[0])])
y_pix_values = np.array([y for _, y in sorted(zip(pa_values, y_pix_values), key=lambda pair: pair[0])])
pa_values = np.array(sorted(pa_values))
wcs_data = [pa_values,elongations]
pixel_data = [x_pix_values, y_pix_values]
cme_data['cme_front_wcs'][i] = wcs_data
cme_data['cme_front_pixels'][i] = pixel_data
cme_names = np.array(['CME_' + str(i) for i in range(len(cme_dictionary))])
cme_dictionary_clean = {}
for i, entry in enumerate(list(cme_dictionary)):
cme_dictionary_clean[cme_names[i]] = cme_dictionary[entry].copy()
return cme_dictionary_clean
def remove_outliers_from_fronts(img_front_wcs, img_fronts_pixels, fits_headers, image_areas=None, window=3, threshold=1.5):
cleaned_fronts = []
cleaned_fronts_pixels = []
if image_areas is not None:
cleaned_fronts_areas = []
for img_idx, img_fronts in enumerate(img_front_wcs):
cleaned_img = []
cleaned_pixels = []
if image_areas is not None:
cleaned_areas = []
wcoord = wcs.WCS(fits_headers[img_idx])
for front_idx, front in enumerate(img_fronts):
pa_array, elon_array = front
pixel_x_array = np.array(img_fronts_pixels[img_idx][front_idx])[0]
pixel_y_array = np.array(img_fronts_pixels[img_idx][front_idx])[1]
pa_array = np.round(pa_array).astype(int)
elon_array = np.array(elon_array, dtype=np.float32)
if len(pa_array) < 6:
# Not enough data to apply outlier detection
cleaned_img.append(np.array([pa_array, elon_array]))
cleaned_pixels.append(np.array([pixel_x_array, pixel_y_array]))
if image_areas is not None:
cleaned_areas.append(image_areas[img_idx][front_idx])
continue
cleaned_elon = elon_array.copy()
outlier_mask = np.zeros_like(elon_array, dtype=bool)
cleaned_pix_arr = np.array([pixel_x_array, pixel_y_array])
for i, pa in enumerate(pa_array):
# Look for surrounding PAs within ±window
surrounding_values_left = []
surrounding_values_right = []
for offset in range(1, window + 1):
neighbor_pa_left = pa - offset
neighbor_pa_right = pa + offset
if neighbor_pa_left in pa_array:
idx_left = np.where(pa_array == neighbor_pa_left)[0][0]
surrounding_values_left.append(elon_array[idx_left])
if neighbor_pa_right in pa_array:
idx_right = np.where(pa_array == neighbor_pa_right)[0][0]
surrounding_values_right.append(elon_array[idx_right])
if len(surrounding_values_left) >= 2 and len(surrounding_values_right) >= 2:
surrounding_mean_left = np.nanmean(surrounding_values_left)
surrounding_mean_right = np.nanmean(surrounding_values_right)
diff_left = np.abs(elon_array[i] - surrounding_mean_left)
diff_right = np.abs(elon_array[i] - surrounding_mean_right)
if diff_left > threshold and diff_right > threshold:
outlier_mask[i] = True
elif len(surrounding_values_left) >= 2:
surrounding_mean_left = np.nanmean(surrounding_values_left)
diff_left = np.abs(elon_array[i] - surrounding_mean_left)
if diff_left > threshold:
outlier_mask[i] = True
elif len(surrounding_values_right) >= 2:
surrounding_mean_right = np.nanmean(surrounding_values_right)
diff_right = np.abs(elon_array[i] - surrounding_mean_right)
if diff_right > threshold:
outlier_mask[i] = True
# Interpolate over outliers
if np.any(outlier_mask):
good_idx = ~outlier_mask
if np.any(good_idx):
cleaned_elon[outlier_mask] = np.interp(
pa_array[outlier_mask],
pa_array[good_idx],
elon_array[good_idx]
)
cleaned_elon_rad = np.deg2rad(cleaned_elon)
pa_array_rad = np.deg2rad(pa_array)
tx = np.rad2deg(np.arctan2(-np.sin(cleaned_elon_rad)*np.sin(pa_array_rad), np.cos(cleaned_elon_rad)))
ty = np.rad2deg(np.arcsin(np.sin(cleaned_elon_rad)*np.cos(pa_array_rad)))
pix_y, pix_x = wcoord.all_world2pix(tx,ty, 0)
if np.any(np.round(pix_x/8,0).astype(int) > 128):
for remove_ind in reversed(np.where(np.round(pix_x/8,0).astype(int) > 128)[0]):
pa_array = np.delete(pa_array, remove_ind)
elon_array = np.delete(elon_array, remove_ind)
cleaned_elon = np.delete(cleaned_elon, remove_ind)
pix_y = np.delete(pix_y, remove_ind)
pix_x = np.delete(pix_x, remove_ind)
if np.any(np.round(pix_x/8,0).astype(int) < 0):
for remove_ind in reversed(np.where(np.round(pix_x/8,0).astype(int) < 0)[0]):
pa_array = np.delete(pa_array, remove_ind)
elon_array = np.delete(elon_array, remove_ind)
cleaned_elon = np.delete(cleaned_elon, remove_ind)
pix_y = np.delete(pix_y, remove_ind)
pix_x = np.delete(pix_x, remove_ind)
if np.any(np.round(pix_y/8,0).astype(int) > 128):
for remove_ind in reversed(np.where(np.round(pix_y/8,0).astype(int) > 128)[0]):
pa_array = np.delete(pa_array, remove_ind)
elon_array = np.delete(elon_array, remove_ind)
cleaned_elon = np.delete(cleaned_elon, remove_ind)
pix_y = np.delete(pix_y, remove_ind)
pix_x = np.delete(pix_x, remove_ind)
if np.any(np.round(pix_y/8,0).astype(int) < 0):
for remove_ind in reversed(np.where(np.round(pix_y/8,0).astype(int) < 0)[0]):
pa_array = np.delete(pa_array, remove_ind)
elon_array = np.delete(elon_array, remove_ind)
cleaned_elon = np.delete(cleaned_elon, remove_ind)
pix_y = np.delete(pix_y, remove_ind)
pix_x = np.delete(pix_x, remove_ind)
cleaned_pix_arr = np.array([np.round(pix_x/8,0).astype(int), np.round(pix_y/8,0).astype(int)])
else:
# All points in the front are considered outliers, discard front
continue
cleaned_pixels.append(np.array(cleaned_pix_arr))
cleaned_img.append(np.array([pa_array, cleaned_elon]))