-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsed_plot_interface.py
3034 lines (2796 loc) · 126 KB
/
sed_plot_interface.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
#
"""
This is the main driver routien for the SED display and analysis.
The normal use would be to invoke this from the command line as in
sed_plot_interface.py
There are no parameters for the call.
This code requires the Python extinction package. Installation of the
package is described at "https://extinction.readthedocs.io/en/latest/".
Other required packages: tkinter, matplotlib, numpy, scipy, sys, os, math,
and astropy. All these are common packages.
"""
import math
import sys
import os
import tkinter as Tk
import tkinter.ttk
import tkinter.filedialog
import tkinter.simpledialog
import tkinter.messagebox
from tkinter.colorchooser import askcolor
from tkinter.scrolledtext import ScrolledText
from tkinter.filedialog import askopenfilenames
from tkinter.simpledialog import askinteger
import numpy
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
from matplotlib.figure import Figure
import read_vizier_sed_table
import sed_utilities
import tkinter_utilities
import extinction_code
import model_utilities
import position_plot
matplotlib.use('TkAgg')
# The following are "global" variables with line/marker information from
# matplotlib. These are used, but not changed, in the code in more than one
# place hence I am using single variables here for the values.
MATPLOTLIB_SYMBOL_LIST = [
None, "o", "v", "^", "<", ">", "1", "2", "3", "4", "8", "s", "p",
"P", "*", "h", "H", "+", "x", "X", "D", "d", "|", "_", ".", "."]
MATPLOTLIB_SYMBOL_NAME_LIST = [
'None', 'circle', 'triangle down', 'triangle up', 'triangle_left',
'triangle right', 'tri_down', 'tri_up', 'tri_left', 'tri_right',
'octagon', 'square', 'pentagon', 'plus (filled)', 'star',
'hexagon1', 'hexagon2', 'plus', 'x', 'x (filled)', 'diamond',
'thin_diamond', 'vline', 'hline', 'point', 'pixel']
MATPLOTLIB_LINE_LIST = ['-', '--', '-.', ':', None]
MATPLOTLIB_LINE_NAME_LIST = ['solid', 'dashed', 'dashdot', 'dotted', 'None']
# define a background colour for windows
BGCOL = '#F8F8FF'
# default colours
COLOUR_SET = ['blue', 'forestgreen', 'black', 'orange', 'red', 'purple',
'cyan', 'lime', 'brown', 'violet', 'grey', 'gold']
WAVELNORM = 2.2
FLAMBDANORM = 5.e-15
def startup():
"""
Startup.py is a wrapper for starting the plot tool.
Parameters
----------
None.
Returns
-------
root : The Tkinter window class variable for the plot window.
plot_object : The SED plot GUI object variable.
"""
# Make a Tkinter window
newroot = Tk.Tk()
newroot.title("SED Fitting Tool")
newroot.config(bg=BGCOL)
# start the interface
plot_object = PlotWindow(newroot)
return newroot, plot_object
def strfmt(value):
"""
Apply a format to a real value for writing out the data values.
This routine is used to format an input real value either in
exponential format or in floating point format depending on
the magnitude of the input value.
This works better for constant width columns than the Python g format.
Parameters
----------
value : a real number value
Returns
-------
outstring : a format string segment
"""
if (abs(value) > 1.e+07) or (abs(value) < 0.001):
outstring = '%14.7e ' % (value)
if value == 0.:
outstring = '%14.6f ' % (value)
else:
outstring = '%14.6f ' % (value)
outstring = outstring.lstrip(' ')
return outstring
def get_data_values(xdata, ydata, mask, filternames):
"""
Utility routine to apply a mask to (x,y) data.
Parameters
----------
xdata: A numpy array of values, nominally float values
ydata: A numpy array of values, nominally float values
mask: A numpy boolean array for which points are to be returned
filternames: A numpy string array of the filter names
Returns
-------
newxdata: A numpy array of the xdata values where mask = True
newydata: A numpy array of the ydata values where mask = True
newfilternames: A numpy array of the filter names where mask = True
"""
inds = numpy.where(mask)
newxdata = numpy.copy(xdata[inds])
newydata = numpy.copy(ydata[inds])
try:
newfilternames = numpy.copy(filternames[inds])
except TypeError:
newfilternames = []
for loop in range(len(newxdata)):
newfilternames.append('')
newfilternames = numpy.asarray(newfilternames)
inds = numpy.argsort(newxdata)
newxdata = newxdata[inds]
newydata = newydata[inds]
newfilternames = newfilternames[inds]
return newxdata, newydata, newfilternames
def unpack_vot(votdata):
"""
Utility routine to unpack Vizier VOT photometry data.
Parameters
----------
votdata: A table of Vizier photometry values from the read_vizier_vot
function
Returns
-------
data_set: A list containing a variety of values read from the VOT file
"""
photometry_values = numpy.copy(votdata[0])
error_mask = numpy.copy(votdata[1])
filter_names = numpy.copy(votdata[2])
references = numpy.copy(votdata[3])
refpos = numpy.copy(votdata[4])
data_set = {'wavelength': None, 'frequency': None, 'fnu': None,
'flambda': None, 'lfl': None, 'l4fl': None,
'dfnu': None, 'dflambda': None, 'dl4fl': None,
'dlfl': None, 'mask': None, 'plot_mask': None,
'filter_name': None, 'distance': None,
'position': None, 'refpos': None,
'references': None, 'plot': None, 'source': None,
'colour_by_name': False}
data_set['wavelength'] = numpy.squeeze(photometry_values[0, :])
data_set['frequency'] = numpy.squeeze(photometry_values[1, :])
data_set['fnu'] = numpy.squeeze(photometry_values[4, :])
data_set['flambda'] = numpy.squeeze(photometry_values[6, :])
data_set['lfl'] = numpy.squeeze(photometry_values[8, :])
data_set['l4fl'] = numpy.squeeze(photometry_values[8, :]) *\
(data_set['wavelength']**3)
data_set['dfnu'] = numpy.squeeze(photometry_values[5, :])
data_set['dflambda'] = numpy.squeeze(photometry_values[7, :])
data_set['dlfl'] = numpy.squeeze(photometry_values[9, :])
data_set['dl4fl'] = numpy.squeeze(photometry_values[9, :]) *\
(data_set['wavelength']**3)
data_set['filter_name'] = numpy.copy(filter_names)
data_set['position'] = [numpy.squeeze(photometry_values[2, :]),
numpy.squeeze(photometry_values[3, :])]
data_set['refpos'] = numpy.copy(refpos)
data_set['references'] = numpy.copy(references)
data_set['mask'] = numpy.copy(error_mask)
data_set['plot_mask'] = numpy.copy(error_mask)
for loop in range(len(error_mask)):
data_set['plot_mask'][loop] = True
data_set['distance'] = numpy.copy(photometry_values[10:14, :])
return data_set
class PlotWindow(Tk.Frame):
"""
This is the class for the plotting window.
Parameters
----------
Tk.Frame: A Tkinter Frame, root or Toplevel variable to hold
the plot window (more usually one of the latter two)
Returns
-------
The class variable is returned.
"""
def __init__(self, parent, **args):
"""
This routine sets a few variables for the interface and calls the
main widget function.
Parameters
----------
parent: A parameter giving the parent Tk root window name.
**args A possible list of additional arguments. This is
currently not used.
Returns
-------
No value is returned by this routine.
"""
if sys.version_info[0] == 2:
raise ValueError('Python version 2 is required for the code.')
if parent is None:
raise ValueError('A root or top level window is required in ' +
'the call to sed_plot_window')
# initialize the window and make the plot area.
Tk.Frame.__init__(self, parent, args)
self.root = parent
self.data_values = [{'wavelength': None, 'fnu': None,
'frequency': None,
'flambda': None, 'lfl': None, 'l4fl': None,
'dfnu': None, 'dflambda': None,
'dl4fl': None, 'dlfl': None, 'mask': None,
'filter_name': None, 'distance': None,
'position': None, 'refpos': None,
'references': None, 'plot': None,
'source': None, 'plot_mask': None,
'color_by_name': False}, ]
self.stellar_models = [{'wavelength': None, 'fnu': None,
'flambda': None, 'lfl': None,
'l4fl': None, 'label': None}, ]
self.tkinter_values = {'plot_frame': None, 'variables': [None, ],
'entry': None, 'button': None,
'radio': None, 'subplot': None,
'canvas': None, 'figure': None,
'set_parameters': None,
'modeltype': None}
self.extinction_values = {'av': None, 'ebmv': None,
'function': None, 'redden': True,
'controls': None,
'rl_wavelengths': None,
'rl_extinction': None}
self.flags = {'auto_scale': True, 'toggle_status': False,
'zoom_status': False, 'positions': [],
'model_scale': False, 'point_scale': False,
'template_spectrum': -1, 'use_ratio': False,
'mask_area': False}
self.make_widget()
def make_widget(self):
"""
This routine makes the main plot window.
The plot area and the control area are created here with Tkinter calls.
Various object variables are defined in the process.
Parameters
----------
None
Returns
-------
Nothing is returned from this routine.
"""
menu_frame = Tk.Frame(self.root)
menu_frame.pack(side=Tk.TOP, anchor=Tk.W)
menu_frame.config(bg=BGCOL)
self.__make_menus(menu_frame)
control_frame = Tk.Frame(self.root)
control_frame.pack(side=Tk.LEFT, fill=Tk.Y, expand=1)
control_frame.config(bg=BGCOL)
self.__make_controls(control_frame)
tkinter_utilities.separator_line(self.root, [5, 750, 5],
False, Tk.LEFT, BGCOL)
plot_frame = Tk.Frame(self.root)
plot_frame.pack(side=Tk.LEFT, fill=Tk.Y, expand=1)
plot_frame.config(bg=BGCOL)
self.__make_plot_area(plot_frame)
self.tkinter_values['plot_frame'] = plot_frame
def __make_menus(self, parent):
"""
Create pull-down menus for tool functionality.
Given a Tk Frame variable "parent" this routine makes a pull-down
menu area within this frame.
Parameters
----------
parent A Tk.Frame variable, that holds the menus
Returns
-------
No values are returned by the routine.
"""
menubutton1 = Tk.Menubutton(parent, text="Read/Save Data")
menubutton1.pack(side=Tk.LEFT, fill=Tk.X, expand=2)
menubutton1.config(bg=BGCOL)
menu1 = Tk.Menu(menubutton1)
menubutton1['menu'] = menu1
menu1.add_command(label='Read Vizier SED file',
command=self.read_vizier_file)
menu1.add_command(label='Read spectrum file',
command=self.read_spectrum_file)
menu1.add_command(label='Save data set',
command=self.save_data_set)
menu1.add_command(label='Read data set',
command=self.read_data_set)
menubutton2 = Tk.Menubutton(parent, text="Data Operations")
menubutton2.pack(side=Tk.LEFT, fill=Tk.X, expand=2)
menubutton2.config(bg=BGCOL)
menu2 = Tk.Menu(menubutton2)
menubutton2['menu'] = menu2
menu2.add_command(label='Delete/Undelete Data Points',
command=self.__toggle_data_status)
menu2.add_command(label='Toggle Points in Region',
command=self.__toggle_mask_area)
menu2.add_command(label='Unmask All Points',
command=self.unmask_all)
menu2.add_command(label='Cursor Zoom',
command=self.__toggle_zoom_status)
menu2.add_command(label='Auto-scale Plot',
command=self.__autoscale_plot)
menu2.add_command(label='Freeze Range',
command=self.freeze_range)
menu2.add_command(label='Average Vizier Data',
command=self.average_vizier_data)
menu2.add_command(label='Toggle Vizier Filter Colours',
command=self.__toggle_colour_display)
menu2.add_command(label='De-redden Data',
command=lambda: self.make_extinction_window(True))
menu2.add_command(label='Calculate Flux',
command=self.calculate_flux)
menu2.add_command(label='Show Position Offsets',
command=self.__plot_position_offsets)
menubutton3 = Tk.Menubutton(parent, text="Stellar Models")
menubutton3.pack(side=Tk.LEFT, fill=Tk.X, expand=2)
menubutton3.config(bg=BGCOL)
menu3 = Tk.Menu(menubutton3)
menubutton3['menu'] = menu3
menu3.add_command(label='Read Stelar Model',
command=self.stellar_model_window)
menu3.add_command(label='Scale Model to Cursor',
command=self.__scale_model_to_cursor)
menu3.add_command(label='Scale Model to Data Point',
command=self.__scale_model_to_point)
menu3.add_command(label='Define Blackbody Spectrum',
command=self.__make_blackbody)
menu3.add_command(label='Toggle Standard/Ratio Fit',
command=self.__toggle_ratio_flag)
menu3.add_command(label='Fit Model to Data Points',
command=self.__fit_model_to_data)
menu3.add_command(label='Redden Model',
command=lambda: self.make_extinction_window(False))
menu3.add_command(label='Set Standard Spectrum',
command=self.set_standard_spectrum)
menu3.add_command(label='Find Best Fit Model',
command=self.__get_model_names)
def __make_blackbody(self):
"""
Query the user for a temperature value, then make a blackbody spectrum
using the standard spectral template wavelengths. Add the spectrum to
the plot with the usual normalization.
"""
temperature = tkinter.simpledialog.askfloat(
'Query', 'Enter blackbody temperature:')
if temperature <= 4.:
str1 = 'The temperature %.3f is too low' % (temperature)
tkinter.messagebox.showinfo('Error', str1)
return
try:
path = os.environ['EXTINCTION_PATH']
if path[-1] != '/':
path = path + '/'
except:
path = './'
try:
wavelengths, spectrum = \
model_utilities.read_calspec_model(path+'sirius_mod_004.fits')
except:
tkinter.messagebox.showinfo(
'Error', 'Could not read in file sirius_mod_004.fits.')
# The following are the standard radiation constants (CODATA 2018)
# with wavelength units changed to microns
c1 = 3.741771852e+08
c2 = 14387.76877
#
factor = numpy.expm1(c2/(WAVELNORM*temperature))
f0 = (c1/numpy.power(WAVELNORM, 5))/factor
scale = FLAMBDANORM/f0
exp1 = c2/(wavelengths*temperature)
spectrum = scale*(c1/numpy.power(wavelengths, 5))/numpy.expm1(exp1)
overflowinds = numpy.isnan(spectrum)
spectrum[overflowinds] = 0.
overflowinds=numpy.isinf(spectrum)
spectrum[overflowinds] = 0.
label = 'stellar model (blackbody %.3f K)' % (temperature)
self.add_spectrum(wavelengths, spectrum, 0, 0, label)
self.make_plot()
def __toggle_colour_display(self):
response = tkinter.simpledialog.askstring(
'Input', 'Set to toggle colour status (or all):')
if 'all' == response.lower():
for loop in range(len(self.data_values)):
if 'vizier_sed' in self.data_values[loop]['source']:
self.data_values[loop]['colour_by_name'] = not \
self.data_values[loop]['colour_by_name']
else:
try:
loop = int(response) - 1
if loop < len(self.data_values):
self.data_values[loop]['colour_by_name'] = not \
self.data_values[loop]['colour_by_name']
except:
pass
self.make_plot()
def __toggle_ratio_flag(self):
self.flags['use_ratio'] = not self.flags['use_ratio']
if self.flags['use_ratio']:
str1 = 'The point by point signal ratio will be used' + \
' in model fitting.'
else:
str1 = 'The normal least squares calculation will be ' + \
'used in model fitting.'
tkinter.messagebox.showinfo('Information', str1)
def __get_model_names(self):
names = askopenfilenames()
print(names)
def __make_controls(self, parent):
"""
Make the control area within the main window.
This routine makes a control area within the main window, under
frame "parent". The overall root value is also passed here for
closing the window.
Parameters
----------
parent : A Tk.Frame variable for the holder of the controla
Returns
-------
No values are returned by this routine.
"""
holder = Tk.Frame(parent)
holder.pack(side=Tk.TOP)
holder.config(bg=BGCOL)
label1 = Tk.Label(holder, text=' ')
label1.pack(side=Tk.TOP, fill=Tk.X)
label1.config(bg=BGCOL)
button1 = Tk.Button(holder, text='(Re-)Plot', command=self.make_plot)
button1.pack(side=Tk.TOP, fill=Tk.X)
button1.config(bg=BGCOL)
button2 = Tk.Button(holder, text='Auto-scale Plot',
command=self.__autoscale_plot)
button2.pack(side=Tk.TOP, fill=Tk.X)
button2.config(bg=BGCOL)
button3 = Tk.Button(holder, text='Apply/Freeze Range',
command=self.freeze_range)
button3.pack(side=Tk.TOP, fill=Tk.X)
button3.config(bg=BGCOL)
button4 = Tk.Button(
holder, text='Set Properties', command=self.change_set_properties)
button4.pack(side=Tk.TOP, fill=Tk.X)
button4.config(bg=BGCOL)
range_field = Tk.Frame(holder)
range_field.pack(side=Tk.TOP)
range_field.config(bg=BGCOL)
label1 = Tk.Label(range_field, text='x min: ')
label1.grid(column=0, row=0)
label1.config(bg=BGCOL)
xmin_field = Tk.Entry(range_field, width=15)
xmin_field.grid(column=1, row=0)
xmin_field.insert(0, ' ')
label1 = Tk.Label(range_field, text='x max: ')
label1.grid(column=0, row=1)
label1.config(bg=BGCOL)
xmax_field = Tk.Entry(range_field, width=15)
xmax_field.grid(column=1, row=1)
xmax_field.insert(0, ' ')
label1 = Tk.Label(range_field, text='y min: ')
label1.grid(column=0, row=2)
label1.config(bg=BGCOL)
ymin_field = Tk.Entry(range_field, width=15)
ymin_field.grid(column=1, row=2)
ymin_field.insert(0, ' ')
label1 = Tk.Label(range_field, text='y max: ')
label1.grid(column=0, row=3)
label1.config(bg=BGCOL)
ymax_field = Tk.Entry(range_field, width=15)
ymax_field.grid(column=1, row=3)
ymax_field.insert(0, ' ')
option_area = Tk.Frame(holder)
option_area.pack(side=Tk.TOP)
option_area.config(bg=BGCOL)
label1 = Tk.Label(option_area, text='y values type: ')
label1.pack(side=Tk.TOP)
ytypeflag = Tk.IntVar()
label1.config(bg=BGCOL)
opt1 = Tk.Radiobutton(option_area, text='lambda*F_lambda',
variable=ytypeflag, value=0,
command=self.make_plot)
opt1.pack(side=Tk.TOP)
opt1.config(bg=BGCOL)
opt2 = Tk.Radiobutton(option_area, text='F_lambda',
variable=ytypeflag, value=1,
command=self.make_plot)
opt2.pack(side=Tk.TOP)
opt2.config(bg=BGCOL)
opt3 = Tk.Radiobutton(option_area, text='F_nu',
variable=ytypeflag, value=2,
command=self.make_plot)
opt3.pack(side=Tk.TOP)
opt3.config(bg=BGCOL)
opt4 = Tk.Radiobutton(option_area, text='lambda^4 * F_lambda',
variable=ytypeflag, value=3,
command=self.make_plot)
opt4.pack(side=Tk.TOP)
opt4.config(bg=BGCOL)
ytypeflag.set(0)
option_area = Tk.Frame(holder)
option_area.pack(side=Tk.TOP)
option_area.config(bg=BGCOL)
label1 = Tk.Label(option_area, text='x values type: ')
label1.pack(side=Tk.TOP)
xtypeflag = Tk.IntVar()
label1.config(bg=BGCOL)
opt1 = Tk.Radiobutton(option_area, text='Wavelength',
variable=xtypeflag, value=0,
command=self.make_plot)
opt1.pack(side=Tk.TOP)
opt1.config(bg=BGCOL)
opt2 = Tk.Radiobutton(option_area, text='Frequency',
variable=xtypeflag, value=1,
command=self.make_plot)
opt2.pack(side=Tk.TOP)
opt2.config(bg=BGCOL)
xtypeflag.set(0)
tkinter_utilities.separator_line(holder, [200, 25, 5], True,
Tk.TOP, BGCOL)
label1 = Tk.Label(holder, text='Apply Filter Extinction')
label1.pack(side=Tk.TOP)
label1.config(bg=BGCOL)
h1 = Tk.Frame(holder)
h1.pack(side=Tk.TOP)
filter_extinction_flag = Tk.IntVar()
opt1 = Tk.Radiobutton(h1, text='Yes',
variable=filter_extinction_flag, value=0)
opt1.pack(side=Tk.LEFT)
opt1.config(bg=BGCOL)
opt2 = Tk.Radiobutton(h1, text='No',
variable=filter_extinction_flag, value=1)
opt2.pack(side=Tk.TOP)
opt2.config(bg=BGCOL)
filter_extinction_flag.set(1)
label1 = Tk.Label(holder, text='Use Filter Mean Flux Density')
label1.pack(side=Tk.TOP)
label1.config(bg=BGCOL)
h1 = Tk.Frame(holder)
h1.pack(side=Tk.TOP)
filter_mean_flambda_flag = Tk.IntVar()
opt1 = Tk.Radiobutton(h1, text='Yes',
variable=filter_mean_flambda_flag, value=0)
opt1.pack(side=Tk.LEFT)
opt1.config(bg=BGCOL)
opt2 = Tk.Radiobutton(h1, text='No',
variable=filter_mean_flambda_flag, value=1)
opt2.pack(side=Tk.TOP)
opt2.config(bg=BGCOL)
filter_mean_flambda_flag.set(1)
tkinter_utilities.separator_line(holder, [200, 25, 5], True,
Tk.TOP, BGCOL)
button5 = Tk.Button(holder, text='Save as PNG',
command=self.save_as_png)
button5.pack(side=Tk.TOP, fill=Tk.X)
button5.config(bg=BGCOL)
button6 = Tk.Button(holder, text='Save as Postscript',
command=self.save_as_postscript)
button6.pack(side=Tk.TOP, fill=Tk.X)
button6.config(bg=BGCOL)
tkinter_utilities.separator_line(holder, [200, 25, 5], True,
Tk.TOP, BGCOL)
button7 = Tk.Button(holder, text='Clear Plot',
command=self.__clear_plot)
button7.pack(side=Tk.TOP, fill=Tk.X)
button7.config(bg=BGCOL)
button8 = Tk.Button(holder, text='Close Window',
command=self.__close_main_window)
button8.pack(side=Tk.TOP, fill=Tk.X)
button8.config(bg=BGCOL)
self.tkinter_values['entry'] = {
'xmin': xmin_field, 'xmax': xmax_field,
'ymin': ymin_field, 'ymax': ymax_field}
if len(self.tkinter_values['variables']) == 1:
self.tkinter_values['variables'].append(ytypeflag)
self.tkinter_values['variables'].append(xtypeflag)
self.tkinter_values['variables'].append(filter_extinction_flag)
self.tkinter_values['variables'].append(filter_mean_flambda_flag)
else:
self.tkinter_values['variables'][1] = ytypeflag
self.tkinter_values['variables'][2] = xtypeflag
self.tkinter_values['variables'][3] = filter_extinction_flag
self.tkinter_values['variables'][4] = filter_mean_flambda_flag
def __close_main_window(self):
response = tkinter.messagebox.askyesno(
"Verify",
"Do you want to quit the interface?")
if not response:
return
self.root.destroy()
def __clear_plot(self):
response = tkinter.messagebox.askyesno(
"Verify",
"Do you want to abandon the current plot?")
if not response:
return
self.data_values = [{'wavelength': None, 'fnu': None,
'frequency': None,
'flambda': None, 'lfl': None, 'l4fl': None,
'dfnu': None, 'dflambda': None, 'dl4fl': None,
'dlfl': None, 'mask': None,
'filter_name': None, 'distance': None,
'position': None, 'refpos': None,
'references': None, 'plot': None,
'source': None, 'plot_mask': None,
'colour_by_name': False}, ]
self.stellar_models = [{'wavelength': None, 'fnu': None,
'flambda': None, 'lfl': None, 'l4fl': None}, ]
self.extinction_values = {'av': None, 'ebmv': None,
'function': None, 'redden': True,
'controls': None,
'rl_wavelengths': None,
'rl_extinction': None}
self.flags = {'auto_scale': True, 'toggle_status': False,
'zoom_status': False, 'positions': [],
'model_scale': False, 'point_scale': False,
'template_spectrum': -1, 'use_ratio': False,
'mask_area': False}
self.make_plot()
xmin, xmax, ymin, ymax = self.get_bounds(
self.tkinter_values['subplot'])
def average_vizier_data(self):
for loop in range(len(self.data_values)):
if self.data_values[loop]['source'] == 'vizier_sed':
data_set = {
'wavelength': None, 'frequency': None,
'fnu': None, 'flambda': None, 'lfl': None, 'l4fl': None,
'dfnu': None, 'dflambda': None, 'dl4fl': None,
'dlfl': None, 'mask': None, 'plot_mask': None,
'filter_name': None, 'distance': None,
'position': None, 'refpos': None,
'references': None, 'plot': None, 'source': None,
'colour_by_name': False}
xvalues = numpy.copy(self.data_values[loop]['wavelength'])
yvalues = numpy.copy(self.data_values[loop]['flambda'])
filter_names = numpy.copy(
self.data_values[loop]['filter_name'])
inds = numpy.where(self.data_values[loop]['plot_mask'])
xvalues = xvalues[inds]
yvalues = yvalues[inds]
filter_names = filter_names[inds]
newxvalues, newyvalues, new_filter_names = \
sed_utilities.vizier_means(
xvalues, yvalues, filter_names)
data_set['wavelength'] = newxvalues
data_set['frequency'] = sed_utilities.trans_wavelength(
newxvalues, 0, 2)
data_set['flambda'] = newyvalues
data_set['fnu'] = sed_utilities.trans_flux_density(
newxvalues, newyvalues, 0, 5)
data_set['lfl'] = sed_utilities.trans_flux_density(
newxvalues, newyvalues, 0, 2)
data_set['l4fl'] = data_set['lfl'] * (
data_set['wavelength']**3)
data_set['dflambda'] = newyvalues * 0.
data_set['dfni'] = newyvalues * 0.
data_set['dlfl'] = newyvalues * 0.
data_set['d4lfl'] = newyvalues * 0.
data_set['source'] = 'averaged_vizier_set'
data_set['filter_name'] = new_filter_names
mask = []
for n1 in range(len(newxvalues)):
mask.append(True)
data_set['mask'] = mask
data_set['plot_mask'] = mask
data_set['plot'] = {
'symbol': self.data_values[loop]['plot']['symbol'],
'size': self.data_values[loop]['plot']['size'],
'line': True,
'line_type': MATPLOTLIB_LINE_LIST[1],
'line_width': 1.0,
'colour': self.data_values[loop]['plot']['colour'],
'show': True}
for newloop in range(len(COLOUR_SET)):
if data_set['plot']['colour'] == COLOUR_SET[newloop]:
n1 = newloop + 1
if n1 == len(COLOUR_SET):
n1 = 0
data_set['plot']['colour'] = COLOUR_SET[n1]
self.data_values.append(data_set)
self.make_plot()
def calculate_flux(self):
"""
Bring up a window for flux calculations.
Parameters
----------
None
Returns
-------
Nothing
"""
try:
ndatasets = len(self.data_values)
if (ndatasets == 0) or (self.data_values[0]['wavelength'] is None):
return
except ValueError:
return
window1 = Tk.Toplevel(self.root)
window1.config(bg=BGCOL)
window1.title('Flux Calculation Window')
text_area = ScrolledText(window1, height=20, width=50,
wrap=Tk.NONE)
text_area.pack(side=Tk.TOP)
text_area.config(font=('courier', 16, 'bold'))
frame1 = Tk.Frame(window1)
frame1.pack(side=Tk.TOP)
frame1.config(bg=BGCOL)
label1 = Tk.Label(frame1, text='Data set number:')
label1.grid(column=0, row=0)
set_number_menu = tkinter.ttk.Combobox(frame1, width=10)
menu = []
for loop in range(ndatasets):
menu.append(str(loop+1))
set_number_menu['values'] = menu
set_number_menu.grid(column=1, row=0)
set_number_menu.current(0)
label1 = Tk.Label(frame1, text='Distance/Parallax:')
label1.grid(column=0, row=1)
parallax_entry = Tk.Entry(frame1, width=10)
parallax_entry.grid(column=1, row=1)
parallax_entry.insert(0, '1.0')
label1 = Tk.Label(frame1, text='Distance/Parallax Uncertainty:')
label1.grid(column=0, row=2)
parallax_uncertainty_entry = Tk.Entry(frame1, width=10)
parallax_uncertainty_entry.grid(column=1, row=2)
parallax_uncertainty_entry.insert(0, '0.0')
label1 = Tk.Label(frame1, text='Value:')
label1.grid(column=0, row=3)
parallax_variable = Tk.IntVar()
button_frame = Tk.Frame(frame1)
button_frame.grid(column=1, row=3)
tkinter_utilities.put_yes_no(button_frame, parallax_variable,
['Distance (kpc)', 'Parallax (mas)'],
False)
apply_button = Tk.Button(
frame1, text='Recalculate',
command=lambda: self.calculate_fluxes(
set_number_menu, parallax_variable,
parallax_entry, parallax_uncertainty_entry,
text_area))
apply_button.grid(column=0, row=4)
close_button = Tk.Button(
frame1, text='Close', command=window1.destroy)
close_button.grid(column=1, row=4)
self.calculate_fluxes(set_number_menu, parallax_variable,
parallax_entry, parallax_uncertainty_entry,
text_area)
def calculate_fluxes(self, set_number_menu, parallax_variable,
parallax_entry, parallax_uncertainty_entry,
text_area):
"""
This routine calculates the flux from integration over the
spectral energy distribution.
Parameters
----------
set_number menu: A Tkinter menu variable
parallax_variable: A Tkinter int variable, gives the parallax
option (parallax in mas or distance in kpc)
parallax_entry: A Tkinter entry variable for the parallax or
distance
parallax_uncertainty_enrtry: A Tkinter entry variable for the
parallax or distance uncertainty
text_area: A TKinter text box or scrolled text variable where
messages are posted
"""
nset = set_number_menu.current()
wl0 = numpy.copy(self.data_values[nset]['wavelength'])
inds = numpy.where(self.data_values[nset]['plot_mask'])
wl1 = wl0[inds]
fl0 = numpy.copy(self.data_values[nset]['flambda'])
fl1 = fl0[inds]
inds = numpy.argsort(wl1)
wl2 = wl1[inds]
fl2 = fl1[inds]
flux1 = sed_utilities.integrate_sed(wl2, fl2)
outstring = '\nData set: %d\nEstimated flux: %13.6e W/m^2\n' % (
nset+1, flux1)
try:
value = float(parallax_entry.get())
value_uncertainty = float(parallax_uncertainty_entry.get())
option = parallax_variable.get()
if option == 0:
parallax = value
distance = 1./parallax
outstring = outstring + \
'Assumed parallax: %.4f mas (distance %.4f kpc)\n' % (
parallax, distance)
if value_uncertainty <= 0.:
dmin = distance
dmax = distance
else:
dmax = 1./(parallax - value_uncertainty)
dmin = 1./(parallax + value_uncertainty)
else:
distance = value
parallax = 1./distance
outstring = outstring + \
'Assumed distance: %.4f kpc (parallax %.4f mas)\n' % (
distance, parallax)
dmin = distance - value_uncertainty
dmax = distance + value_uncertainty
parsec = 3.0856781e+16
scale = 4.*parsec*parsec*math.pi*1.e+06*distance*distance
xlsun = 3.84134e+26
luminosity = flux1*scale/xlsun
outstring = outstring + 'Estimated luminosity: %.4f L_sun\n' % (
luminosity)
if dmin < dmax:
scale1 = 4.*parsec*parsec*math.pi*1.e+06*dmax*dmax
scale2 = 4.*parsec*parsec*math.pi*1.e+06*dmin*dmin
lum_max = flux1*scale1/xlsun
lum_min = flux1*scale2/xlsun
outstring = outstring + \
'Luminosity range: %.4f to %.4f L_sun' % (
lum_min,
lum_max
) + '\n (distance uncertainties only)\n'
xmbol = 4.74 - 2.5*math.log10(luminosity)
ambol = xmbol + 5.0*math.log10(distance/0.010)
outstring = outstring + 'Bolometric magnitude: %.3f\n' % (ambol)
outstring = outstring + \
'Absolute bolometric magnitude: %.3f\n' % (xmbol)
if dmin < dmax:
xmbol1 = 4.74 - 2.5*math.log10(lum_max)
xmbol2 = 4.74 - 2.5*math.log10(lum_min)
delmbol1 = xmbol - xmbol1
delmbol2 = xmbol2 - xmbol
outstring = outstring + \
'Bolometric magnitude range -%.3f +%.3f\n' % (
delmbol1, delmbol2)
except:
pass
outstring = outstring + ' \n'
tkinter_utilities.append_text(text_area, outstring)
def __toggle_data_status(self):
"""
Routine to toggle the data status flag.
Points with the flag value set to True are plotted.
"""
self.flags['toggle_status'] = True
def __toggle_mask_area(self):
"""
Routine to set the mask area flag. If set, cursor key events will
define an area within which to mask all points.
"""
self.flags['mask_area'] = True
def unmask_all(self):
"""
Routine to unmask all data points for plotting.
This undoes any points that have been masked by mouse input.
"""
for loop in range(len(self.data_values)):
for n1 in range(len(self.data_values[loop]['plot_mask'])):
self.data_values[loop]['plot_mask'][n1] = True
self.make_plot()
def __toggle_zoom_status(self):
"""
Routine to set the zoom status flag.
When set, cursor button press/release is used to zoom on the plot.
"""
self.flags['zoom_status'] = True
def save_as_png(self):
"""
Save the current plot as a PNG file.
"""
outfile = tkinter.filedialog.asksaveasfilename(
filetypes=[('PNG', '.png')])
if isinstance(outfile, type('string')):
s1 = outfile.split('.')
if 'png' not in s1[-1]:
outfile = outfile+'.png'
self.tkinter_values['figure'].savefig(outfile, format="PNG")
def save_as_postscript(self):
"""
Save the current plot as a postscript file.
"""
outfile = tkinter.filedialog.asksaveasfilename(
filetypes=[('PS', '.ps')])
if isinstance(outfile, type('string')):
s1 = outfile.split('.')
if 'ps' not in s1[-1]:
outfile = outfile+'.ps'
self.tkinter_values['figure'].savefig(outfile, format="PS")
def __make_plot_area(self, parent):
"""
Set up the main figure area for the plot.
This routine makes the figure area and the sub-plot, and then
sets up some event call-backs.
Parameters
----------
parent : A Tk.Frame variable that holds the plot
Returns
-------
No values are returned by this routine.
"""
# The size of the plot area is determined here (values in inches).
# The x/y ratio is 10 to 7 as in xmgrace. One could also use the
# golden ratio 1.618 to 1. Take whatever values seem to be the
# most aesthetically pleasing. The DPI value should probably not
# be set below 100.
figure_area = Figure(figsize=(7.142857, 5.), dpi=100)
figure_subplot = figure_area.add_subplot(1, 1, 1)
self.tkinter_values['subplot'] = figure_subplot
# The following sets up a label above the plot, for the plot
# position.
position_label_text = Tk.StringVar()
self.tkinter_values['variables'][0] = position_label_text
position_label = Tk.Label(parent, textvariable=position_label_text)
position_label.pack(side=Tk.TOP)
position_label_text.set("Position:")