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