-
Notifications
You must be signed in to change notification settings - Fork 13
/
vriTk.py
executable file
·1889 lines (1624 loc) · 83.3 KB
/
vriTk.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
#=============================================================================#
# #
# NAME: vriTK.py #
# #
# PURPOSE: A virtual interferometer application written in Tkinter. #
# #
# REQUIRED: Requires numpy, tkinter, matplotlib, pillow, scipy #
# #
# CREDITS: Cormac R. Purcell (cormac.purcell at mq.edu.au) #
# Roy Truelove (Macquarie University) #
# #
# CONTENTS: #
# #
# App (class) ... class containing the main application logic #
# _applicationExit #
# _show_textfile #
# _show_lone_figure #
# _update_status #
# _on_select_config #
# _on_sel_change #
# _on_obsparm_change #
# _on_pixscale_change #
# _on_plot_modFFT #
# _on_plot_uvcov #
# _on_plot_elevation #
# _on_load_model #
# _on_do_observation #
# _on_show_results #
# #
# ArraySelector ... class defining the array selection interface #
# _handler_add_button #
# _handler_clear_button #
# _handler_clear_all_button #
# #
# ObsInputs ... class exposing the remaining observation inputs #
# _handler_browse_button #
# _handler_capture_photo #
# _round_scale #
# #
# StatusFrame ... class defining status indicators and action buttons #
# _draw_checkbox #
# set_state_by_dict #
# set_state #
# #
# InformationPanel ... class showing derived properties of observation #
# update #
# #
# PlotFrame ... class defining the plotting window #
# _show_control_window #
# plot_image #
# plot_fft #
# plot_uvcov #
# show #
# clear_by_state #
# #
# MPLnavToolbar ... subclass the MPL nav toolbar to disable readout #
# set_message #
# #
#=============================================================================#
# #
# The MIT License (MIT) #
# #
# Copyright (c) 2017 - 2022 Cormac R. Purcell and Roy Truelove #
# #
# Permission is hereby granted, free of charge, to any person obtaining a #
# copy of this software and associated documentation files (the "Software"), #
# to deal in the Software without restriction, including without limitation #
# the rights to use, copy, modify, merge, publish, distribute, sublicense, #
# and/or sell copies of the Software, and to permit persons to whom the #
# Software is furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER #
# DEALINGS IN THE SOFTWARE. #
# #
#=============================================================================#
import os
import sys
try: # Python 2.7x
import Tkinter as tk
import ttk
import tkFont
import tkMessageBox
import tkFileDialog
import tkSimpleDialog
from ScrolledText import ScrolledText as tkScrolledText
except Exception: # Python 3.x
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
import tkinter.messagebox as tkMessageBox
import tkinter.filedialog as tkFileDialog
import tkinter.simpledialog as tkSimpleDialog
from tkinter.scrolledtext import ScrolledText as tkScrolledText
import numpy as np
import matplotlib as mpl
import platform
mpl.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.colors import LogNorm
from matplotlib.ticker import MaxNLocator
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk
try:
import cv2
hasCV2 = True
except ImportError:
hasCV2 = False
from Imports.util_tk import *
from Imports.vriCalc import *
from Imports.util_scan import *
#-----------------------------------------------------------------------------#
class App(ttk.Frame):
"""Class defining the Virtual Radio Interferometer application.
This class creates a root window used to set observation
parameters, choose and accumulate array configurations and load a
model image. A secondary Toplevel window is used to display the
input, output and intermediate Fourier transforms and images.
"""
def __init__(self, parent, bgColour=None, *args, **kwargs):
ttk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.bgColour=bgColour
self.parent.title("Friendly VRI: Control Window")
self.obsManager = None
# Set the grid expansion properties
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.rowconfigure(2, weight=1)
# Menu bar
self.menuBar = tk.Menu(self, background=self.bgColour)
self.fileMenu = tk.Menu(self.menuBar, tearoff=0)
self.fileMenu.add_command(label="Quit", command=self._applicationExit)
self.menuBar.add_cascade(label="File", menu=self.fileMenu)
self.helpMenu = tk.Menu(self.menuBar, tearoff=0)
self.helpMenu.add_command(label="Instructions",
command=lambda fileName="docs/HELP.txt",
title="Vriendly VRI Instructions" :
self._show_textfile(fileName, title))
self.helpMenu.add_command(label="About",
command=lambda fileName="docs/ABOUT.txt",
title="About Friendly VRI" :
self._show_textfile(fileName, title))
self.menuBar.add_cascade(label="Help", menu=self.helpMenu)
self.parent.config(menu=self.menuBar)
# Array selector interface
self.selector = ArraySelector(self, bgColour=self.bgColour)
self.selector.grid(column=0, row=0, padx=10, pady=5, sticky="EW")
sep = ttk.Separator(self, orient="horizontal")
sep.grid(column=0, row=1, padx=10, pady=5, sticky="EW")
# Observation settings
self.inputs = ObsInputs(self)
self.inputs.grid(column=0, row=2, padx=10, pady=5, sticky="EW")
sep = ttk.Separator(self, orient="horizontal")
sep.grid(column=0, row=3, padx=10, pady=5, sticky="EW")
# Status frame
self.statFrm = StatusFrame(self, bgColour=self.bgColour, boxWidth=22,
gapWidth=155)
self.statFrm.grid(column=0, row=4, padx=10, pady=5)
# Create the display window
self.dispWin = tk.Toplevel(self)
self.dispWin.title("Friendly VRI: Plot Window")
self.dispWin.protocol("WM_DELETE_WINDOW", self._applicationExit)
self.dispWin.columnconfigure(0, weight=1)
self.dispWin.rowconfigure(0, weight=1)
# Placeholder for the scan window
self.scanWin = None
# Draw the display interface
self.pltFrm = PlotFrame(self.dispWin, bgColour=self.bgColour)
self.pltFrm.grid(row=0, column=0, padx=0, pady=0, sticky="NSEW")
# Set focus to the main window and bring to the fore
self.focus_force()
self.lift()
# DEBUG
if False:
self.testWin = tk.Toplevel(self)
self.testWin.title(" TEST WINDOW ")
self.testWin.protocol("WM_DELETE_WINDOW", self._applicationExit)
self.testWin.resizable(True, True)
self.testWin.columnconfigure(0, weight=1)
self.testWin.rowconfigure(0, weight=1)
self.a = ObsInputs(self.testWin)
self.a.grid(row=0, column=0, padx=0, pady=0, sticky="NSEW")
# Load the back-end and populate the array configuration list
# The observationManager class can be used stand-alone from an
# iPython terminal and replicates the functionality of the GUI.
# The tkinter GUI serves as a controller for this class.
self.obsManager = observationManager(verbose=False, debug=False)
vals = self.obsManager.arrsAvailable.values()
configLst = zip([x["telescope"] for x in vals],
[x["config"] for x in vals])
self.selector.configInTab.insert_rows(configLst,
("Telescope", "Array"))
# Bind virtual events generated by the control widgets
self.parent.bind("<<config_in_selected>>",
lambda event : self._on_select_config(event))
self.parent.bind("<<selection_changed>>",
lambda event : self._on_sel_change(event))
self.parent.bind("<<obsparm_changed>>",
lambda event : self._on_obsparm_change(event))
self.parent.bind("<<pixscale_changed>>",
lambda event : self._on_pixscale_change(event))
self.parent.bind("<<plot_modFFT>>",
lambda event : self._on_plot_modFFT(event))
self.parent.bind("<<plot_uvcoverage>>",
lambda event : self._on_plot_uvcov(event))
self.parent.bind("<<plot_elevation>>",
lambda event : self._on_plot_elevation(event))
self.parent.bind("<<do_observation>>",
lambda event : self._on_do_observation(event))
self.parent.bind("<<show_results>>",
lambda event : self._on_show_results(event))
self.parent.bind("<<load_model_image>>",
lambda event : self._on_load_model(event))
self.parent.bind("<<show_scanwin>>",
lambda event : self._show_scanwin(event))
# Force a minimum size on the windows & set resize properties
self.parent.update()
self.parent.minsize(self.parent.winfo_width(),
self.parent.winfo_height())
self.parent.resizable(False, False)
self.dispWin.update()
self.dispWin.minsize(self.dispWin.winfo_width(),
self.dispWin.winfo_height())
self.dispWin.resizable(True, True)
def _applicationExit(self):
"""Exit the application cleanly if the window is closed."""
self.parent.destroy()
def _show_textfile(self, fileName, title=""):
"""Show a text file in a new window."""
self.helpWin = tk.Toplevel(self, background=self.bgColour)
self.helpWin.title(title)
self.helpTxt = tkScrolledText(self.helpWin, width=80,
font=fontFixed)
self.helpTxt.config(state="normal")
with open(fileName,'r') as f:
text = f.read()
self.helpTxt.insert('1.0', text)
self.helpTxt.config(state="disabled")
self.helpTxt.grid(column=0, row=0, padx=5, pady=5, sticky="NSEW")
self.closeBtn = ttk.Button(self.helpWin, text='Close',
command=self.helpWin.destroy)
self.closeBtn.grid(column=0, row=1, padx=5, pady=5, sticky="E")
self.helpWin.rowconfigure(0, weight=1)
self.helpWin.columnconfigure(0, weight=1)
def _show_lone_figure(self, fig, title="Plot Window"):
"""Show a matplotlib figure in a new window."""
self.figWin = tk.Toplevel(self, background=self.bgColour)
self.figWin.title(title)
figCanvas = FigureCanvasTkAgg(fig, master=self.figWin)
loneCan = figCanvas.get_tk_widget()
loneCan.configure(highlightthickness=0)
loneCan.configure(background=self.bgColour)
loneCan.grid(column=0, row=0, columnspan=2, padx=0, pady=0,
sticky="NSEW")
tbarFrm = ttk.Frame(self.figWin)
toolbar = MPLnavToolbar(figCanvas, tbarFrm)
tbarFrm.grid(column=0, row=1, padx=5, pady=5, sticky="W")
closeBtn = ttk.Button(self.figWin, text='Close',
command=self.figWin.destroy)
closeBtn.grid(column=1, row=1, padx=5, pady=5, sticky="E")
self.figWin.rowconfigure(0, weight=1)
self.figWin.columnconfigure(0, weight=1)
def _update_status(self):
"""Update the status of the user interface, including the checkbox
indicators, plot axes and information panels. The status of each step
is queried from the instance of the observationManager class."""
# Query the status and set the indicators
stateDict = self.obsManager.get_status()
self.statFrm.set_state_by_dict(stateDict)
# Clear the plots based on the status
self.pltFrm.clear_by_state(stateDict)
# Query the scales and update the information panel
parmDict = self.obsManager.get_scales()
self.pltFrm.infoPanel.update(parmDict)
# Force an update of the GUI
root.update()
# Event handlers bound to virtual events ---------------------------------#
def _on_select_config(self, event=None):
"""Plot the antenna layout for the selected array configuration"""
# Query the antenna parameters of the selected configuration
row = event.widget.get_indx_selected()
d = self.obsManager.get_array_params(row=row)
# Plot the antenna positions
self.selector.antPosPlot.load_data(d["x"]/1000.0, d["y"]/1000.0)
self.selector.antPosPlot.draw_zerolines()
self.selector.antPosPlot.set_xlabel("East-West (km)")
self.selector.antPosPlot.set_ylabel("North-South (km)")
# Show the antenna diameter and array latitude
text = "{:.1f} m".format(d["diameter_m"])
self.selector.antD_m.set(text)
text = u"{:.4f}\u00B0".format(d["latitude_deg"])
self.selector.antL_deg.set(text)
text = u"{:.3f} km".format(d["baseMin_m"]/1000.0)
self.selector.minBase_km.set(text)
text = u"{:.3f} km".format(d["baseMax_m"]/1000.0)
self.selector.maxBase_km.set(text)
def _on_sel_change(self, event=None):
"""When the arrays selected change in the GUI, refresh the observation
parameters in the observation manager."""
# Reset the common parameters
self.obsManager.set_obs_parms(self.inputs.freq_MHz.get(),
self.inputs.dec_deg.get())
# Reset the array and hour-angle selections
self.obsManager.clear_all_selections()
for selection in self.selector.configOutTab.get_all_text():
key = "_".join(selection[:2])
haStart = float(selection[2])
haEnd = float(selection[3])
sampRate = float(selection[4])
self.obsManager.select_array(key, haStart, haEnd, sampRate)
# Update the status
self._update_status()
def _on_obsparm_change(self, event=None):
"""When the observation parameters change in the GUI, reset the
calculations."""
# Reset the common parameters
try:
self.obsManager.set_obs_parms(float(self.inputs.freq_MHz.get()),
float(self.inputs.dec_deg.get()))
except Exception:
pass
# Update the status
self._update_status()
def _on_pixscale_change(self, event=None):
"""When the pixel scale is changed in the GUI, clear the FFT plot."""
# Only operate if a model is already loaded
stateDict = self.obsManager.get_status()
if not stateDict["statusModel"]:
return
# Reset the pixel scale
try:
pixScale_asec = float(self.inputs.pixScale_asec.get())
self.obsManager.set_pixscale(pixScale_asec)
except Exception:
self.inputs.extent.set("")
return
# Set the extent label in the load frame
pixScaleImg_deg = self.obsManager.pixScaleImg_asec / 3600.0
nX = self.obsManager.nX
nY = self.obsManager.nY
text = " %d x %d pix / %s x %s" % (nX, nY,
ang2str(nX * pixScaleImg_deg),
ang2str(nY * pixScaleImg_deg))
self.inputs.extent.set(text)
# Only update the status if this is the first change after processing
if stateDict["statusModelFFT"]:
self._update_status()
def _on_plot_modFFT(self, event=None):
"""Show the FFT of the model image."""
# Invert the model image
self.obsManager.invert_model()
# Plot the model FFT
parmDict = self.obsManager.get_scales()
lim_kl = parmDict["fftScale_lam"]/1e3
self.pltFrm.plot_fft("modelFFT", self.obsManager.modelFFTarr,
limit=lim_kl, title="Model FFT")
# Update the status
self._update_status()
def _on_plot_uvcov(self, event=None):
"""Plot the uv-coverage for all selected array configurations"""
# Calculate the uv-coverage for the selected observation parameters
self.obsManager.calc_uvcoverage()
# Plot the uv-coverage in the display window
self.pltFrm.plot_uvcov("uvCov", self.obsManager.arrsSelected,
title="uv-Coverage")
# Update the status
self._update_status()
def _on_plot_elevation(self, event=None):
"""Create a plot showing the elevation of the source as seen from
the currently selected telescopes."""
colLst=["r", "b", "g", "m", "c", "y", "k"]
# Query the selected array configurations
selTab = self.obsManager.get_selected_arrays()
if not selTab is None:
telescopeLst = set(selTab["telescope"])
else:
return
# Plot each of the elevation curves
fig = Figure(figsize=(7.5, 6), facecolor=bgColour)
ax = fig.add_subplot(111)
for i, e in enumerate(telescopeLst):
haArr_hr, elArr_deg = self.obsManager.calc_elevation_curve(e)
ax.plot(haArr_hr, elArr_deg, color=colLst[i%len(colLst)],
label=e.decode("utf-8"))
# Format labels and legend
ax.set_xlim(-12.0, 12.0)
ax.set_ylim(0.0, 90.0)
ax.set_xlabel("Hour Angle (hours)")
ax.set_ylabel("Elevation (degrees)")
ax.margins(0.02)
leg = ax.legend(shadow=False)
for t in leg.get_texts():
t.set_fontsize('small')
# Show the figure
if len(telescopeLst)>0:
self._show_lone_figure(fig, title="Elevation Plot")
def _on_load_model(self, event=None):
"""Load a model image into the observation manager"""
# Load the model image
modelFile = self.inputs.modelPath
pixScale_asec = self.inputs.pixScale_asec.get()
self.obsManager.load_model_image(modelFile, pixScale_asec)
# Set the extent label in the load frame
pixScaleImg_deg = self.obsManager.pixScaleImg_asec / 3600.0
nX = self.obsManager.nX
nY = self.obsManager.nY
text = " %d x %d pix / %s x %s" % (nX, nY,
ang2str(nX * pixScaleImg_deg),
ang2str(nY * pixScaleImg_deg))
self.inputs.extent.set(text)
# Plot the model image
self.pltFrm.plot_image("modelImg", self.obsManager.modelImgArr,
title="Model Image")
# Update the status
self._update_status()
def _on_do_observation(self, event=None):
"""Perform the bulk of the observing steps"""
# Calculate the uv-coverage if not cached
stateDict = self.obsManager.get_status()
if not stateDict['statusuvCalc']:
self.obsManager.calc_uvcoverage()
# Plot the uv-coverage
self.pltFrm.plot_uvcov("uvCov", self.obsManager.arrsSelected,
title="uv-Coverage")
# Update the status
self._update_status()
# Calculate the Fourier transform of the model if not cached
stateDict = self.obsManager.get_status()
if not stateDict['statusModelFFT']:
self.obsManager.invert_model()
# Plot the model FFT
parmDict = self.obsManager.get_scales()
lim_kl = parmDict["fftScale_lam"]/1e3
self.pltFrm.plot_fft("modelFFT", self.obsManager.modelFFTarr,
limit=lim_kl, title="Model FFT")
# Update the status
self._update_status()
# Grid the uv-coverage to make a mask
self.obsManager.grid_uvcoverage()
# Show the observed FFT
parmDict = self.obsManager.get_scales()
lim_kl = parmDict["fftScale_lam"]/1e3
self.pltFrm.plot_fft("obsFFT", self.obsManager.obsFFTarr, limit=lim_kl,
title="Observed FFT")
#self.pltFrm.plot_fft("obsFFT", self.obsManager.uvCntArr, limit=lim_kl,
# title="Observed FFT")
# Update the status
self._update_status()
# Calculate the PSF
self.obsManager.calc_beam()
# Show the synthesised beam
self.pltFrm.plot_image("beam", np.abs(self.obsManager.beamArr),
title="Synthesised Beam", pRng=(-0.1, 0.5))
# Update the status
self._update_status()
# Invert the observed FFT
self.obsManager.invert_observation()
# Show the observed image
self.pltFrm.plot_image("obsImg", np.abs(self.obsManager.obsImgArr),
title="Observed Image")
# Update the status
self._update_status()
def _on_show_results(self, event=None):
"""Raise the focus of the plotting window."""
self.dispWin.focus_force()
self.dispWin.lift()
def _show_scanwin(self, event=None):
exists=0
try:
exists = self.scanWin.winfo_exists()
except Exception:
pass
if exists:
self.scanWin.focus_force()
self.scanWin.lift()
else:
self.scanWin = tk.Toplevel(self, background=self.bgColour)
self.scanWin.title("Friendly VRI: Array Scanner Window")
self.scanWin.resizable(True, True)
self.scanWin.columnconfigure(0, weight=1)
self.scanWin.rowconfigure(0, weight=1)
self.scanner = ArrayScanner(self.scanWin)
self.scanner.grid(row=0, column=0, padx=0, pady=0, sticky="NSEW")
self.scanWin.bind("<<array_scanned>>",
lambda event : self._on_scan_array(event))
def _on_scan_array(self, event=None):
"""Load the latest scan of the antenna plate."""
# Load the custom array file into the observation manager
tmpFile = "arrays/custom.config"
self.obsManager._load_one_array(tmpFile)
# Append to the list of available array configurations
vals = list(self.obsManager.arrsAvailable.values())[-1]
configLst = zip([vals["telescope"]],
[vals["config"]])
self.selector.configInTab.insert_rows(configLst,
("Telescope", "Array"))
# Clean up
os.remove(tmpFile)
#-----------------------------------------------------------------------------#
class ArraySelector(ttk.Frame):
"""Two multi-column listboxes an hour-angle slider and a 'Select' button
that make up the array selection interface."""
def __init__(self, parent, bgColour=None, *args, **kwargs):
ttk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
if bgColour is None:
bgColour = ttk.Style().lookup("TFrame", "background")
# Set the expansion properties
self.columnconfigure(4, weight=10)
self.columnconfigure(6, weight=1)
self.columnconfigure(7, weight=20)
self.columnconfigure(8, weight=20)
self.rowconfigure(2, weight=1)
self.rowconfigure(3, weight=1)
self.rowconfigure(4, weight=1)
# Scatter plot of antenna locations
self.antPosPlot = ScatterPlot(self, width=340, height=300,
axPad=(100,25,70,25), aspect="equal",
pntSize=2.5)
self.antPosPlot.grid(column=0, row=0, columnspan=4, rowspan=6,
padx=5, pady=5)
txt = "To begin, select an array configuration\n"
txt += "from the table and click the 'Add' button.\n\n"
txt += "Then load a model image\nand click 'Do Observation'."
self.antPosPlot.display_message(txt)
# Antenna Diameter and array latitude labels
self.antDlab = ttk.Label(self, text=u"Antenna \u0398: ")
self.antDlab.grid(column=0, row=6, padx=0, pady=0, sticky="E")
self.antD_m = tk.StringVar()
self.antDval = ttk.Label(self, textvariable=self.antD_m)
self.antDval.grid(column=1, row=6, padx=0, pady=0, sticky="W")
self.antLlab = ttk.Label(self, text=u"Telescope \u03c6: ")
self.antLlab.grid(column=0, row=7, padx=0, pady=0, sticky="E")
self.antL_deg = tk.StringVar()
self.antLval = ttk.Label(self, textvariable=self.antL_deg)
self.antLval.grid(column=1, row=7, padx=0, pady=0, sticky="W")
# Minimum and maximum baseline labels
self.minBaseLab = ttk.Label(self, text=u"Min Baseline: ")
self.minBaseLab.grid(column=3, row=6, padx=0, pady=0, sticky="E")
self.minBase_km = tk.StringVar()
self.minBaseVal = ttk.Label(self, textvariable=self.minBase_km)
self.minBaseVal.grid(column=4, row=6, padx=0, pady=0, sticky="W")
self.maxBaseLab = ttk.Label(self, text=u"Max Baseline: ")
self.maxBaseLab.grid(column=3, row=7, padx=0, pady=0, sticky="E")
self.maxBase_km = tk.StringVar()
self.maxBaseVal = ttk.Label(self, textvariable=self.maxBase_km )
self.maxBaseVal.grid(column=4, row=7, padx=0, pady=0, sticky="W")
# Listbox showing the available array configurations
self.configInTab = ScrolledTreeTab(self,
virtEvent="<<config_in_selected>>")
self.configInTab.name_columns(("Telescope", "Array"))
self.configInTab.grid(column=4, row=0, columnspan=1, rowspan=5,
padx=5, pady=5, sticky="NSEW")
# Scan array button
self.scanBtn = ttk.Button(self, text="Scan Array Model", width=20,
command=lambda: self.event_generate("<<show_scanwin>>"))
self.scanBtn.grid(column=4, row=5, columnspan=1,
padx=5, pady=5, sticky="EW" )
# Hour angle slider
self.haLab = ttk.Label(self, text="Hour Angle Range (hours):")
self.haLab.grid(column=5, row=0, columnspan=2, padx=0, pady=5,
sticky="NW")
self.haScale = DoubleScale(self, from_=-12.0, to=12.0,
initLeft=-1.0, initRight=+1.0,
tickIntMajor=6, tickIntMinor=1, width=270)
self.haScale.grid(column=5, row=1, columnspan=2, padx=0, pady=5,
sticky="N")
# Sampling cadence
self.sampRtLab = ttk.Label(self, text="Sampling Cadence (s):")
self.sampRtLab.grid(column=5, row=2, padx=5, pady=5, sticky="E")
sampRtLst_s = ["10", "30", "60", "100", "300", "600", "1200", "1800",
"3600"]
self.sampRt_s = tk.StringVar()
self.sampRtComb = ttk.Combobox(self, state="readonly",
textvariable=self.sampRt_s,
values=sampRtLst_s, width=5)
self.sampRtComb.current(4)
self.sampRtComb.grid(column=6, row=2, padx=5, pady=5, sticky="EW")
# Fancy add button with strike-through arrow
self.canvas = tk.Canvas(self, width=270, height=30,
background=bgColour, highlightthickness=0)
self.canvas.create_line(10,15,260,15, width=2, arrow=tk.LAST,
arrowshape=(10,15,5), fill="black")
self.addBtn = ttk.Button(self, text="Add", width=10,
command=self._handler_add_button)
self.canvas.create_window(135, 15, window=self.addBtn)
self.canvas.grid(column=5, row=3, columnspan=2, padx=0, pady=5)
# Listbox showing the selected array configurations
self.configOutTab = ScrolledTreeTab(self,
virtEvent="<<config_out_selected>>")
self.configOutTab.name_columns(("Telescope", " Array ",
"HA-Start", " HA-End ", "Cadence"))
self.configOutTab.grid(column=7, row=0, columnspan=2, rowspan=6,
padx=5, pady=5, sticky="NSEW")
# Delete and plot elevation buttons
self.delBtn = ttk.Button(self, text="Clear Selected", width=20,
command=self._handler_clear_button)
self.delBtn.grid(column=7, row=6, padx=5, pady=5, sticky="EW" )
self.delAllBtn = ttk.Button(self, text="Clear All", width=20,
command=self._handler_clear_all_button)
self.delAllBtn.grid(column=8, row=6, padx=5, pady=5, sticky="EW" )
self.plotElBtn = ttk.Button(self, text="Plot Elevation", width=20,
command=lambda: self.event_generate("<<plot_elevation>>"))
self.plotElBtn.grid(column=7, row=7, columnspan=2, padx=5, pady=5,
sticky="EW" )
def _handler_add_button(self):
"""Add the selected configuration to the list box"""
selConf = self.configInTab.get_text_selected()
if selConf is not None:
selConf = list(selConf)
selConf.append(self.haScale.valueLeft.get())
selConf.append(self.haScale.valueRight.get())
selConf.append(self.sampRt_s.get())
self.configOutTab.insert_rows(
[selConf], ("Telescope", " Array ", "HA-Start", " HA-End ",
"Cadence"))
prevAddedLst = self.configOutTab.get_all_text()
self.event_generate("<<selection_changed>>")
def _handler_clear_button(self):
"""Delete the selected configuration from the list box"""
if self.configOutTab.clear_selected():
self.event_generate("<<selection_changed>>")
def _handler_clear_all_button(self):
"""Delete all configurations from the list box"""
self.configOutTab.clear_entries()
self.event_generate("<<selection_changed>>")
#-----------------------------------------------------------------------------#
class ArrayScanner(ttk.Frame):
"""Interface to scan the physical model of the array using webcam 2."""
def __init__(self, parent, bgColour=None, *args, **kwargs):
ttk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
if bgColour is None:
bgColour = ttk.Style().lookup("TFrame", "background")
self.X_m = None
self.Y_m = None
self.shape = None
self.doFlat = None
# Set the expansion properties
self.columnconfigure(1, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
# Scanner settings
self.scanFrm = ttk.Labelframe(self, text=" Scanner Settings ")
self.scanFrm.grid(column=0, row=0, padx=5, pady=5, sticky="NSEW")
# Resolution
self.resLab = ttk.Label(self.scanFrm, text="Resolution:")
self.resLab.grid(column=0, row=1, padx=5, pady=5, sticky="E")
self.resX = tk.StringVar()
self.resY = tk.StringVar()
self.resX.set("1280")
self.resY.set("800")
self.resXEnt = ttk.Entry(self.scanFrm, width=5,
textvariable=self.resX)
self.resXEnt.grid(column=1, row=1, padx=5, pady=5, sticky="EW")
self.resYEnt = ttk.Entry(self.scanFrm, width=5,
textvariable=self.resY)
self.resYEnt.grid(column=2, row=1, padx=5, pady=5, sticky="EW")
# Crop size
self.cropLab = ttk.Label(self.scanFrm, text="Crop Size:")
self.cropLab.grid(column=0, row=2, padx=5, pady=5, sticky="E")
self.cropX = tk.StringVar()
self.cropY = tk.StringVar()
self.cropX.set("40")
self.cropY.set("40")
self.cropXEnt = ttk.Entry(self.scanFrm, width=5,
textvariable=self.cropX)
self.cropXEnt.grid(column=1, row=2, padx=5, pady=5, sticky="EW")
self.cropYEnt = ttk.Entry(self.scanFrm, width=5,
textvariable=self.cropY)
self.cropYEnt.grid(column=2, row=2, padx=5, pady=5, sticky="EW")
# Smoothing kernel
self.kernLab = ttk.Label(self.scanFrm, text="Kernel Size:")
self.kernLab.grid(column=0, row=3, padx=5, pady=5, sticky="E")
self.kernSize = tk.StringVar()
self.kernSize.set("51")
self.kernEnt = ttk.Entry(self.scanFrm, width=5,
textvariable=self.kernSize)
self.kernEnt.grid(column=1, row=3, columnspan=2, padx=5, pady=5,
sticky="EW")
# Dettection threshold
self.sigmaLab = ttk.Label(self.scanFrm, text="Threshold (sigma):")
self.sigmaLab.grid(column=0, row=4, padx=5, pady=5, sticky="E")
self.sigma = tk.StringVar()
self.sigma.set("3")
self.sigmaEnt = ttk.Entry(self.scanFrm, width=5,
textvariable=self.sigma)
self.sigmaEnt.grid(column=1, row=4, columnspan=2, padx=5, pady=5,
sticky="EW")
# Min number pixels in island
self.minPixLab = ttk.Label(self.scanFrm, text="Min # Pixels:")
self.minPixLab.grid(column=0, row=5, padx=5, pady=5, sticky="E")
self.minPix = tk.StringVar()
self.minPix.set("100")
self.minPixEnt = ttk.Entry(self.scanFrm, width=5,
textvariable=self.minPix)
self.minPixEnt.grid(column=1, row=5, columnspan=2, padx=5, pady=5,
sticky="EW")
# Flat Field button
self.flatBtn = ttk.Button(self.scanFrm, text="Flat Field", width=20,
command=self._handler_flat_button)
# self.flatBtn.grid(column=0, row=6, columnspan=3, padx=5, pady=5,
# sticky="SEW" )
# Scan button
self.scanBtn = ttk.Button(self.scanFrm, text="Scan Array", width=20,
command=self._handler_scan_button)
self.scanBtn.grid(column=0, row=7, columnspan=3, padx=5, pady=5,
sticky="SEW" )
self.scanFrm.columnconfigure(0, weight=1)
self.scanFrm.rowconfigure(6, weight=1)
# Array settings
self.arrFrm = ttk.Labelframe(self, text=" Custom Array Settings ")
self.arrFrm.grid(column=0, row=1, padx=5, pady=5, sticky="NSEW")
# Telescope name
self.myScopeLab = ttk.Label(self.arrFrm, text="Telescope Name:")
self.myScopeLab.grid(column=0, row=0, padx=5, pady=5, sticky="E")
self.myScope = tk.StringVar()
self.myScope.set("Custom_1")
self.myScopeEnt = ttk.Entry(self.arrFrm, width=20, state="disabled",
textvariable=self.myScope)
self.myScopeEnt.grid(column=1, row=0, padx=5, pady=5, sticky="EW")
# Array config
self.myArrayLab = ttk.Label(self.arrFrm, text="Array Name:")
self.myArrayLab.grid(column=0, row=1, padx=5, pady=5, sticky="E")
self.myArray = tk.StringVar()
self.myArray.set("Array")
self.myArrayEnt = ttk.Entry(self.arrFrm, width=10,
textvariable=self.myArray)
self.myArrayEnt.grid(column=1, row=1, padx=5, pady=5, sticky="EW")
# Latitude
self.myLatLab = ttk.Label(self.arrFrm, text="Latitude (deg):")
self.myLatLab.grid(column=0, row=2, padx=5, pady=5, sticky="E")
latLst = [str(x) for x in range(90, -91, -10)]
self.myLat = tk.StringVar()
self.myLatComb = ttk.Combobox(self.arrFrm, textvariable=self.myLat,
values=latLst, width=10)
self.myLatComb.current(11)
self.myLatComb.grid(column=1, row=2, padx=5, pady=5, sticky="EW")
# Antenna diameter
self.myAntDiamLab = ttk.Label(self.arrFrm, text=u"Antenna \u0398 (m):")
self.myAntDiamLab.grid(column=0, row=3, padx=5, pady=5, sticky="E")
dLst = ["22"]
self.myAntDiam = tk.StringVar()
self.myAntDiamComb = ttk.Combobox(self.arrFrm, width=12, values=dLst,
textvariable=self.myAntDiam)
self.myAntDiamComb.current(0)
self.myAntDiamComb.grid(column=1, row=3, padx=5, pady=5, sticky="EW")
# Plate scale
self.plateScaleLab = ttk.Label(self.arrFrm, text=u"Array Scale (m):")
self.plateScaleLab.grid(column=0, row=4, padx=5, pady=5, sticky="E")
self.plateScale = tk.StringVar()
self.plateScale.set("2000.0")
self.plateScaleEnt = ttk.Entry(self.arrFrm, width=12,
textvariable=self.plateScale)
self.plateScaleEnt.grid(column=1, row=4, padx=5, pady=5, sticky="EW")
# Save button
self.saveBtn = ttk.Button(self.arrFrm, text="Save Array", width=20,
command=self._handler_save_button)
self.saveBtn.configure(state="disabled")
self.saveBtn.grid(column=0, row=5, columnspan=2, padx=5, pady=5,
sticky="SEW" )
# Show control window
self.showBtn = ttk.Button(self.arrFrm, text = "Show Control Window",
width=20, command=self._show_control_window)
self.showBtn.grid(column=0, row=6, columnspan=3, padx=5, pady=5,
sticky="SEW")
self.arrFrm.columnconfigure(0, weight=1)
self.arrFrm.rowconfigure(5, weight=1)
# Figure showing the scan of the antenna models
self.fig = Figure(figsize=(8.0, 7.0), facecolor=bgColour)
self.figCanvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas = self.figCanvas.get_tk_widget()
self.canvas.configure(highlightthickness=0)
self.canvas.configure(background=bgColour)
self.canvas.grid(column=1, row=0, columnspan=1, rowspan=2,
padx=0, pady=0, sticky="NSEW")
self.ax = self.fig.add_subplot(111)
plt.setp(self.ax.get_yticklabels(), visible=False)
plt.setp(self.ax.get_xticklabels(), visible=False)
def _handler_scan_button(self):
# Capture an image of the array via webcam 2
cam = cv2.VideoCapture()
cam.open(1)
#cam.open(0)
cam.set(3, int(self.resX.get()))
cam.set(4, int(self.resX.get()))
for i in range(10):
success, img = cam.read()
cam.release()
if success:
# Resize the image to make it easier to manage
img = cv2.resize(img, (0,0), fx=0.5, fy=0.5)
# Save scan to a png file
cv2.imwrite("arrays/scan.png", img)
# Detect the islands in the image
imgName = "arrays/scan.png"
if self.doFlat:
flatImgName = "arrays/scan.png"
else:
flatImgName = None
self.X_m, self.Y_m, self.shape = \
scan_to_pixcoords("arrays/scan.png",
eSize=float(self.kernSize.get()),
threshold_sigma=float(self.sigma.get()),
minPix=int(self.minPix.get()),
cropX=img.shape[1]-int(self.cropX.get()),
cropY=img.shape[0]-int(self.cropY.get()),
flatImgName = flatImgName,
ax=self.ax)
# Show the scanned figure and allow saving
self.figCanvas.draw()
# Enable/disable saving
if len(self.X_m)>0:
self.saveBtn.configure(state="enabled")
else:
self.saveBtn.configure(state="disabled")
def _handler_flat_button(self):
# Capture an image of the array via webcam 2
cam = cv2.VideoCapture()
cam.open(1)
cam.set(3, int(self.resX.get()))
cam.set(4, int(self.resX.get()))
for i in range(10):
success, img = cam.read()
cam.release()
if success:
# Resize the image to make it easier to manage
img = cv2.resize(img, (0,0), fx=0.5, fy=0.5)
# Save scan to a png file
cv2.imwrite("arrays/flat.png", img)
self.doFlat = True
def _handler_save_button(self):
# Write a temporary array definition file
tmpFile = "arrays/custom.config"
write_arrayfile(tmpFile,
X_m=self.X_m,
Y_m=self.Y_m,
Nx=self.shape[-1],
Ny=self.shape[-2],
scale_m=float(self.plateScale.get()),
telescope=self.myScope.get(),
config=self.myArray.get(),
latitude_deg=float(self.myLat.get()),
diameter_m=float(self.myAntDiam.get()))
# Increment the number of the telescope
pre, i = self.myScope.get().rsplit("_")
self.myScope.set(pre + "_" + str(int(i)+1))
self.event_generate("<<array_scanned>>")
def _show_control_window(self):
"""Set focus back to the main control window."""
root.focus_force()