-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalizer.py
More file actions
1908 lines (1424 loc) · 74.9 KB
/
Copy pathnormalizer.py
File metadata and controls
1908 lines (1424 loc) · 74.9 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QTableWidget, QTableWidgetItem, QVBoxLayout, QAction
from PyQt5.QtCore import QFile, QIODevice, QObject, Qt, QSortFilterProxyModel, QDir, QCoreApplication, QEvent
from PyQt5.uic import loadUi
from PyQt5.QtGui import QFont, QClipboard, QKeySequence
import numpy as np
from numpy import inf, nan
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import os,sys
import warnings
import ast
mpl.rcParams['text.usetex'] = False
import astropy
from astropy.io import fits
from astropy.wcs import WCS
from astropy import units as u
from astropy.modeling import models, fitting
from astropy.utils.exceptions import AstropyWarning
from PyAstronomy import pyasl
from scipy.interpolate import UnivariateSpline, InterpolatedUnivariateSpline, LSQUnivariateSpline, interp1d
from scipy.signal import correlate
from scipy.optimize import curve_fit
from scipy.stats import norm
from mask_peaks import PeakMask
from exp_mask import exp_mask
from plotwindow import PlotWindow
from about import AboutWin
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
# TableWidget event filter function
def table_key_press_event_filter(obj, event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Delete:
# Get all selected items
selectedItems = obj.selectedItems()
# Clear the content of each selected item
for item in selectedItems:
item.setText('') # Set the text of the item to an empty string
return True # Indicate that the event has been handled
elif event.type() == QEvent.KeyPress and event.matches(QKeySequence.Copy):
selected_ranges = obj.selectedRanges()
if not selected_ranges:
return
table_data = []
for selected_range in selected_ranges:
for row in range(selected_range.topRow(), selected_range.bottomRow() + 1):
row_data = []
for col in range(selected_range.leftColumn(), selected_range.rightColumn() + 1):
item = obj.item(row, col)
row_data.append(item.text() if item else '')
table_data.append('\t'.join(row_data))
# Convert the selected table data to a string
table_string = '\n'.join(table_data)
# Copy the table data to the clipboard
clipboard = QApplication.clipboard()
clipboard.setText(table_string)
return True
elif event.type() == QEvent.KeyPress and event.matches(QKeySequence.Paste):
# Handle pasting clipboard data into the table
clipboard = QApplication.clipboard()
clipboard_text = clipboard.text()
if clipboard_text:
selected_ranges = obj.selectedRanges()
if selected_ranges:
# Start pasting at the top-left corner of the selected range
top_left_row = selected_ranges[0].topRow()
top_left_col = selected_ranges[0].leftColumn()
# Split clipboard data into rows and columns
rows = clipboard_text.split('\n')
for i, row_data in enumerate(rows):
columns = row_data.split('\t')
for j, text in enumerate(columns):
target_row = top_left_row + i
target_col = top_left_col + j
if target_row < obj.rowCount() and target_col < obj.columnCount():
item = obj.item(target_row, target_col)
if not item:
item = QTableWidgetItem()
obj.setItem(target_row, target_col, item)
item.setText(text)
return True # Indicate that the event has been handled
return False # Pass other events to the base class
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
class start(QMainWindow):
def __init__(self, ui_file, parent=None):
""" Initialize main window for user interactions
"""
super(start, self).__init__(parent)
self.gui = self # this has historic reasons....
loadUi(ui_file, self.gui)
if not self.gui:
print(loader.errorString())
sys.exit(-1)
# Create the menu bar
menubar = self.gui.menuBar()
menubar.setNativeMenuBar(True)
# Create 'File' menu and add actions
fileMenu = menubar.addMenu('&File')
saveAction = QAction('&Save as...', self)
exitAction = QAction('&Exit', self)
saveAction.triggered.connect(lambda: self.saveFile(showfiledialogue=True))
exitAction.triggered.connect(self.close)
fileMenu.addAction(saveAction)
fileMenu.addAction(exitAction)
# Create 'Help' menu and add actions
helpMenu = menubar.addMenu('&Help')
aboutAction = QAction('&About', self)
aboutAction.triggered.connect(self.showAboutDialog)
helpMenu.addAction(aboutAction)
self.gui.label_8.setHidden(True)
self.gui.lineEdit_interior_knots.setHidden(True)
self.gui.label_4.setHidden(True)
self.gui.lineEdit_fixed_width.setHidden(True)
self.gui.show()
# figure with 2 subplots
self.plotwindow = PlotWindow()
self.plotwindow.custom_toolbar.slicePressed.connect(self.on_slice_pressed)
self.plotwindow.custom_toolbar.resetPressed.connect(self.on_reset_pressed)
self.plotwindow.custom_toolbar.homePressed.connect(self.on_home_pressed)
self.plotwindow.custom_toolbar.rectangleSelected.connect(self.on_coordinates_selected)
self.gui.fig = self.plotwindow.figure # Use the Figure from PlotWindow
self.gui.ax = self.plotwindow.ax # Use the Axes from PlotWindow
# set standard values
self.gui.method='Polynomial'
self.gui.lineEdit_degree.setText('0')
self.gui.lineEdit_smooth.setText('200')
self.gui.label_2.setVisible(False)
self.gui.lineEdit_smooth.setVisible(False)
self.gui.label_9.setVisible(False)
self.gui.lineEdit_fixpoints.setVisible(False)
self.gui.lineEdit_sigma_high.setText('5.0')
self.gui.lineEdit_sigma_low.setText('2.5')
self.gui.lineEdit_fixed_width.setText('10')
self.gui.lineEdit_interior_knots.setText('200')
self.gui.lineEdit_offset.setText('1.0')
self.gui.lineEdit_auto_velocity_shift.setText('0.0')
self.gui.lineEdit_auto_velocity_shift_lim1.setText('-400')
self.gui.lineEdit_auto_velocity_shift_lim2.setText('400')
self.gui.lineEdit_auto_velocity_shift_lim1.setReadOnly(True)
self.gui.lineEdit_auto_velocity_shift_lim2.setReadOnly(True)
self.vradshift_aa = []
self.vradshift_kms = 0.0
self.vradshift_applied = False
self.snr = None
self.rms = None
self.renorm_factor_autovalue = 1.0
self.gui.x=np.array([]) # origianl wavelength range
self.gui.y=np.array([]) # original spectrum
self.gui.xzoom=np.array([]) # zoomed-in wavelength range
self.gui.yzoom=np.array([]) # zoomed-in original spectrum
self.gui.yi=np.array([]) # smoothed, masked and interpolated spectrum used for normalisation (continuum fitting)
self.gui.ynorm=np.array([]) # normalized array
self.gui.xcurrent=np.array([])
self.gui.ycurrent=np.array([]) # figure 0
self.gui.ynormcurrent=np.array([]) # figure 1
self.gui.ymaskedcurrent=np.array([])
self.gui.mask=np.array([])
self.gui.telluricmask=np.array([])
self.mask_history = [] # keep mask history for undo function
self.userpath = os.getcwd()
self.gui.xlim_l_last=0
self.gui.xlim_h_last=0
# Identify the layout that contains the main parts, including the tableWidget
layout = self.gui.horizontalLayout_main
# Hide button to apply velo shift
self.gui.pushButton_shift_spectrum.setVisible(True)
self.gui.lineEdit_auto_velocity_shift.setVisible(True)
# adjust table row height
table = self.gui.tableWidget
for i in range(table.rowCount()):
table.setRowHeight(i, 20) # Set each row's height to 40 pixels
font = QFont()
font.setPointSize(10) # Set the font size to 10 points for table
# Apply the font to the table
table.setFont(font)
# Install the event filter for the table
self.gui.tableWidget.installEventFilter(self)
self.c = 299792.458 # speed of light in km/s
def closeEvent(self, event):
# Close the plotwindow when the main window is about to close
self.plotwindow.close()
def showAboutDialog(self):
# Create and show the About dialog
dialog = AboutWin(self)
dialog.exec_() # Show the dialog modally
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def eventFilter(self, obj, event):
if obj == self.tableWidget:
return table_key_press_event_filter(obj, event)
return super().eventFilter(obj, event)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def on_coordinates_selected(self, x0, y0, x1, y1, flagtype):
#print(f"Coordinates selected: ({x0}, {y0}) to ({x1}, {y1})")
tellurics = self.gui.lineEdit_telluric.text()
x0_user = round(x0,3)
x1_user = round(x1,3)
if x0_user > x1_user:
x0 = x1_user
x1 = x0_user
else:
x0 = x0_user
x1 = x1_user
if flagtype=='BAD':
self.mask_history.append(np.copy(self.gui.mask))
tellurics_lambda_corrfactor = self.calc_tellurics_lambda_corrfactor()
self.gui.lineEdit_telluric.setText(f"{tellurics}, ({x0/tellurics_lambda_corrfactor},{x1/tellurics_lambda_corrfactor})")
elif flagtype=='LINE':
self.mask_history.append(np.copy(self.gui.mask))
linewidth = round(0.5*(x1-x0),3)
linecenter = round(x0 + linewidth,3)
self.add_values_to_first_empty_row(self.gui.tableWidget, [linecenter, linewidth])
elif flagtype == 'UNFLAG':
self.mask_history.append(np.copy(self.gui.mask))
# Unflag line flags:
table = self.gui.tableWidget
rowCount = table.rowCount()
# List to store rows to remove and new rows to add
rows_to_remove = []
rows_to_add = []
# Iterate through the rows in reverse order
for row in range(rowCount -1, -1, -1): # Start from the last row
# Retrieve the value from the first and second columns of the current row
item_center = table.item(row, 0) # Center value in column 0
item_width = table.item(row, 1) # Width value in column 1
# Skip if either item is empty or invalid
if not item_center or not item_width:
continue
try:
center_value = float(item_center.text())
width_value = float(item_width.text())
except ValueError:
# Skip rows with non-numeric data
continue
center_value = float(item_center.text())
width_value = float(item_width.text())
# Calculate the range
range_start = center_value - width_value
range_end = center_value + width_value
# Check for overlap with the user's selection [x0, x1]
if x0 <= range_start and x1 >= range_end:
# Case 0: Remove the entire range
rows_to_remove.append(row)
elif x0 > range_start and x1 < range_end:
# Case 1: Exclude from the middle part of the existing range
rows_to_remove.append(row)
# Add the left part
new_width_left = (x0 - range_start) / 2.0
new_center_left = range_start + new_width_left
rows_to_add.append((row, new_center_left, new_width_left))
# Add the right part
new_width_right = (range_end - x1) / 2.0
new_center_right = x1 + new_width_right
rows_to_add.append((row + 1, new_center_right, new_width_right))
elif x1 > range_end and x0 > range_start and x0 < range_end:
# Case 2: Remove the right part of the range
rows_to_remove.append(row)
new_width = (x0 - range_start) / 2.0
new_center = range_start + new_width
rows_to_add.append((row, new_center, new_width))
elif x0 < range_start and x1 < range_end and x1 > range_start:
# Case 3: Remove the left part of the range
rows_to_remove.append(row)
new_width = (range_end - x1) / 2.0
new_center = x1 + new_width
rows_to_add.append((row, new_center, new_width))
# Remove the rows after processing
for row in rows_to_remove:
table.removeRow(row)
# Now add the new rows
for row, center, width in rows_to_add:
table.insertRow(row)
table.setItem(row, 0, QTableWidgetItem(str(round(center, 3))))
table.setItem(row, 1, QTableWidgetItem(str(round(width, 3))))
# unflag tellurics
# Parse the intervals from the telluric line edit
# and shift to the observed scale
if self.gui.lineEdit_telluric.text().strip().strip(',') != '' and len(self.gui.lineEdit_telluric.text().strip().strip(','))>0:
telluric_intervals = ast.literal_eval(self.gui.lineEdit_telluric.text().strip().strip(','))
tellurics_lambda_corrfactor = self.calc_tellurics_lambda_corrfactor()
if self.is_iterable(telluric_intervals[0]):
telluric_intervals = [(a * tellurics_lambda_corrfactor, b * tellurics_lambda_corrfactor) for a, b in telluric_intervals]
else:
telluric_intervals = self.fix_telluric_intervals_notalist(telluric_intervals)
# Filter and adjust the intervals based on the user selection
updated_intervals = []
for a, b in telluric_intervals:
if b <= x0 or a >= x1:
# Interval is completely outside user selection, keep it as is
updated_intervals.append((a/tellurics_lambda_corrfactor, b/tellurics_lambda_corrfactor))
elif a < x0 and b > x1:
# User selection is completely within the interval, split it into two
updated_intervals.append((a/tellurics_lambda_corrfactor, x0/tellurics_lambda_corrfactor))
updated_intervals.append((x1/tellurics_lambda_corrfactor, b/tellurics_lambda_corrfactor))
elif a < x0 <= b:
# Only the upper part of the interval overlaps with user selection
updated_intervals.append((a/tellurics_lambda_corrfactor, x0/tellurics_lambda_corrfactor))
elif a >= x0 and b > x1:
# Only the lower part of the interval overlaps with user selection
updated_intervals.append((x1/tellurics_lambda_corrfactor, b/tellurics_lambda_corrfactor))
# If the interval is entirely within the user selection, it gets removed (no action required)
# Convert the updated intervals back to string format for the line edit
#updated_intervals_str = str(updated_intervals).replace(' ', '').replace('[','').replace(']','') # Format it to match the original input format
updated_intervals_str = ','.join(f"({float(a):.6f},{float(b):.6f})" for a, b in updated_intervals)
# Set the updated string back to the QLineEdit
self.gui.lineEdit_telluric.setText(updated_intervals_str)
else:
print("Flag type unknown.")
self.linetable_mask()
self.fit_spline()
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def on_slice_pressed(self):
xlim_l=float(self.gui.ax[0].get_xlim()[0])
xlim_h=float(self.gui.ax[0].get_xlim()[1])
# Conditions to get the indices within the desired limits
indices = (self.gui.xcurrent >= xlim_l) & (self.gui.xcurrent <= xlim_h)
self.gui.xcurrent=self.gui.xcurrent[indices]
self.gui.ycurrent=self.gui.ycurrent[indices]
self.gui.xlim_l_last=xlim_l
self.gui.xlim_h_last=xlim_h
# remove fit
self.gui.yi=np.array([])
self.gui.ynorm = np.array([])
self.gui.ynormcurrent=np.array([])
self.gui.knots_x = np.array([])
self.gui.knots_y = np.array([])
# preserve masks
# handle strange case where length of self.gui.mask is greater by 1 than length of original self.gui.xcurrent
if len(self.gui.mask)-len(indices):
self.gui.mask = self.gui.mask[:-1]
if len(self.gui.telluricmask)>0: self.gui.telluricmask=self.gui.telluricmask[indices]
if len(self.gui.mask)>0: self.gui.mask=self.gui.mask[indices]
if len(self.gui.ymaskedcurrent)>0: self.gui.ymaskedcurrent[indices]
self.fit_spline(showfit=True)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def on_reset_pressed(self):
self.gui.xcurrent=self.gui.x
self.gui.ycurrent=self.gui.y
self.gui.ymaskedcurrent=self.gui.y
self.gui.ynorm = np.array([])
self.gui.ynormcurrent=self.gui.ynorm
self.gui.yi=np.array([])
#self.gui.mask=np.array([])
self.gui.telluricmask=np.array([])
if len(self.gui.x)>0:
self.gui.ax[0].set_xlim([min(self.gui.x),max(self.gui.x)])
self.gui.ax[1].set_xlim([min(self.gui.x),max(self.gui.x)])
self.gui.xlim_h_last=max(self.gui.x)
self.gui.xlim_l_last=min(self.gui.x)
else:
self.gui.xlim_h_last=0
self.gui.xlim_l_last=0
self.gui.knots_x = np.array([])
self.gui.knots_y = np.array([])
self.gui.ax[0].cla()
self.gui.ax[1].cla()
# Standard telluric absorption bands
self.create_telluric_mask(initialize_from_models=True)
self.linetable_mask()
self.make_fig(0)
#self.gui.tableWidget.clearContents()
#self.fit_spline(showfit=False)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def on_home_pressed(self, *args, **kwargs):
""" add some functionality to matplotlib's home button
"""
self.gui.ax[0].set_xlim([min(self.gui.xcurrent),max(self.gui.xcurrent)])
self.gui.ax[1].set_xlim([min(self.gui.xcurrent),max(self.gui.xcurrent)])
self.fit_spline(showfit=True)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def connect_buttons(self):
""" Connect the GUI buttons with slots
"""
self.gui.pushButton_openfits.clicked.connect(self.selectFile)
self.gui.comboBox_method.currentIndexChanged.connect(self.method_changed)
self.gui.pushButton_normalize.clicked.connect(lambda _: self.fit_spline(showfit=True))
self.gui.pushButton_identify_mask_lines.clicked.connect(self.identify_mask)
self.gui.pushButton_linetable_mask.clicked.connect(self.linetable_mask)
self.gui.pushButton_savefits.clicked.connect(self.saveFile)
self.gui.pushButton_determine_rad_velocity.clicked.connect(self.determine_rad_velocity)
self.gui.pushButton_undo.clicked.connect(self.undo_mask_change)
self.gui.pushButton_shift_spectrum.clicked.connect(self.apply_velocity_shift)
self.gui.pushButton_renorm_factor_auto.clicked.connect(self.renorm_auto)
# IO PART
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def selectFile(self):
""" Opens a window for the user to select a FITS files
"""
if self.gui.lbl_fname.text() is not None and os.path.isfile(self.gui.lbl_fname.text()):
mydir = os.path.dirname(self.gui.lbl_fname.text())
else:
mydir = QDir.currentPath()
filename,_ = QFileDialog.getOpenFileName(None,'Open FITS spectrum', self.userpath, self.tr("*.fits"))
if filename == '':
# cancel was clicked
return
if mydir == QDir.currentPath():
self.gui.lbl_fname.setText(os.path.basename(filename))
else:
self.gui.lbl_fname.setText(filename)
self.readfits(filename)
self.on_reset_pressed()
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def saveFile(self, showfiledialogue=False):
"""
if self.gui.lbl_fname.text() is not None and os.path.isfile(self.gui.lbl_fname.text()):
mydir = os.path.dirname(self.gui.lbl_fname.text())
else:
mydir = QtCore.QDir.currentPath()
filename,_ = QFileDialog.getSaveFileName(None,'Save to FITS', self.tr("(*.fits)"))
"""
if len(self.gui.x) > 0:
if showfiledialogue:
# Set the options for the dialog
options = QFileDialog.Options()
filename, _ = QFileDialog.getSaveFileName(self, "QFileDialog.getSaveFileName()", self.userpath,
"All Files (*);;FITS Files (*.fits)",
options=options)
else:
file_basename = os.path.basename(self.gui.lbl_fname.text())
# Split the filename and extension
file_name_without_extension, file_extension = os.path.splitext(file_basename)
filename = f"{file_name_without_extension}_{str(int(self.gui.xlim_l_last))}-{str(int(self.gui.xlim_h_last))}.fits"
# Check if the filename is valid, e.g. when user pressed "Cancel" the filename is empty
if filename != '':
self.gui.lbl_fname2.setText(filename)
self.writefits(filename)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def zoom_fig(self,wave_min,wave_max):
if wave_min < min(self.gui.x): wave_min = min(self.gui.x)
if wave_max > max(self.gui.x): wave_max = max(self.gui.x)
self.gui.ax[0].set_xlim([wave_min,wave_max])
#self.gui.ax[1].set_xlim()
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def tr(self, text):
return QObject.tr(self, text)
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def remove_spikes(self, indata, n_std=10):
"""
Iteratively remove spikes from the edges of a 1D spectrum if they exceed a certain threshold.
Parameters:
data: numpy array of 1D spectrum.
n_std: number of standard deviations above/below the mean to use as a threshold for spikes.
Returns:
The cleaned spectrum.
"""
data = self.smooth(indata,100)
# Calculate mean and standard deviation of the data
mean = np.mean(data)
std = np.std(data)
# Define threshold
threshold_upper = mean + n_std * std
threshold_lower = mean - n_std * std
# Define indices for iterative edge spike check
start_index = 0
end_index = len(data) - 1
# Check for spikes from edges towards the center
while start_index < end_index:
# Check start
if data[start_index] > threshold_upper or data[start_index] < threshold_lower:
start_index += 1
else:
# If no spike is found, stop the iteration
break
# Start from the end and move towards the start
while end_index >= start_index:
# Check end
if data[end_index] > threshold_upper or data[end_index] < threshold_lower:
end_index -= 1
else:
# If no spike is found, stop the iteration
break
# Return the cleaned spectrum
return start_index, end_index+1
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def find_telluric_intervals(self, filename):
# Read the data from the file
data = pd.read_csv(filename, sep='\t', comment='#', header=None,
names=["Wavelength", "Molecular Absorption", "Ozone",
"Rayleigh Scattering", "Aerosol Extinction"])
# Multiply the Wavelength column by 10
data["Wavelength"] = data["Wavelength"] * 10
# Filter the data where Molecular Absorption < 0.99
filtered_data = data[data["Molecular Absorption"] < 0.99]
# Find continuous regions/intervals
intervals = []
start = end = np.round(filtered_data['Wavelength'].iloc[0],3)
for i in range(1, len(filtered_data)):
if filtered_data['Wavelength'].iloc[i] - end > 1: # Change this as per the gap in your data
intervals.append((start, end))
start = np.round(filtered_data['Wavelength'].iloc[i],3)
end = np.round(filtered_data['Wavelength'].iloc[i],3)
intervals.append((start, end))
return intervals
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def is_iterable(self,obj):
try:
iter(obj)
return True
except TypeError:
return False
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def fix_telluric_intervals_notalist(self, telluric_intervals):
telluric_intervals = [list(telluric_intervals)]
telluric_intervals.append([0.0001,0.0002] )
return telluric_intervals
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def create_telluric_mask(self, initialize_from_models=False):
if initialize_from_models:
telluric_intervals = self.find_telluric_intervals(os.environ['NORMALIZER_DIR']+"/skycalc_molec_abs.txt")
self.gui.lineEdit_telluric.setText(', '.join('({}, {})'.format(*t) for t in telluric_intervals))
if self.gui.lineEdit_telluric.text().strip().strip(',') != '' and len(self.gui.lineEdit_telluric.text().strip().strip(','))>0:
# Initialize new array for telluric mask
self.gui.telluricmask = np.full_like(self.gui.xcurrent, 1)
# Parse the intervals from the telluric line edit
# and shift to the observed scale
telluric_intervals = ast.literal_eval(self.gui.lineEdit_telluric.text().strip().strip(','))
tellurics_lambda_corrfactor = self.calc_tellurics_lambda_corrfactor()
if self.is_iterable(telluric_intervals[0]):
telluric_intervals = [(a * tellurics_lambda_corrfactor, b * tellurics_lambda_corrfactor) for a, b in telluric_intervals]
else:
telluric_intervals = self.fix_telluric_intervals_notalist(telluric_intervals)
for a, b in telluric_intervals:
self.gui.telluricmask[(self.gui.xcurrent >= a) & (self.gui.xcurrent <= b)] = 0
return self.gui.telluricmask, telluric_intervals
else:
self.gui.telluricmask = np.array([])
return self.gui.telluricmask, None
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def calc_tellurics_lambda_corrfactor(self):
try:
user_vrad = float(self.gui.lineEdit_telluric_vrad.text())
except:
user_vrad = 0.0
tellurics_lambda_corrfactor = 1.0 / self.doppler_shift(user_vrad)
return tellurics_lambda_corrfactor
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def doppler_shift(self, v_rad):
"""
Calculate the wavelength shift from v_rad
Parameters
----------
v_rad : float
The radial velocity (in same units as speed of light).
Returns
-------
float
The shifted wavelength.
"""
# Scale factor: sf = lambda_observed/lambda_emitted
sf = np.sqrt((self.c + v_rad)/(self.c - v_rad))
return sf
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def readfits(self, fitsfile, hduid=0):
self.on_reset_pressed()
# store the path of the input filename for later use when saving
self.userpath = os.path.dirname(fitsfile)
# show filename in Plot Window header
self.plotwindow.setWindowTitle(os.path.basename(fitsfile))
self.gui.ax[0].cla()
self.gui.ax[1].cla()
mask = np.array([])
# Read the input file
if fitsfile.lower().endswith('.fits') or fitsfile.lower().endswith('.fit') or fitsfile.lower().endswith('.tfit') or fitsfile.lower().endswith('.tfits'):
# If the input file is a FITS file, read it using Astropy's fits module
hdus = fits.open(fitsfile)
# Check if a BinTableHDU exists in the list of HDUs
binary_table_hdu = None
for hdu in hdus:
if isinstance(hdu, fits.BinTableHDU):
binary_table_hdu = hdu
break
# Load binary table data if it exists
if binary_table_hdu is not None:
# Read some header info
current_header = hdus[1].header
if all(key in current_header for key in ['SN_RVAPL', 'SN_RVVAL']):
if bool(current_header['SN_RVAPL']):
self.gui.lineEdit_telluric_vrad.setText(str(current_header['SN_RVVAL']))
else:
self.gui.lineEdit_telluric_vrad.setText('0.0')
self.create_telluric_mask(initialize_from_models=True)
available_cols = binary_table_hdu.data.columns.names # Get the list of available columns
# Check if 'Wavelength', 'Normalized_Flux' or 'Flux' columns are available
wavecolumnnotfound = False
if 'wavelength' in available_cols: tablename_wave = 'wavelength'
elif 'Wavelength' in available_cols: tablename_wave = 'Wavelength'
elif 'wave' in available_cols: tablename_wave = 'wave'
elif 'Wave' in available_cols: tablename_wave = 'Wave'
elif 'WAVE' in available_cols: tablename_wave = 'WAVE'
elif 'WAVELENGTH' in available_cols: tablename_wave = 'WAVELENGTH'
else:
wavecolumnnotfound = True
fluxcolumnnotfound = False
if 'normalized_flux' in available_cols: tablename_flux = 'normalized_flux'
elif 'Normalized_Flux' in available_cols: tablename_flux = 'Normalized_Flux'
elif 'flux' in available_cols: tablename_flux = 'flux'
elif 'Flux' in available_cols: tablename_flux = 'Flux'
elif 'FLUX' in available_cols: tablename_flux = 'FLUX'
elif 'NORMALIZED_FLUX' in available_cols: tablename_flux = 'NORMALIZED_FLUX'
else:
fluxcolumnnotfound = True
maskcolumnnotfound = False
if 'Mask' in available_cols: tablename_mask = 'Mask'
elif 'mask' in available_cols: tablename_mask = 'mask'
elif 'MASK' in available_cols: tablename_mask = 'MASK'
else:
maskcolumnnotfound = True
if not wavecolumnnotfound and not fluxcolumnnotfound:
x = binary_table_hdu.data[tablename_wave].ravel()
y = binary_table_hdu.data[tablename_flux].ravel()
if not maskcolumnnotfound:
mask = np.array(binary_table_hdu.data[tablename_mask].ravel(),dtype=int)
hdr = binary_table_hdu.header
else:
# check primary header for WSTART, WEND and DELTA_W
current_header = hdus[0].header
if all(key in current_header for key in ['WSTART', 'WEND', 'DELTA_W', 'N_PIXELS']) and fluxcolumnnotfound == False and wavecolumnnotfound == True:
wstart = float(current_header['WSTART'])
delta_w = float(current_header['DELTA_W'])
n_pix = int(current_header['N_PIXELS'])
# Calculate the wavelengths
new_wave = [wstart + int(i) * delta_w for i in range(n_pix)]
x = np.array(new_wave,dtype=np.float64)
y = np.array(binary_table_hdu.data[tablename_flux].ravel(),dtype=np.float64)
if not maskcolumnnotfound:
mask = np.array(binary_table_hdu.data[tablename_mask].ravel(),dtype=int)
hdr = binary_table_hdu.header
else:
# Let user select columns
print("At least one of the expected columns 'Wave', 'Wavelength', 'Flux' or 'Normalized_Flux' are not available.")
print("Available columns are: ", available_cols)
x_col = input("Please enter the column name to use as Wavelength: ")
while x_col not in available_cols:
print(f"{x_col} is not a valid column name. Please enter a valid column name for Wavelength: ")
x_col = input()
y_col = input("Please enter the column name to use as Normalized_Flux: ")
while y_col not in available_cols or y_col == x_col:
if y_col == x_col:
print(f"{y_col} is already used as Wavelength. Please enter a different column name for Normalized_Flux: ")
else:
print(f"{y_col} is not a valid column name. Please enter a valid column name for Normalized_Flux: ")
y_col = input()
x = binary_table_hdu.data[x_col].ravel()
y = binary_table_hdu.data[y_col].ravel()
hdr = binary_table_hdu.header
else:
# Otherwise, assume a regular FITS file and load image data
hdr = hdus[hduid].header
img = hdus[hduid].data
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter('always', AstropyWarning) # Change 'always' to 'error' to turn warnings into exceptions
wcs = WCS(hdr)
# Check if any relevant warnings were caught
for warning in caught_warnings:
if isinstance(warning.message, astropy.wcs.FITSFixedWarning):
print("Caught an astropy WCS warning. Trying to fix header now.")
hdr = self.clean_wcs_for_1d_fits_header(fitsfile)
# Recreate the WCS object with the potentially updated header
wcs = WCS(hdr)
if int(hdr['NAXIS']) == 2:
y = img.sum(axis=0) # summing up along spatial direction
x = wcs.all_pix2world([(x, 0) for x in range(len(y))], 0)
x = np.delete(x, 1, axis=1)
x = x.flatten()
y = y.flatten()
elif int(hdr['NAXIS']) == 1:
y = img
crpix1 = hdr['CRPIX1'] # Pixel coordinate of reference point
crval1 = hdr['CRVAL1'] # Coordinate value at reference point
cdelt1 = hdr['CDELT1'] # Coordinate increment at reference point
x = crval1 + cdelt1 * (np.arange(len(y)) - (crpix1 - 1))
else:
# Otherwise, assume the input file is an ASCII file and read it using numpy
if fitsfile.lower().endswith('.csv'):
delimiter = ','
else:
delimiter = '\t'
data = np.loadtxt(fitsfile, delimiter=delimiter, comments='#')
x = data[:, 0]
y = data[:, 1]
hdr = fits.Header()
# detect spikes at edges
start, end = self.remove_spikes(y)
# check for constant flux at edges and truncate
_, start_idx, end_idx = self.truncate_constant_edges(y, 5)
x = x[start_idx:end_idx]
y = y[start_idx:end_idx]
# remove nans
nan_indices_x = np.isnan(x)
x = x[~nan_indices_x]
y = y[~nan_indices_x]
nan_indices_y = np.isnan(y)
x = x[~nan_indices_y]
y = y[~nan_indices_y]
# Save re-usable quantities in global variables
self.gui.x = x
self.gui.y = y
self.gui.xcurrent = x
self.gui.ycurrent = y
self.gui.ymaskedcurrent = y
self.gui.hdr = hdr
self.gui.ynorm = np.array([])
self.gui.ynormcurrent = np.array([])
self.gui.yi = np.array([])
self.gui.knots_x = np.array([])
self.gui.knots_y = np.array([])
# recover mask
# mask value 0...BAD/Telluric
# mask value 1...Line
# mask value 2...Continuum
normalizer_mask = np.ones_like(mask)
normalizer_mask[mask==2] = 0
self.gui.mask = np.array(normalizer_mask,dtype=bool)
self.gui.xlim_h_last=0
self.gui.xlim_l_last=0
#self.on_reset_pressed()
#self.apply_mask()
#self.fit_spline()
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
# Define function to clean WCS keywords for 1D data and return the updated header
def clean_wcs_for_1d_fits_header(self,fits_file):
# Open the FITS file
with fits.open(fits_file) as hdul:
header = hdul[0].header # Assuming the primary header contains the WCS info
# Check if the data is 1-dimensional
if hdul[0].data.ndim == 1:
print(f"Data in {fits_file} is 1-dimensional, but header suggests otherwise!")
# List of WCS keywords that are irrelevant for 1D data
wcs_keywords_2d_3d = ['CRPIX2', 'CRPIX3', 'CDELT2', 'CDELT3',
'CRVAL2', 'CRVAL3', 'CTYPE2', 'CTYPE3',
'CUNIT2', 'CUNIT3', 'CROTA2', 'CROTA3',
'PC2_', 'PC3_', 'CD2_', 'CD3_', 'PV2_', 'PV3_']
# Create a copy of the header before modification
updated_header = header.copy()
# Remove the irrelevant WCS keywords from the copy
for key in wcs_keywords_2d_3d:
# Check each pattern and remove if present
for k in list(updated_header.keys()):
if k.startswith(key):
del updated_header[k]
return updated_header
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
def writefits(self, fitsfile, hduid=0):
""" Save normalized spectrum and mask in
fits file