Added --notch_taps to allow user to specify number of taps in notch filter
[debian/gnuradio] / gr-radio-astronomy / src / python / usrp_ra_receiver.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2004,2005,2007 Free Software Foundation, Inc.
4
5 # This file is part of GNU Radio
6
7 # GNU Radio is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3, or (at your option)
10 # any later version.
11
12 # GNU Radio is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with GNU Radio; see the file COPYING.  If not, write to
19 # the Free Software Foundation, Inc., 51 Franklin Street,
20 # Boston, MA 02110-1301, USA.
21
22
23 from gnuradio import gr, gru
24 from gnuradio import usrp
25 from usrpm import usrp_dbid
26 from gnuradio import eng_notation
27 from gnuradio.eng_option import eng_option
28 from gnuradio.wxgui import stdgui2, ra_fftsink, ra_stripchartsink, ra_waterfallsink, form, slider
29 from optparse import OptionParser
30 import wx
31 import sys
32 import Numeric 
33 import time
34 import numpy.fft
35 import ephem
36
37 class app_flow_graph(stdgui2.std_top_block):
38         def __init__(self, frame, panel, vbox, argv):
39                 stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)
40
41                 self.frame = frame
42                 self.panel = panel
43                 
44                 parser = OptionParser(option_class=eng_option)
45                 parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0, 0),
46                         help="select USRP Rx side A or B (default=A)")
47                 parser.add_option("-d", "--decim", type="int", default=16,
48                         help="set fgpa decimation rate to DECIM [default=%default]")
49                 parser.add_option("-f", "--freq", type="eng_float", default=None,
50                         help="set frequency to FREQ", metavar="FREQ")
51                 parser.add_option("-a", "--avg", type="eng_float", default=1.0,
52                         help="set spectral averaging alpha")
53                 parser.add_option("-i", "--integ", type="eng_float", default=1.0,
54                         help="set integration time")
55                 parser.add_option("-g", "--gain", type="eng_float", default=None,
56                         help="set gain in dB (default is midpoint)")
57                 parser.add_option("-l", "--reflevel", type="eng_float", default=30.0,
58                         help="Set Total power reference level")
59                 parser.add_option("-y", "--division", type="eng_float", default=0.5,
60                         help="Set Total power Y division size")
61                 parser.add_option("-e", "--longitude", type="eng_float", default=-76.02,help="Set Observer Longitude")
62                 parser.add_option("-c", "--latitude", type="eng_float", default=44.85,help="Set Observer Latitude")
63                 parser.add_option("-o", "--observing", type="eng_float", default=0.0,
64                         help="Set observing frequency")
65                 parser.add_option("-x", "--ylabel", default="dB", help="Y axis label") 
66                 parser.add_option("-z", "--divbase", type="eng_float", default=0.025, help="Y Division increment base") 
67                 parser.add_option("-v", "--stripsize", type="eng_float", default=2400, help="Size of stripchart, in 2Hz samples") 
68                 parser.add_option("-F", "--fft_size", type="eng_float", default=1024, help="Size of FFT")
69                 parser.add_option("-N", "--decln", type="eng_float", default=999.99, help="Observing declination")
70                 parser.add_option("-X", "--prefix", default="./")
71                 parser.add_option("-M", "--fft_rate", type="eng_float", default=8.0, help="FFT Rate")
72                 parser.add_option("-A", "--calib_coeff", type="eng_float", default=1.0, help="Calibration coefficient")
73                 parser.add_option("-B", "--calib_offset", type="eng_float", default=0.0, help="Calibration coefficient")
74                 parser.add_option("-W", "--waterfall", action="store_true", default=False, help="Use Waterfall FFT display")
75                 parser.add_option("-S", "--setimode", action="store_true", default=False, help="Enable SETI processing of spectral data")
76                 parser.add_option("-K", "--setik", type="eng_float", default=1.5, help="K value for SETI analysis")
77                 parser.add_option("-T", "--setibandwidth", type="eng_float", default=12500, help="Instantaneous SETI observing bandwidth--must be divisor of 250Khz")
78                 parser.add_option("-Q", "--seti_range", type="eng_float", default=1.0e6, help="Total scan width, in Hz for SETI scans")
79                 parser.add_option("-Z", "--dual_mode", action="store_true",
80                         default=False, help="Dual-polarization mode")
81                 parser.add_option("-I", "--interferometer", action="store_true", default=False, help="Interferometer mode")
82                 parser.add_option("-D", "--switch_mode", action="store_true", default=False, help="Dicke Switching mode")
83                 parser.add_option("-P", "--reference_divisor", type="eng_float", default=1.0, help="Reference Divisor")
84                 parser.add_option("-U", "--ref_fifo", default="@@@@")
85                 parser.add_option("-h", "--notch_taps", type="int", default=64, help="Number of notch taps")
86                 parser.add_option("-n", "--notches", action="store_true", 
87                     default=False, help="Notch frequencies after all other args")
88                 (options, args) = parser.parse_args()
89
90                 self.setimode = options.setimode
91                 self.dual_mode = options.dual_mode
92                 self.interferometer = options.interferometer
93                 self.normal_mode = False
94                 self.switch_mode = options.switch_mode
95                 self.switch_state = 0
96                 self.reference_divisor = options.reference_divisor
97                 self.ref_fifo = options.ref_fifo
98                 
99                 self.NOTCH_TAPS = options.notch_taps
100                 self.notches = Numeric.zeros(self.NOTCH_TAPS,Numeric.Float64)
101                 # Get notch locations
102                 j = 0
103                 for i in args:
104                         self.notches[j] = float(i)
105                         j = j + 1
106                 
107                 self.use_notches = options.notches
108                 
109                 if (self.ref_fifo != "@@@@"):
110                         self.ref_fifo_file = open (self.ref_fifo, "w")
111                 
112                 modecount = 0
113                 for modes in (self.dual_mode, self.interferometer):
114                         if (modes == True):
115                                 modecount = modecount + 1
116                                 
117                 if (modecount > 1):
118                         print "must select only 1 of --dual_mode, or --interferometer"
119                         sys.exit(1)
120                         
121                 self.chartneeded = True
122                 
123                 if (self.setimode == True):
124                         self.chartneeded = False
125                         
126                 if (self.setimode == True and self.interferometer == True):
127                         print "can't pick both --setimode and --interferometer"
128                         sys.exit(1)
129                         
130                 if (self.setimode == True and self.switch_mode == True):
131                         print "can't pick both --setimode and --switch_mode"
132                         sys.exit(1)
133                 
134                 if (self.interferometer == True and self.switch_mode == True):
135                         print "can't pick both --interferometer and --switch_mode"
136                         sys.exit(1)
137                 
138                 if (modecount == 0):
139                         self.normal_mode = True
140
141                 self.show_debug_info = True
142                 
143                 # Pick up waterfall option
144                 self.waterfall = options.waterfall
145
146                 # SETI mode stuff
147                 self.setimode = options.setimode
148                 self.seticounter = 0
149                 self.setik = options.setik
150                 self.seti_fft_bandwidth = int(options.setibandwidth)
151
152                 # Calculate binwidth
153                 binwidth = self.seti_fft_bandwidth / options.fft_size
154
155                 # Use binwidth, and knowledge of likely chirp rates to set reasonable
156                 #  values for SETI analysis code.       We assume that SETI signals will
157                 #  chirp at somewhere between 0.10Hz/sec and 0.25Hz/sec.
158                 #
159                 # upper_limit is the "worst case"--that is, the case for which we have
160                 #  to wait the longest to actually see any drift, due to the quantizing
161                 #  on FFT bins.
162                 upper_limit = binwidth / 0.10
163                 self.setitimer = int(upper_limit * 2.00)
164                 self.scanning = True
165
166                 # Calculate the CHIRP values based on Hz/sec
167                 self.CHIRP_LOWER = 0.10 * self.setitimer
168                 self.CHIRP_UPPER = 0.25 * self.setitimer
169
170                 # Reset hit counters to 0
171                 self.hitcounter = 0
172                 self.s1hitcounter = 0
173                 self.s2hitcounter = 0
174                 self.avgdelta = 0
175                 # We scan through 2Mhz of bandwidth around the chosen center freq
176                 self.seti_freq_range = options.seti_range
177                 # Calculate lower edge
178                 self.setifreq_lower = options.freq - (self.seti_freq_range/2)
179                 self.setifreq_current = options.freq
180                 # Calculate upper edge
181                 self.setifreq_upper = options.freq + (self.seti_freq_range/2)
182
183                 # Maximum "hits" in a line
184                 self.nhits = 20
185
186                 # Number of lines for analysis
187                 self.nhitlines = 4
188
189                 # We change center frequencies based on nhitlines and setitimer
190                 self.setifreq_timer = self.setitimer * (self.nhitlines * 5)
191
192                 # Create actual timer
193                 self.seti_then = time.time()
194
195                 # The hits recording array
196                 self.hits_array = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
197                 self.hit_intensities = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
198                 # Calibration coefficient and offset
199                 self.calib_coeff = options.calib_coeff
200                 self.calib_offset = options.calib_offset
201                 if self.calib_offset < -750:
202                         self.calib_offset = -750
203                 if self.calib_offset > 750:
204                         self.calib_offset = 750
205
206                 if self.calib_coeff < 1:
207                         self.calib_coeff = 1
208                 if self.calib_coeff > 100:
209                         self.calib_coeff = 100
210
211                 self.integ = options.integ
212                 self.avg_alpha = options.avg
213                 self.gain = options.gain
214                 self.decln = options.decln
215
216                 # Set initial values for datalogging timed-output
217                 self.continuum_then = time.time()
218                 self.spectral_then = time.time()
219                 
220           
221                 # build the graph
222
223                 self.subdev = [(0, 0), (0,0)]
224                 
225                 #
226                 # If SETI mode, we always run at maximum USRP decimation
227                 #
228                 if (self.setimode):
229                         options.decim = 256
230
231                 if (self.dual_mode == False and self.interferometer == False):
232                         self.u = usrp.source_c(decim_rate=options.decim,fusb_block_size=8192)
233                         self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
234                         # determine the daughterboard subdevice we're using
235                         self.subdev[0] = usrp.selected_subdev(self.u, options.rx_subdev_spec)
236                         self.subdev[1] = self.subdev[0]
237                         self.cardtype = self.subdev[0].dbid()
238                 else:
239                         self.u=usrp.source_c(decim_rate=options.decim, nchan=2,fusb_block_size=8192)
240                         self.subdev[0] = usrp.selected_subdev(self.u, (0, 0))
241                         self.subdev[1] = usrp.selected_subdev(self.u, (1, 0))
242                         self.cardtype = self.subdev[0].dbid()
243                         self.u.set_mux(0x32103210)
244                         c1 = self.subdev[0].name()
245                         c2 = self.subdev[1].name()
246                         if (c1 != c2):
247                                 print "Must have identical cardtypes for --dual_mode or --interferometer"
248                                 sys.exit(1)
249                 #
250                 # Set 8-bit mode
251                 #
252                 width = 8
253                 shift = 8
254                 format = self.u.make_format(width, shift)
255                 r = self.u.set_format(format)
256                 
257                 # Set initial declination
258                 self.decln = options.decln
259
260                 input_rate = self.u.adc_freq() / self.u.decim_rate()
261                 self.bw = input_rate
262                 #
263                 # Set prefix for data files
264                 #
265                 self.prefix = options.prefix
266
267                 #
268                 # The lower this number, the fewer sample frames are dropped
269                 #  in computing the FFT.  A sampled approach is taken to
270                 #  computing the FFT of the incoming data, which reduces
271                 #  sensitivity.  Increasing sensitivity inreases CPU loading.
272                 #
273                 self.fft_rate = options.fft_rate
274
275                 self.fft_size = int(options.fft_size)
276
277                 # This buffer is used to remember the most-recent FFT display
278                 #       values.  Used later by self.write_spectral_data() to write
279                 #       spectral data to datalogging files, and by the SETI analysis
280                 #       function.
281                 #
282                 self.fft_outbuf = Numeric.zeros(self.fft_size, Numeric.Float64)
283
284                 #
285                 # If SETI mode, only look at seti_fft_bandwidth
286                 #       at a time.
287                 #
288                 if (self.setimode):
289                         self.fft_input_rate = self.seti_fft_bandwidth
290
291                         #
292                         # Build a decimating bandpass filter
293                         #
294                         self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
295                            input_rate,
296                            -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
297                            gr.firdes.WIN_HAMMING, 0)
298
299                         #
300                         # Compute required decimation factor
301                         #
302                         decimation = int(input_rate/self.fft_input_rate)
303                         self.fft_bandpass = gr.fir_filter_ccc (decimation, 
304                                 self.fft_input_taps)
305                 else:
306                         self.fft_input_rate = input_rate
307
308                 # Set up FFT display
309                 if self.waterfall == False:
310                    self.scope = ra_fftsink.ra_fft_sink_c (panel, 
311                            fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
312                            fft_rate=int(self.fft_rate), title="Spectral",  
313                            ofunc=self.fft_outfunc, xydfunc=self.xydfunc)
314                 else:
315                         self.scope = ra_waterfallsink.waterfall_sink_c (panel,
316                                 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
317                                 fft_rate=int(self.fft_rate), title="Spectral", ofunc=self.fft_outfunc, size=(1100, 600), xydfunc=self.xydfunc, ref_level=0, span=10)
318
319                 # Set up ephemeris data
320                 self.locality = ephem.Observer()
321                 self.locality.long = str(options.longitude)
322                 self.locality.lat = str(options.latitude)
323                 
324                 # We make notes about Sunset/Sunrise in Continuum log files
325                 self.sun = ephem.Sun()
326                 self.sunstate = "??"
327
328                 # Set up stripchart display
329                 tit = "Continuum"
330                 if (self.dual_mode != False):
331                         tit = "H+V Continuum"
332                 if (self.interferometer != False):
333                         tit = "East x West Correlation"
334                 self.stripsize = int(options.stripsize)
335                 if self.chartneeded == True:
336                         self.chart = ra_stripchartsink.stripchart_sink_f (panel,
337                                 stripsize=self.stripsize,
338                                 title=tit,
339                                 xlabel="LMST Offset (Seconds)",
340                                 scaling=1.0, ylabel=options.ylabel,
341                                 divbase=options.divbase)
342
343                 # Set center frequency
344                 self.centerfreq = options.freq
345
346                 # Set observing frequency (might be different from actual programmed
347                 #        RF frequency)
348                 if options.observing == 0.0:
349                         self.observing = options.freq
350                 else:
351                         self.observing = options.observing
352
353                 # Remember our input bandwidth
354                 self.bw = input_rate
355                 
356                 #
357                 # 
358                 # The strip chart is fed at a constant 1Hz rate
359                 #
360
361                 #
362                 # Call constructors for receive chains
363                 #
364                 
365                 if (self.dual_mode == True):
366                         self.setup_dual (self.setimode)
367                         
368                 if (self.interferometer == True):
369                         self.setup_interferometer(self.setimode)
370                                 
371                 if (self.normal_mode == True):
372                         self.setup_normal(self.setimode)
373                         
374                 if (self.setimode == True):
375                         self.setup_seti()
376
377                 self._build_gui(vbox)
378
379                 # Make GUI agree with command-line
380                 self.integ = options.integ
381                 if self.setimode == False:
382                         self.myform['integration'].set_value(int(options.integ))
383                         self.myform['offset'].set_value(self.calib_offset)
384                         self.myform['dcgain'].set_value(self.calib_coeff)
385                 self.myform['average'].set_value(int(options.avg))
386
387
388                 if self.setimode == False:
389                         # Make integrator agree with command line
390                         self.set_integration(int(options.integ))
391
392                 self.avg_alpha = options.avg
393
394                 # Make spectral averager agree with command line
395                 if options.avg != 1.0:
396                         self.scope.set_avg_alpha(float(1.0/options.avg))
397                         self.scope.set_average(True)
398
399                 if self.setimode == False:
400                         # Set division size
401                         self.chart.set_y_per_div(options.division)
402                         # Set reference(MAX) level
403                         self.chart.set_ref_level(options.reflevel)
404
405                 # set initial values
406
407                 if options.gain is None:
408                         # if no gain was specified, use the mid-point in dB
409                         g = self.subdev[0].gain_range()
410                         options.gain = float(g[0]+g[1])/2
411
412                 if options.freq is None:
413                         # if no freq was specified, use the mid-point
414                         r = self.subdev[0].freq_range()
415                         options.freq = float(r[0]+r[1])/2
416
417                 # Set the initial gain control
418                 self.set_gain(options.gain)
419
420                 if not(self.set_freq(options.freq)):
421                         self._set_status_msg("Failed to set initial frequency")
422
423                 # Set declination
424                 self.set_decln (self.decln)
425
426
427                 # RF hardware information
428                 self.myform['decim'].set_value(self.u.decim_rate())
429                 self.myform['USB BW'].set_value(self.u.adc_freq() / self.u.decim_rate())
430                 if (self.dual_mode == True):
431                         self.myform['dbname'].set_value(self.subdev[0].name()+'/'+self.subdev[1].name())
432                 else:
433                         self.myform['dbname'].set_value(self.subdev[0].name())
434
435                 # Set analog baseband filtering, if DBS_RX
436                 if self.cardtype in (usrp_dbid.DBS_RX, usrp_dbid.DBS_RX_REV_2_1):
437                         lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
438                         if lbw < 1.0e6:
439                                 lbw = 1.0e6
440                         self.subdev[0].set_bw(lbw)
441                         self.subdev[1].set_bw(lbw)
442                         
443                 # Start the timer for the LMST display and datalogging
444                 self.lmst_timer.Start(1000)
445                 if (self.switch_mode == True):
446                         self.other_timer.Start(330)
447
448
449         def _set_status_msg(self, msg):
450                 self.frame.GetStatusBar().SetStatusText(msg, 0)
451
452         def _build_gui(self, vbox):
453
454                 def _form_set_freq(kv):
455                         # Adjust current SETI frequency, and limits
456                         self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
457                         self.setifreq_current = kv['freq']
458                         self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)
459
460                         # Reset SETI analysis timer
461                         self.seti_then = time.time()
462                         # Zero-out hits array when changing frequency
463                         self.hits_array[:,:] = 0.0
464                         self.hit_intensities[:,:] = -60.0
465
466                         return self.set_freq(kv['freq'])
467
468                 def _form_set_decln(kv):
469                         return self.set_decln(kv['decln'])
470
471                 # Position the FFT display
472                 vbox.Add(self.scope.win, 15, wx.EXPAND)
473
474                 if self.setimode == False:
475                         # Position the Total-power stripchart
476                         vbox.Add(self.chart.win, 15, wx.EXPAND)
477                 
478                 # add control area at the bottom
479                 self.myform = myform = form.form()
480                 hbox = wx.BoxSizer(wx.HORIZONTAL)
481                 hbox.Add((7,0), 0, wx.EXPAND)
482                 vbox1 = wx.BoxSizer(wx.VERTICAL)
483                 myform['freq'] = form.float_field(
484                         parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
485                         callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
486
487                 vbox1.Add((4,0), 0, 0)
488
489                 myform['lmst_high'] = form.static_text_field(
490                         parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
491                 vbox1.Add((4,0), 0, 0)
492
493                 if self.setimode == False:
494                         myform['spec_data'] = form.static_text_field(
495                                 parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
496                         vbox1.Add((4,0), 0, 0)
497
498                 vbox2 = wx.BoxSizer(wx.VERTICAL)
499                 if self.setimode == False:
500                         vbox3 = wx.BoxSizer(wx.VERTICAL)
501                 g = self.subdev[0].gain_range()
502                 myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
503                                                                                    weight=1,
504                                                                                    min=int(g[0]), max=int(g[1]),
505                                                                                    callback=self.set_gain)
506
507                 vbox2.Add((4,0), 0, 0)
508                 if self.setimode == True:
509                         max_savg = 100
510                 else:
511                         max_savg = 3000
512                 myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2, 
513                                         label="Spectral Averaging (FFT frames)", weight=1, min=1, max=max_savg, callback=self.set_averaging)
514
515                 # Set up scan control button when in SETI mode
516                 if (self.setimode == True):
517                         # SETI scanning control
518                         buttonbox = wx.BoxSizer(wx.HORIZONTAL)
519                         self.scan_control = form.button_with_callback(self.panel,
520                                   label="Scan: On ",
521                                   callback=self.toggle_scanning)
522         
523                         buttonbox.Add(self.scan_control, 0, wx.CENTER)
524                         vbox2.Add(buttonbox, 0, wx.CENTER)
525
526                 vbox2.Add((4,0), 0, 0)
527
528                 if self.setimode == False:
529                         myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
530                                    label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)
531
532                         vbox2.Add((4,0), 0, 0)
533
534                 myform['decln'] = form.float_field(
535                         parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
536                         callback=myform.check_input_and_call(_form_set_decln))
537                 vbox2.Add((4,0), 0, 0)
538
539                 if self.setimode == False:
540                         myform['offset'] = form.slider_field(parent=self.panel, sizer=vbox3,
541                                 label="Post-Detector Offset", weight=1, min=-750, max=750, 
542                                 callback=self.set_pd_offset)
543                         vbox3.Add((2,0), 0, 0)
544                         myform['dcgain'] = form.slider_field(parent=self.panel, sizer=vbox3,
545                                 label="Post-Detector Gain", weight=1, min=1, max=100, 
546                                 callback=self.set_pd_gain)
547                         vbox3.Add((2,0), 0, 0)
548                 hbox.Add(vbox1, 0, 0)
549                 hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
550
551                 if self.setimode == False:
552                         hbox.Add(vbox3, wx.ALIGN_RIGHT, 0)
553
554                 vbox.Add(hbox, 0, wx.EXPAND)
555
556                 self._build_subpanel(vbox)
557
558                 self.lmst_timer = wx.PyTimer(self.lmst_timeout)
559                 self.other_timer = wx.PyTimer(self.other_timeout)
560
561
562         def _build_subpanel(self, vbox_arg):
563                 # build a secondary information panel (sometimes hidden)
564
565                 # FIXME figure out how to have this be a subpanel that is always
566                 # created, but has its visibility controlled by foo.Show(True/False)
567                 
568                 if not(self.show_debug_info):
569                         return
570
571                 panel = self.panel
572                 vbox = vbox_arg
573                 myform = self.myform
574
575                 #panel = wx.Panel(self.panel, -1)
576                 #vbox = wx.BoxSizer(wx.VERTICAL)
577
578                 hbox = wx.BoxSizer(wx.HORIZONTAL)
579                 hbox.Add((5,0), 0)
580                 myform['decim'] = form.static_float_field(
581                         parent=panel, sizer=hbox, label="Decim")
582
583                 hbox.Add((5,0), 1)
584                 myform['USB BW'] = form.static_float_field(
585                         parent=panel, sizer=hbox, label="USB BW")
586
587                 hbox.Add((5,0), 1)
588                 myform['dbname'] = form.static_text_field(
589                         parent=panel, sizer=hbox)
590
591                 hbox.Add((5,0), 1)
592                 myform['baseband'] = form.static_float_field(
593                         parent=panel, sizer=hbox, label="Analog BB")
594
595                 hbox.Add((5,0), 1)
596                 myform['ddc'] = form.static_float_field(
597                         parent=panel, sizer=hbox, label="DDC")
598
599                 hbox.Add((5,0), 0)
600                 vbox.Add(hbox, 0, wx.EXPAND)
601
602                 
603                 
604         def set_freq(self, target_freq):
605                 """
606                 Set the center frequency we're interested in.
607
608                 @param target_freq: frequency in Hz
609                 @rypte: bool
610
611                 Tuning is a two step process.  First we ask the front-end to
612                 tune as close to the desired frequency as it can.  Then we use
613                 the result of that operation and our target_frequency to
614                 determine the value for the digital down converter.
615                 """
616                 #
617                 # Everything except BASIC_RX should support usrp.tune()
618                 #
619                 if not (self.cardtype == usrp_dbid.BASIC_RX):
620                         r = usrp.tune(self.u, self.subdev[0].which(), self.subdev[0], target_freq)
621                         r = usrp.tune(self.u, self.subdev[1].which(), self.subdev[1], target_freq)
622                 else:
623                         r = self.u.set_rx_freq(0, target_freq)
624                         f = self.u.rx_freq(0)
625                         if abs(f-target_freq) > 2.0e3:
626                                 r = 0
627                 if r:
628                         self.myform['freq'].set_value(target_freq)         # update displayed value
629                         #
630                         # Make sure calibrator knows our target freq
631                         #
632
633                         # Remember centerfreq---used for doppler calcs
634                         delta = self.centerfreq - target_freq
635                         self.centerfreq = target_freq
636                         self.observing -= delta
637                         self.scope.set_baseband_freq (self.observing)
638
639                         self.myform['baseband'].set_value(r.baseband_freq)
640                         self.myform['ddc'].set_value(r.dxc_freq)
641                         
642                         if (self.use_notches):
643                                 self.compute_notch_taps(self.notches)
644                                 if self.dual_mode == False and self.interferometer == False:
645                                         self.notch_filt.set_taps(self.notch_taps)
646                                 else:
647                                         self.notch_filt1.set_taps(self.notch_taps)
648                                         self.notch_filt2.set_taps(self.notch_taps)
649
650                         return True
651
652                 return False
653
654         def set_decln(self, dec):
655                 self.decln = dec
656                 self.myform['decln'].set_value(dec)             # update displayed value
657
658         def set_gain(self, gain):
659                 self.myform['gain'].set_value(gain)             # update displayed value
660                 self.subdev[0].set_gain(gain)
661                 self.subdev[1].set_gain(gain)
662                 self.gain = gain
663
664         def set_averaging(self, avval):
665                 self.myform['average'].set_value(avval)
666                 self.scope.set_avg_alpha(1.0/(avval))
667                 self.scope.set_average(True)
668                 self.avg_alpha = avval
669
670         def set_integration(self, integval):
671                 if self.setimode == False:
672                         self.integrator.set_taps(1.0/((integval)*(self.bw/2)))
673                 self.myform['integration'].set_value(integval)
674                 self.integ = integval
675
676         #
677         # Timeout function
678         # Used to update LMST display, as well as current
679         #  continuum value
680         #
681         # We also write external data-logging files here
682         #
683         def lmst_timeout(self):
684                 self.locality.date = ephem.now()
685                 if self.setimode == False:
686                  x = self.probe.level()
687                 sidtime = self.locality.sidereal_time()
688                 # LMST
689                 s = str(ephem.hours(sidtime)) + " " + self.sunstate
690                 # Continuum detector value
691                 if self.setimode == False:
692                  sx = "%7.4f" % x
693                  s = s + "\nDet: " + str(sx)
694                 else:
695                  sx = "%2d" % self.hitcounter
696                  s1 = "%2d" % self.s1hitcounter
697                  s2 = "%2d" % self.s2hitcounter
698                  sa = "%4.2f" % self.avgdelta
699                  sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
700                  s = s + "\nHits: " + str(sx) + "\nS1:" + str(s1) + " S2:" + str(s2)
701                  s = s + "\nAv D: " + str(sa) + "\nCh lim: " + str(sy)
702
703                 self.myform['lmst_high'].set_value(s)
704
705                 #
706                 # Write data out to recording files
707                 #
708                 if self.setimode == False:
709                  self.write_continuum_data(x,sidtime)
710                  self.write_spectral_data(self.fft_outbuf,sidtime)
711
712                 else:
713                  self.seti_analysis(self.fft_outbuf,sidtime)
714                  now = time.time()
715                  if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
716                          self.seti_then = now
717                          self.setifreq_current = self.setifreq_current + self.fft_input_rate
718                          if (self.setifreq_current > self.setifreq_upper):
719                                  self.setifreq_current = self.setifreq_lower
720                          self.set_freq(self.setifreq_current)
721                          # Make sure we zero-out the hits array when changing
722                          #       frequency.
723                          self.hits_array[:,:] = 0.0
724                          self.hit_intensities[:,:] = 0.0
725         
726         def other_timeout(self):
727                 if (self.switch_state == 0):
728                         self.switch_state = 1
729                         
730                 elif (self.switch_state == 1):
731                         self.switch_state = 0
732                         
733                 if (self.switch_state == 0):
734                         self.mute.set_n(1)
735                         self.cmute.set_n(int(1.0e9))
736                         
737                 elif (self.switch_state == 1):
738                         self.mute.set_n(int(1.0e9))
739                         self.cmute.set_n(1)
740                         
741                 if (self.ref_fifo != "@@@@"):
742                         self.ref_fifo_file.write(str(self.switch_state)+"\n")
743                         self.ref_fifo_file.flush()
744
745                 self.avg_reference_value = self.cprobe.level()
746                         
747                 #
748                 # Set reference value
749                 #
750                 self.reference_level.set_k(-1.0 * (self.avg_reference_value/self.reference_divisor))
751
752         def fft_outfunc(self,data,l):
753                 self.fft_outbuf=data
754
755         def write_continuum_data(self,data,sidtime):
756         
757                 # Create localtime structure for producing filename
758                 foo = time.localtime()
759                 pfx = self.prefix
760                 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
761                    foo.tm_mon, foo.tm_mday, foo.tm_hour)
762         
763                 # Open the data file, appending
764                 continuum_file = open (filenamestr+".tpdat","a")
765           
766                 flt = "%6.3f" % data
767                 inter = self.decln
768                 integ = self.integ
769                 fc = self.observing
770                 fc = fc / 1000000
771                 bw = self.bw
772                 bw = bw / 1000000
773                 ga = self.gain
774         
775                 now = time.time()
776         
777                 #
778                 # If time to write full header info (saves storage this way)
779                 #
780                 if (now - self.continuum_then > 20):
781                         self.sun.compute(self.locality)
782                         enow = ephem.now()
783                         sunset = self.locality.next_setting(self.sun)
784                         sunrise = self.locality.next_rising(self.sun)
785                         sun_insky = "Down"
786                         self.sunstate = "Dn"
787                         if ((sunrise < enow) and (enow < sunset)):
788                            sun_insky = "Up"
789                            self.sunstate = "Up"
790                         self.continuum_then = now
791                 
792                         continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
793                         continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
794                         continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
795                 else:
796                         continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
797         
798                 continuum_file.close()
799                 return(data)
800
801         def write_spectral_data(self,data,sidtime):
802         
803                 now = time.time()
804                 delta = 10
805                         
806                 # If time to write out spectral data
807                 # We don't write this out every time, in order to
808                 #       save disk space.  Since the spectral data are
809                 #       typically heavily averaged, writing this data
810                 #       "once in a while" is OK.
811                 #
812                 if (now - self.spectral_then >= delta):
813                         self.spectral_then = now
814
815                         # Get localtime structure to make filename from
816                         foo = time.localtime()
817                 
818                         pfx = self.prefix
819                         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
820                            foo.tm_mon, foo.tm_mday, foo.tm_hour)
821         
822                         # Open the file
823                         spectral_file = open (filenamestr+".sdat","a")
824           
825                         # Setup data fields to be written
826                         r = data
827                         inter = self.decln
828                         fc = self.observing
829                         fc = fc / 1000000
830                         bw = self.bw
831                         bw = bw / 1000000
832                         av = self.avg_alpha
833
834                         # Write those fields
835                         spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
836                         spectral_file.write (" [ ")
837                         for r in data:
838                                 spectral_file.write(" "+str(r))
839
840                         spectral_file.write(" ]\n")
841                         spectral_file.close()
842                         return(data)
843         
844                 return(data)
845
846         def seti_analysis(self,fftbuf,sidtime):
847                 l = len(fftbuf)
848                 x = 0
849                 hits = []
850                 hit_intensities = []
851                 if self.seticounter < self.setitimer:
852                         self.seticounter = self.seticounter + 1
853                         return
854                 else:
855                         self.seticounter = 0
856
857                 # Run through FFT output buffer, computing standard deviation (Sigma)
858                 avg = 0
859                 # First compute average
860                 for i in range(0,l):
861                         avg = avg + fftbuf[i]
862                 avg = avg / l
863
864                 sigma = 0.0
865                 # Then compute standard deviation (Sigma)
866                 for i in range(0,l):
867                         d = fftbuf[i] - avg
868                         sigma = sigma + (d*d)
869
870                 sigma = Numeric.sqrt(sigma/l)
871
872                 #
873                 # Snarfle through the FFT output buffer again, looking for
874                 #        outlying data points
875
876                 start_f = self.observing - (self.fft_input_rate/2)
877                 current_f = start_f
878                 l = len(fftbuf)
879                 f_incr = self.fft_input_rate / l
880                 hit = -1
881
882                 # -nyquist to DC
883                 for i in range(l/2,l):
884                         #
885                         # If current FFT buffer has an item that exceeds the specified
886                         #  sigma
887                         #
888                         if ((fftbuf[i] - avg) > (self.setik * sigma)):
889                                 hits.append(current_f)
890                                 hit_intensities.append(fftbuf[i])
891                         current_f = current_f + f_incr
892
893                 # DC to nyquist
894                 for i in range(0,l/2):
895                         #
896                         # If current FFT buffer has an item that exceeds the specified
897                         #  sigma
898                         #
899                         if ((fftbuf[i] - avg) > (self.setik * sigma)):
900                                 hits.append(current_f)
901                                 hit_intensities.append(fftbuf[i])
902                         current_f = current_f + f_incr
903
904                 # No hits
905                 if (len(hits) <= 0):
906                         return
907
908
909                 #
910                 # OK, so we have some hits in the FFT buffer
911                 #       They'll have a rather substantial gauntlet to run before
912                 #       being declared a real "hit"
913                 #
914
915                 # Update stats
916                 self.s1hitcounter = self.s1hitcounter + len(hits)
917
918                 # Weed out buffers with an excessive number of
919                 #       signals above Sigma
920                 if (len(hits) > self.nhits):
921                         return
922
923
924                 # Weed out FFT buffers with apparent multiple narrowband signals
925                 #       separated significantly in frequency.  This means that a
926                 #       single signal spanning multiple bins is OK, but a buffer that
927                 #       has multiple, apparently-separate, signals isn't OK.
928                 #
929                 last = hits[0]
930                 ns2 = 1
931                 for i in range(1,len(hits)):
932                         if ((hits[i] - last) > (f_incr*3.0)):
933                                 return
934                         last = hits[i]
935                         ns2 = ns2 + 1
936
937                 self.s2hitcounter = self.s2hitcounter + ns2
938
939                 #
940                 # Run through all available hit buffers, computing difference between
941                 #       frequencies found there, if they're all within the chirp limits
942                 #       declare a good hit
943                 #
944                 good_hit = False
945                 f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
946                 avg_delta = 0
947                 k = 0
948                 for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
949                         f_ds[0] = abs(self.hits_array[i,0] - hits[i])
950                         for j in range(1,len(f_ds)):
951                            f_ds[j] = abs(self.hits_array[i,j] - self.hits_array[i,0])
952                            avg_delta = avg_delta + f_ds[j]
953                            k = k + 1
954
955                         if (self.seti_isahit (f_ds)):
956                                 good_hit = True
957                                 self.hitcounter = self.hitcounter + 1
958                                 break
959
960                 if (avg_delta/k < (self.seti_fft_bandwidth/2)):
961                         self.avgdelta = avg_delta / k
962
963                 # Save 'n shuffle hits
964                 #  Old hit buffers percolate through the hit buffers
965                 #  (there are self.nhitlines of these buffers)
966                 #  and then drop off the end
967                 #  A consequence is that while the nhitlines buffers are filling,
968                 #  you can get some absurd values for self.avgdelta, because some
969                 #  of the buffers are full of zeros
970                 for i in range(self.nhitlines,1):
971                         self.hits_array[:,i] = self.hits_array[:,i-1]
972                         self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
973
974                 for i in range(0,len(hits)):
975                         self.hits_array[i,0] = hits[i]
976                         self.hit_intensities[i,0] = hit_intensities[i]
977
978                 # Finally, write the hits/intensities buffer
979                 if (good_hit):
980                         self.write_hits(sidtime)
981
982                 return
983
984         def seti_isahit(self,fdiffs):
985                 truecount = 0
986
987                 for i in range(0,len(fdiffs)):
988                         if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
989                                 truecount = truecount + 1
990
991                 if truecount == len(fdiffs):
992                         return (True)
993                 else:
994                         return (False)
995
996         def write_hits(self,sidtime):
997                 # Create localtime structure for producing filename
998                 foo = time.localtime()
999                 pfx = self.prefix
1000                 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
1001                    foo.tm_mon, foo.tm_mday, foo.tm_hour)
1002         
1003                 # Open the data file, appending
1004                 hits_file = open (filenamestr+".seti","a")
1005
1006                 # Write sidtime first
1007                 hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
1008
1009                 #
1010                 # Then write the hits/hit intensities buffers with enough
1011                 #       "syntax" to allow parsing by external (not yet written!)
1012                 #       "stuff".
1013                 #
1014                 for i in range(0,self.nhitlines):
1015                         hits_file.write(" ")
1016                         for j in range(0,self.nhits):
1017                                 hits_file.write(str(self.hits_array[j,i])+":")
1018                                 hits_file.write(str(self.hit_intensities[j,i])+",")
1019                 hits_file.write("\n")
1020                 hits_file.close()
1021                 return
1022
1023         def xydfunc(self,func,xyv):
1024                 if self.setimode == True:
1025                         return
1026                 magn = int(Numeric.log10(self.observing))
1027                 if (magn == 6 or magn == 7 or magn == 8):
1028                         magn = 6
1029                 dfreq = xyv[0] * pow(10.0,magn)
1030                 if func == 0:
1031                         ratio = self.observing / dfreq
1032                         vs = 1.0 - ratio
1033                         vs *= 299792.0
1034                         if magn >= 9:
1035                            xhz = "Ghz"
1036                         elif magn >= 6:
1037                            xhz = "Mhz"
1038                         elif magn <= 5:
1039                            xhz =  "Khz"
1040                         s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
1041                         s2 = "\n%.3fkm/s" % vs
1042                         self.myform['spec_data'].set_value(s+s2)
1043                 else:
1044                         tmpnotches = Numeric.zeros(self.NOTCH_TAPS,Numeric.Float64)
1045                         delfreq = -1
1046                         if self.use_notches == True:
1047                                 for i in range(0,len(self.notches)):
1048                                         if self.notches[i] != 0 and abs(self.notches[i] - dfreq) < ((self.bw/self.NOTCH_TAPS)/2.0):
1049                                                 delfreq = i
1050                                                 break
1051                                 j = 0
1052                                 for i in range(0,len(self.notches)):
1053                                         if (i != delfreq):
1054                                                 tmpnotches[j] = self.notches[i]
1055                                                 j = j + 1
1056                                 if (delfreq == -1):
1057                                         for i in range(0,len(tmpnotches)):
1058                                                 if (int(tmpnotches[i]) == 0):
1059                                                         tmpnotches[i] = dfreq
1060                                                         break
1061                                 self.notches = tmpnotches
1062                                 self.compute_notch_taps(self.notches)
1063                                 if self.dual_mode == False and self.interferometer == False:
1064                                         self.notch_filt.set_taps(self.notch_taps)
1065                                 else:
1066                                         self.notch_filt1.set_taps(self.notch_taps)
1067                                         self.notch_filt2.set_taps(self.notch_taps)
1068
1069         def xydfunc_waterfall(self,pos):
1070                 lower = self.observing - (self.seti_fft_bandwidth / 2)
1071                 upper = self.observing + (self.seti_fft_bandwidth / 2)
1072                 binwidth = self.seti_fft_bandwidth / 1024
1073                 s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
1074                 self.myform['spec_data'].set_value(s)
1075
1076         def toggle_cal(self):
1077                 if (self.calstate == True):
1078                   self.calstate = False
1079                   self.u.write_io(0,0,(1<<15))
1080                   self.calibrator.SetLabel("Calibration Source: Off")
1081                 else:
1082                   self.calstate = True
1083                   self.u.write_io(0,(1<<15),(1<<15))
1084                   self.calibrator.SetLabel("Calibration Source: On")
1085
1086         def toggle_annotation(self):
1087                 if (self.annotate_state == True):
1088                   self.annotate_state = False
1089                   self.annotation.SetLabel("Annotation: Off")
1090                 else:
1091                   self.annotate_state = True
1092                   self.annotation.SetLabel("Annotation: On")
1093         #
1094         # Turn scanning on/off
1095         # Called-back by "Recording" button
1096         #
1097         def toggle_scanning(self):
1098                 # Current scanning?      Flip state
1099                 if (self.scanning == True):
1100                   self.scanning = False
1101                   self.scan_control.SetLabel("Scan: Off")
1102                 # Not scanning
1103                 else:
1104                   self.scanning = True
1105                   self.scan_control.SetLabel("Scan: On ")
1106
1107         def set_pd_offset(self,offs):
1108                  self.myform['offset'].set_value(offs)
1109                  self.calib_offset=offs
1110                  x = self.calib_coeff / 100.0
1111                  self.cal_offs.set_k(offs*(x*8000))
1112
1113         def set_pd_gain(self,gain):
1114                  self.myform['dcgain'].set_value(gain)
1115                  self.cal_mult.set_k(gain*0.01)
1116                  self.calib_coeff = gain
1117                  x = gain/100.0
1118                  self.cal_offs.set_k(self.calib_offset*(x*8000))
1119
1120         def compute_notch_taps(self,notchlist):
1121                  tmptaps = Numeric.zeros(self.NOTCH_TAPS,Numeric.Complex64)
1122                  binwidth = self.bw / self.NOTCH_TAPS
1123  
1124                  for i in range(0,self.NOTCH_TAPS):
1125                          tmptaps[i] = complex(1.0,0.0)
1126  
1127                  for i in notchlist:
1128                          diff = i - self.observing
1129                          if int(i) == 0:
1130                                  break
1131                          if ((i < (self.observing - self.bw/2)) or (i > (self.observing + self.bw/2))):
1132                                  continue
1133                          if (diff > 0):
1134                                  idx = diff / binwidth
1135                                  idx = round(idx)
1136                                  idx = int(idx)
1137                                  if (idx < 0 or idx > (self.NOTCH_TAPS/2)):
1138                                          break
1139                                  tmptaps[idx] = complex(0.0, 0.0)
1140
1141                          if (diff < 0):
1142                                  idx = -diff / binwidth
1143                                  idx = round(idx)
1144                                  idx = (self.NOTCH_TAPS/2) - idx
1145                                  idx = int(idx+(self.NOTCH_TAPS/2))
1146                                  if (idx < 0 or idx >= (self.NOTCH_TAPS)):
1147                                          break
1148                                  tmptaps[idx] = complex(0.0, 0.0)
1149
1150                  self.notch_taps = numpy.fft.ifft(tmptaps)
1151         
1152         #
1153         # Setup common pieces of radiometer mode
1154         #
1155         def setup_radiometer_common(self,n):
1156                 # The IIR integration filter for post-detection
1157                 self.integrator = gr.single_pole_iir_filter_ff(1.0)
1158                 self.integrator.set_taps (1.0/self.bw)
1159                 
1160                 if (self.use_notches == True):
1161                         self.compute_notch_taps(self.notches)
1162                         if (n == 2):
1163                                 self.notch_filt1 = gr.fft_filter_ccc(1, self.notch_taps)
1164                                 self.notch_filt2 = gr.fft_filter_ccc(1, self.notch_taps)
1165                         else:
1166                                 self.notch_filt = gr.fft_filter_ccc(1, self.notch_taps)
1167
1168
1169                 # Signal probe
1170                 self.probe = gr.probe_signal_f()
1171
1172                 #
1173                 # Continuum calibration stuff
1174                 #
1175                 x = self.calib_coeff/100.0
1176                 self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0)
1177                 self.cal_offs = gr.add_const_ff(self.calib_offset*(x*8000))
1178                 
1179                 #
1180                 # Mega decimator after IIR filter
1181                 #
1182                 if (self.switch_mode == False):
1183                         self.keepn = gr.keep_one_in_n(gr.sizeof_float, self.bw)
1184                 else:
1185                         self.keepn = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/2))
1186                 
1187                 #
1188                 # For the Dicke-switching scheme
1189                 #
1190                 #self.switch = gr.multiply_const_ff(1.0)
1191                 
1192                 #
1193                 if (self.switch_mode == True):
1194                         self.vector = gr.vector_sink_f()
1195                         self.swkeep = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/3))
1196                         self.mute = gr.keep_one_in_n(gr.sizeof_float, 1)
1197                         self.cmute = gr.keep_one_in_n(gr.sizeof_float, int(1.0e9))
1198                         self.cintegrator = gr.single_pole_iir_filter_ff(1.0/(self.bw/2))        
1199                         self.cprobe = gr.probe_signal_f()
1200                 else:
1201                         self.mute = gr.multiply_const_ff(1.0)
1202                         
1203                         
1204                 self.avg_reference_value = 0.0
1205                 self.reference_level = gr.add_const_ff(0.0)
1206                 
1207         #
1208         # Setup ordinary single-channel radiometer mode
1209         #        
1210         def setup_normal(self, setimode):
1211                 
1212                 self.setup_radiometer_common(1)
1213                 
1214                 self.head = self.u
1215                 if (self.use_notches == True):
1216                         self.shead = self.notch_filt
1217                 else:
1218                         self.shead = self.u
1219                 
1220                 if setimode == False:
1221                                 
1222                         self.detector = gr.complex_to_mag_squared()
1223                         self.connect(self.shead, self.scope)
1224
1225                         if (self.use_notches == False):
1226                                 self.connect(self.head, self.detector, self.mute, self.reference_level,
1227                                         self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1228                         else:
1229                                 self.connect(self.head, self.notch_filt, self.detector, self.mute, self.reference_level,
1230                                         self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1231                                 
1232                         self.connect(self.cal_offs, self.probe)
1233                         
1234                         #
1235                         # Add a side-chain detector chain, with a different integrator, for sampling
1236                         #   The reference channel data
1237                         # This is used to derive the offset value for self.reference_level, used above
1238                         #
1239                         if (self.switch_mode == True):          
1240                                 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)
1241                         
1242                 return
1243         
1244         #
1245         # Setup dual-channel (two antenna, usual orthogonal polarity probes in the same waveguide)
1246         #
1247         def setup_dual(self, setimode):
1248                 
1249                 self.setup_radiometer_common(2)
1250                 
1251                 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1252                 self.addchans = gr.add_cc ()
1253                 self.detector = gr.add_ff ()
1254                 self.h_power = gr.complex_to_mag_squared()
1255                 self.v_power = gr.complex_to_mag_squared()
1256                 self.connect (self.u, self.di)
1257                 
1258                 if (self.use_notches == True):
1259                         self.connect((self.di, 0), self.notch_filt1, (self.addchans, 0))
1260                         self.connect((self.di, 1), self.notch_filt2, (self.addchans, 1))
1261                 else:
1262                         #
1263                         # For spectral, adding the two channels works, assuming no gross
1264                         #       phase or amplitude error
1265                         self.connect ((self.di, 0), (self.addchans, 0))
1266                         self.connect ((self.di, 1), (self.addchans, 1))
1267                 
1268                 #
1269                 # Connect heads of spectral and total-power chains
1270                 #
1271                 if (self.use_notches == False):
1272                         self.head = self.di
1273                 else:
1274                         self.head = (self.notch_filt1, self.notch_filt2)
1275                         
1276                 self.shead = self.addchans
1277                 
1278                 if (setimode == False):
1279                         #
1280                         # For dual-polarization mode, we compute the sum of the
1281                         #       powers on each channel, after they've been detected
1282                         #
1283                         self.detector = gr.add_ff()
1284                         
1285                         #
1286                         # In dual-polarization mode, we compute things a little differently
1287                         # In effect, we have two radiometer chains, terminating in an adder
1288                         #
1289                         if self.use_notches == True:
1290                                 self.connect(self.notch_filt1, self.h_power)
1291                                 self.connect(self.notch_filt2, self.v_power)
1292                         else:
1293                                 self.connect((self.head, 0), self.h_power)
1294                                 self.connect((self.head, 1), self.v_power)
1295                         self.connect(self.h_power, (self.detector, 0))
1296                         self.connect(self.v_power, (self.detector, 1))
1297                         self.connect(self.detector, self.mute, self.reference_level,
1298                                 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1299                         self.connect(self.cal_offs, self.probe)
1300                         self.connect(self.shead, self.scope)
1301                         
1302                         #
1303                         # Add a side-chain detector chain, with a different integrator, for sampling
1304                         #   The reference channel data
1305                         # This is used to derive the offset value for self.reference_level, used above
1306                         #
1307                         if (self.switch_mode == True):
1308                                 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)                     
1309                 return
1310         
1311         #
1312         # Setup correlating interferometer mode
1313         #
1314         def setup_interferometer(self, setimode):
1315                 self.setup_radiometer_common(2)
1316                 
1317                 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1318                 self.connect (self.u, self.di)
1319                 self.corr = gr.multiply_cc()
1320                 self.c2f = gr.complex_to_float()
1321                 
1322                 self.shead = (self.di, 0)
1323                 
1324                 # Channel 0 to multiply port 0
1325                 # Channel 1 to multiply port 1
1326                 if (self.use_notches == False):
1327                         self.connect((self.di, 0), (self.corr, 0))
1328                         self.connect((self.di, 1), (self.corr, 1))
1329                 else:
1330                         self.connect((self.di, 0), self.notch_filt1, (self.corr, 0))
1331                         self.connect((self.di, 1), self.notch_filt2, (self.corr, 0))
1332                 
1333                 #
1334                 # Multiplier (correlator) to complex-to-float, followed by integrator, etc
1335                 #
1336                 self.connect(self.corr, self.c2f, self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1337                 
1338                 #
1339                 # FFT scope gets only 1 channel
1340                 #  FIX THIS, by cross-correlating the *outputs* of two different FFTs, then display
1341                 #  Funky!
1342                 #
1343                 self.connect(self.shead, self.scope)
1344                 
1345                 #
1346                 # Output of correlator/integrator chain to probe
1347                 #
1348                 self.connect(self.cal_offs, self.probe)
1349                 
1350                 return
1351         
1352         #
1353         # Setup SETI mode
1354         #
1355         def setup_seti(self):
1356                 self.connect (self.shead, self.fft_bandpass, self.scope)
1357                 return
1358
1359                 
1360
1361 def main ():
1362         app = stdgui2.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1363         app.MainLoop()
1364
1365 if __name__ == '__main__':
1366         main ()