fa6d02c6faa327e90449a6105a7e8f80037e0ca8
[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 in (usrp_dbid.DBS_RX, usrp_dbid.DBS_RX_REV_2_1):
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                 @rypte: bool
603
604                 Tuning is a two step process.  First we ask the front-end to
605                 tune as close to the desired frequency as it can.  Then we use
606                 the result of that operation and our target_frequency to
607                 determine the value for the digital down converter.
608                 """
609                 #
610                 # Everything except BASIC_RX should support usrp.tune()
611                 #
612                 if not (self.cardtype == usrp_dbid.BASIC_RX):
613                         r = usrp.tune(self.u, self.subdev[0].which(), self.subdev[0], target_freq)
614                         r = usrp.tune(self.u, self.subdev[1].which(), self.subdev[1], target_freq)
615                 else:
616                         r = self.u.set_rx_freq(0, target_freq)
617                         f = self.u.rx_freq(0)
618                         if abs(f-target_freq) > 2.0e3:
619                                 r = 0
620                 if r:
621                         self.myform['freq'].set_value(target_freq)         # update displayed value
622                         #
623                         # Make sure calibrator knows our target freq
624                         #
625
626                         # Remember centerfreq---used for doppler calcs
627                         delta = self.centerfreq - target_freq
628                         self.centerfreq = target_freq
629                         self.observing -= delta
630                         self.scope.set_baseband_freq (self.observing)
631
632                         self.myform['baseband'].set_value(r.baseband_freq)
633                         self.myform['ddc'].set_value(r.dxc_freq)
634                         
635                         if (self.use_notches):
636                                 self.compute_notch_taps(self.notches)
637                                 if self.dual_mode == False and self.interferometer == False:
638                                         self.notch_filt.set_taps(self.notch_taps)
639                                 else:
640                                         self.notch_filt1.set_taps(self.notch_taps)
641                                         self.notch_filt2.set_taps(self.notch_taps)
642
643                         return True
644
645                 return False
646
647         def set_decln(self, dec):
648                 self.decln = dec
649                 self.myform['decln'].set_value(dec)             # update displayed value
650
651         def set_gain(self, gain):
652                 self.myform['gain'].set_value(gain)             # update displayed value
653                 self.subdev[0].set_gain(gain)
654                 self.subdev[1].set_gain(gain)
655                 self.gain = gain
656
657         def set_averaging(self, avval):
658                 self.myform['average'].set_value(avval)
659                 self.scope.set_avg_alpha(1.0/(avval))
660                 self.scope.set_average(True)
661                 self.avg_alpha = avval
662
663         def set_integration(self, integval):
664                 if self.setimode == False:
665                         self.integrator.set_taps(1.0/((integval)*(self.bw/2)))
666                 self.myform['integration'].set_value(integval)
667                 self.integ = integval
668
669         #
670         # Timeout function
671         # Used to update LMST display, as well as current
672         #  continuum value
673         #
674         # We also write external data-logging files here
675         #
676         def lmst_timeout(self):
677                 self.locality.date = ephem.now()
678                 if self.setimode == False:
679                  x = self.probe.level()
680                 sidtime = self.locality.sidereal_time()
681                 # LMST
682                 s = str(ephem.hours(sidtime)) + " " + self.sunstate
683                 # Continuum detector value
684                 if self.setimode == False:
685                  sx = "%7.4f" % x
686                  s = s + "\nDet: " + str(sx)
687                 else:
688                  sx = "%2d" % self.hitcounter
689                  s1 = "%2d" % self.s1hitcounter
690                  s2 = "%2d" % self.s2hitcounter
691                  sa = "%4.2f" % self.avgdelta
692                  sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
693                  s = s + "\nHits: " + str(sx) + "\nS1:" + str(s1) + " S2:" + str(s2)
694                  s = s + "\nAv D: " + str(sa) + "\nCh lim: " + str(sy)
695
696                 self.myform['lmst_high'].set_value(s)
697
698                 #
699                 # Write data out to recording files
700                 #
701                 if self.setimode == False:
702                  self.write_continuum_data(x,sidtime)
703                  self.write_spectral_data(self.fft_outbuf,sidtime)
704
705                 else:
706                  self.seti_analysis(self.fft_outbuf,sidtime)
707                  now = time.time()
708                  if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
709                          self.seti_then = now
710                          self.setifreq_current = self.setifreq_current + self.fft_input_rate
711                          if (self.setifreq_current > self.setifreq_upper):
712                                  self.setifreq_current = self.setifreq_lower
713                          self.set_freq(self.setifreq_current)
714                          # Make sure we zero-out the hits array when changing
715                          #       frequency.
716                          self.hits_array[:,:] = 0.0
717                          self.hit_intensities[:,:] = 0.0
718         
719         def other_timeout(self):
720                 if (self.switch_state == 0):
721                         self.switch_state = 1
722                         
723                 elif (self.switch_state == 1):
724                         self.switch_state = 0
725                         
726                 if (self.switch_state == 0):
727                         self.mute.set_n(1)
728                         self.cmute.set_n(int(1.0e9))
729                         
730                 elif (self.switch_state == 1):
731                         self.mute.set_n(int(1.0e9))
732                         self.cmute.set_n(1)
733                         
734                 if (self.ref_fifo != "@@@@"):
735                         self.ref_fifo_file.write(str(self.switch_state)+"\n")
736                         self.ref_fifo_file.flush()
737
738                 self.avg_reference_value = self.cprobe.level()
739                         
740                 #
741                 # Set reference value
742                 #
743                 self.reference_level.set_k(-1.0 * (self.avg_reference_value/self.reference_divisor))
744
745         def fft_outfunc(self,data,l):
746                 self.fft_outbuf=data
747
748         def write_continuum_data(self,data,sidtime):
749         
750                 # Create localtime structure for producing filename
751                 foo = time.localtime()
752                 pfx = self.prefix
753                 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
754                    foo.tm_mon, foo.tm_mday, foo.tm_hour)
755         
756                 # Open the data file, appending
757                 continuum_file = open (filenamestr+".tpdat","a")
758           
759                 flt = "%6.3f" % data
760                 inter = self.decln
761                 integ = self.integ
762                 fc = self.observing
763                 fc = fc / 1000000
764                 bw = self.bw
765                 bw = bw / 1000000
766                 ga = self.gain
767         
768                 now = time.time()
769         
770                 #
771                 # If time to write full header info (saves storage this way)
772                 #
773                 if (now - self.continuum_then > 20):
774                         self.sun.compute(self.locality)
775                         enow = ephem.now()
776                         sunset = self.locality.next_setting(self.sun)
777                         sunrise = self.locality.next_rising(self.sun)
778                         sun_insky = "Down"
779                         self.sunstate = "Dn"
780                         if ((sunrise < enow) and (enow < sunset)):
781                            sun_insky = "Up"
782                            self.sunstate = "Up"
783                         self.continuum_then = now
784                 
785                         continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
786                         continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
787                         continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
788                 else:
789                         continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
790         
791                 continuum_file.close()
792                 return(data)
793
794         def write_spectral_data(self,data,sidtime):
795         
796                 now = time.time()
797                 delta = 10
798                         
799                 # If time to write out spectral data
800                 # We don't write this out every time, in order to
801                 #       save disk space.  Since the spectral data are
802                 #       typically heavily averaged, writing this data
803                 #       "once in a while" is OK.
804                 #
805                 if (now - self.spectral_then >= delta):
806                         self.spectral_then = now
807
808                         # Get localtime structure to make filename from
809                         foo = time.localtime()
810                 
811                         pfx = self.prefix
812                         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
813                            foo.tm_mon, foo.tm_mday, foo.tm_hour)
814         
815                         # Open the file
816                         spectral_file = open (filenamestr+".sdat","a")
817           
818                         # Setup data fields to be written
819                         r = data
820                         inter = self.decln
821                         fc = self.observing
822                         fc = fc / 1000000
823                         bw = self.bw
824                         bw = bw / 1000000
825                         av = self.avg_alpha
826
827                         # Write those fields
828                         spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
829                         spectral_file.write (" [ ")
830                         for r in data:
831                                 spectral_file.write(" "+str(r))
832
833                         spectral_file.write(" ]\n")
834                         spectral_file.close()
835                         return(data)
836         
837                 return(data)
838
839         def seti_analysis(self,fftbuf,sidtime):
840                 l = len(fftbuf)
841                 x = 0
842                 hits = []
843                 hit_intensities = []
844                 if self.seticounter < self.setitimer:
845                         self.seticounter = self.seticounter + 1
846                         return
847                 else:
848                         self.seticounter = 0
849
850                 # Run through FFT output buffer, computing standard deviation (Sigma)
851                 avg = 0
852                 # First compute average
853                 for i in range(0,l):
854                         avg = avg + fftbuf[i]
855                 avg = avg / l
856
857                 sigma = 0.0
858                 # Then compute standard deviation (Sigma)
859                 for i in range(0,l):
860                         d = fftbuf[i] - avg
861                         sigma = sigma + (d*d)
862
863                 sigma = Numeric.sqrt(sigma/l)
864
865                 #
866                 # Snarfle through the FFT output buffer again, looking for
867                 #        outlying data points
868
869                 start_f = self.observing - (self.fft_input_rate/2)
870                 current_f = start_f
871                 l = len(fftbuf)
872                 f_incr = self.fft_input_rate / l
873                 hit = -1
874
875                 # -nyquist to DC
876                 for i in range(l/2,l):
877                         #
878                         # If current FFT buffer has an item that exceeds the specified
879                         #  sigma
880                         #
881                         if ((fftbuf[i] - avg) > (self.setik * sigma)):
882                                 hits.append(current_f)
883                                 hit_intensities.append(fftbuf[i])
884                         current_f = current_f + f_incr
885
886                 # DC to nyquist
887                 for i in range(0,l/2):
888                         #
889                         # If current FFT buffer has an item that exceeds the specified
890                         #  sigma
891                         #
892                         if ((fftbuf[i] - avg) > (self.setik * sigma)):
893                                 hits.append(current_f)
894                                 hit_intensities.append(fftbuf[i])
895                         current_f = current_f + f_incr
896
897                 # No hits
898                 if (len(hits) <= 0):
899                         return
900
901
902                 #
903                 # OK, so we have some hits in the FFT buffer
904                 #       They'll have a rather substantial gauntlet to run before
905                 #       being declared a real "hit"
906                 #
907
908                 # Update stats
909                 self.s1hitcounter = self.s1hitcounter + len(hits)
910
911                 # Weed out buffers with an excessive number of
912                 #       signals above Sigma
913                 if (len(hits) > self.nhits):
914                         return
915
916
917                 # Weed out FFT buffers with apparent multiple narrowband signals
918                 #       separated significantly in frequency.  This means that a
919                 #       single signal spanning multiple bins is OK, but a buffer that
920                 #       has multiple, apparently-separate, signals isn't OK.
921                 #
922                 last = hits[0]
923                 ns2 = 1
924                 for i in range(1,len(hits)):
925                         if ((hits[i] - last) > (f_incr*3.0)):
926                                 return
927                         last = hits[i]
928                         ns2 = ns2 + 1
929
930                 self.s2hitcounter = self.s2hitcounter + ns2
931
932                 #
933                 # Run through all available hit buffers, computing difference between
934                 #       frequencies found there, if they're all within the chirp limits
935                 #       declare a good hit
936                 #
937                 good_hit = False
938                 f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
939                 avg_delta = 0
940                 k = 0
941                 for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
942                         f_ds[0] = abs(self.hits_array[i,0] - hits[i])
943                         for j in range(1,len(f_ds)):
944                            f_ds[j] = abs(self.hits_array[i,j] - self.hits_array[i,0])
945                            avg_delta = avg_delta + f_ds[j]
946                            k = k + 1
947
948                         if (self.seti_isahit (f_ds)):
949                                 good_hit = True
950                                 self.hitcounter = self.hitcounter + 1
951                                 break
952
953                 if (avg_delta/k < (self.seti_fft_bandwidth/2)):
954                         self.avgdelta = avg_delta / k
955
956                 # Save 'n shuffle hits
957                 #  Old hit buffers percolate through the hit buffers
958                 #  (there are self.nhitlines of these buffers)
959                 #  and then drop off the end
960                 #  A consequence is that while the nhitlines buffers are filling,
961                 #  you can get some absurd values for self.avgdelta, because some
962                 #  of the buffers are full of zeros
963                 for i in range(self.nhitlines,1):
964                         self.hits_array[:,i] = self.hits_array[:,i-1]
965                         self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
966
967                 for i in range(0,len(hits)):
968                         self.hits_array[i,0] = hits[i]
969                         self.hit_intensities[i,0] = hit_intensities[i]
970
971                 # Finally, write the hits/intensities buffer
972                 if (good_hit):
973                         self.write_hits(sidtime)
974
975                 return
976
977         def seti_isahit(self,fdiffs):
978                 truecount = 0
979
980                 for i in range(0,len(fdiffs)):
981                         if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
982                                 truecount = truecount + 1
983
984                 if truecount == len(fdiffs):
985                         return (True)
986                 else:
987                         return (False)
988
989         def write_hits(self,sidtime):
990                 # Create localtime structure for producing filename
991                 foo = time.localtime()
992                 pfx = self.prefix
993                 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
994                    foo.tm_mon, foo.tm_mday, foo.tm_hour)
995         
996                 # Open the data file, appending
997                 hits_file = open (filenamestr+".seti","a")
998
999                 # Write sidtime first
1000                 hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
1001
1002                 #
1003                 # Then write the hits/hit intensities buffers with enough
1004                 #       "syntax" to allow parsing by external (not yet written!)
1005                 #       "stuff".
1006                 #
1007                 for i in range(0,self.nhitlines):
1008                         hits_file.write(" ")
1009                         for j in range(0,self.nhits):
1010                                 hits_file.write(str(self.hits_array[j,i])+":")
1011                                 hits_file.write(str(self.hit_intensities[j,i])+",")
1012                 hits_file.write("\n")
1013                 hits_file.close()
1014                 return
1015
1016         def xydfunc(self,func,xyv):
1017                 if self.setimode == True:
1018                         return
1019                 magn = int(Numeric.log10(self.observing))
1020                 if (magn == 6 or magn == 7 or magn == 8):
1021                         magn = 6
1022                 dfreq = xyv[0] * pow(10.0,magn)
1023                 if func == 0:
1024                         ratio = self.observing / dfreq
1025                         vs = 1.0 - ratio
1026                         vs *= 299792.0
1027                         if magn >= 9:
1028                            xhz = "Ghz"
1029                         elif magn >= 6:
1030                            xhz = "Mhz"
1031                         elif magn <= 5:
1032                            xhz =  "Khz"
1033                         s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
1034                         s2 = "\n%.3fkm/s" % vs
1035                         self.myform['spec_data'].set_value(s+s2)
1036                 else:
1037                         tmpnotches = Numeric.zeros(self.NOTCH_TAPS,Numeric.Float64)
1038                         delfreq = -1
1039                         if self.use_notches == True:
1040                                 for i in range(0,len(self.notches)):
1041                                         if self.notches[i] != 0 and abs(self.notches[i] - dfreq) < ((self.bw/self.NOTCH_TAPS)/2.0):
1042                                                 delfreq = i
1043                                                 break
1044                                 j = 0
1045                                 for i in range(0,len(self.notches)):
1046                                         if (i != delfreq):
1047                                                 tmpnotches[j] = self.notches[i]
1048                                                 j = j + 1
1049                                 if (delfreq == -1):
1050                                         for i in range(0,len(tmpnotches)):
1051                                                 if (int(tmpnotches[i]) == 0):
1052                                                         tmpnotches[i] = dfreq
1053                                                         break
1054                                 self.notches = tmpnotches
1055                                 self.compute_notch_taps(self.notches)
1056                                 if self.dual_mode == False and self.interferometer == False:
1057                                         self.notch_filt.set_taps(self.notch_taps)
1058                                 else:
1059                                         self.notch_filt1.set_taps(self.notch_taps)
1060                                         self.notch_filt2.set_taps(self.notch_taps)
1061
1062         def xydfunc_waterfall(self,pos):
1063                 lower = self.observing - (self.seti_fft_bandwidth / 2)
1064                 upper = self.observing + (self.seti_fft_bandwidth / 2)
1065                 binwidth = self.seti_fft_bandwidth / 1024
1066                 s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
1067                 self.myform['spec_data'].set_value(s)
1068
1069         def toggle_cal(self):
1070                 if (self.calstate == True):
1071                   self.calstate = False
1072                   self.u.write_io(0,0,(1<<15))
1073                   self.calibrator.SetLabel("Calibration Source: Off")
1074                 else:
1075                   self.calstate = True
1076                   self.u.write_io(0,(1<<15),(1<<15))
1077                   self.calibrator.SetLabel("Calibration Source: On")
1078
1079         def toggle_annotation(self):
1080                 if (self.annotate_state == True):
1081                   self.annotate_state = False
1082                   self.annotation.SetLabel("Annotation: Off")
1083                 else:
1084                   self.annotate_state = True
1085                   self.annotation.SetLabel("Annotation: On")
1086         #
1087         # Turn scanning on/off
1088         # Called-back by "Recording" button
1089         #
1090         def toggle_scanning(self):
1091                 # Current scanning?      Flip state
1092                 if (self.scanning == True):
1093                   self.scanning = False
1094                   self.scan_control.SetLabel("Scan: Off")
1095                 # Not scanning
1096                 else:
1097                   self.scanning = True
1098                   self.scan_control.SetLabel("Scan: On ")
1099
1100         def set_pd_offset(self,offs):
1101                  self.myform['offset'].set_value(offs)
1102                  self.calib_offset=offs
1103                  x = self.calib_coeff / 100.0
1104                  self.cal_offs.set_k(offs*(x*8000))
1105
1106         def set_pd_gain(self,gain):
1107                  self.myform['dcgain'].set_value(gain)
1108                  self.cal_mult.set_k(gain*0.01)
1109                  self.calib_coeff = gain
1110                  x = gain/100.0
1111                  self.cal_offs.set_k(self.calib_offset*(x*8000))
1112
1113         def compute_notch_taps(self,notchlist):
1114                  tmptaps = Numeric.zeros(self.NOTCH_TAPS,Numeric.Complex64)
1115                  binwidth = self.bw / self.NOTCH_TAPS
1116  
1117                  for i in range(0,self.NOTCH_TAPS):
1118                          tmptaps[i] = complex(1.0,0.0)
1119  
1120                  for i in notchlist:
1121                          diff = i - self.observing
1122                          if int(i) == 0:
1123                                  break
1124                          if ((i < (self.observing - self.bw/2)) or (i > (self.observing + self.bw/2))):
1125                                  continue
1126                          if (diff > 0):
1127                                  idx = diff / binwidth
1128                                  idx = round(idx)
1129                                  idx = int(idx)
1130                                  if (idx < 0 or idx > (self.NOTCH_TAPS/2)):
1131                                          break
1132                                  tmptaps[idx] = complex(0.0, 0.0)
1133
1134                          if (diff < 0):
1135                                  idx = -diff / binwidth
1136                                  idx = round(idx)
1137                                  idx = (self.NOTCH_TAPS/2) - idx
1138                                  idx = int(idx+(self.NOTCH_TAPS/2))
1139                                  if (idx < 0 or idx >= (self.NOTCH_TAPS)):
1140                                          break
1141                                  tmptaps[idx] = complex(0.0, 0.0)
1142
1143                  self.notch_taps = numpy.fft.ifft(tmptaps)
1144         
1145         #
1146         # Setup common pieces of radiometer mode
1147         #
1148         def setup_radiometer_common(self,n):
1149                 # The IIR integration filter for post-detection
1150                 self.integrator = gr.single_pole_iir_filter_ff(1.0)
1151                 self.integrator.set_taps (1.0/self.bw)
1152                 
1153                 if (self.use_notches == True):
1154                         self.compute_notch_taps(self.notches)
1155                         if (n == 2):
1156                                 self.notch_filt1 = gr.fft_filter_ccc(1, self.notch_taps)
1157                                 self.notch_filt2 = gr.fft_filter_ccc(1, self.notch_taps)
1158                         else:
1159                                 self.notch_filt = gr.fft_filter_ccc(1, self.notch_taps)
1160
1161
1162                 # Signal probe
1163                 self.probe = gr.probe_signal_f()
1164
1165                 #
1166                 # Continuum calibration stuff
1167                 #
1168                 x = self.calib_coeff/100.0
1169                 self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0)
1170                 self.cal_offs = gr.add_const_ff(self.calib_offset*(x*8000))
1171                 
1172                 #
1173                 # Mega decimator after IIR filter
1174                 #
1175                 if (self.switch_mode == False):
1176                         self.keepn = gr.keep_one_in_n(gr.sizeof_float, self.bw)
1177                 else:
1178                         self.keepn = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/2))
1179                 
1180                 #
1181                 # For the Dicke-switching scheme
1182                 #
1183                 #self.switch = gr.multiply_const_ff(1.0)
1184                 
1185                 #
1186                 if (self.switch_mode == True):
1187                         self.vector = gr.vector_sink_f()
1188                         self.swkeep = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/3))
1189                         self.mute = gr.keep_one_in_n(gr.sizeof_float, 1)
1190                         self.cmute = gr.keep_one_in_n(gr.sizeof_float, int(1.0e9))
1191                         self.cintegrator = gr.single_pole_iir_filter_ff(1.0/(self.bw/2))        
1192                         self.cprobe = gr.probe_signal_f()
1193                 else:
1194                         self.mute = gr.multiply_const_ff(1.0)
1195                         
1196                         
1197                 self.avg_reference_value = 0.0
1198                 self.reference_level = gr.add_const_ff(0.0)
1199                 
1200         #
1201         # Setup ordinary single-channel radiometer mode
1202         #        
1203         def setup_normal(self, setimode):
1204                 
1205                 self.setup_radiometer_common(1)
1206                 
1207                 self.head = self.u
1208                 if (self.use_notches == True):
1209                         self.shead = self.notch_filt
1210                 else:
1211                         self.shead = self.u
1212                 
1213                 if setimode == False:
1214                                 
1215                         self.detector = gr.complex_to_mag_squared()
1216                         self.connect(self.shead, self.scope)
1217
1218                         if (self.use_notches == False):
1219                                 self.connect(self.head, self.detector, self.mute, self.reference_level,
1220                                         self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1221                         else:
1222                                 self.connect(self.head, self.notch_filt, self.detector, self.mute, self.reference_level,
1223                                         self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1224                                 
1225                         self.connect(self.cal_offs, self.probe)
1226                         
1227                         #
1228                         # Add a side-chain detector chain, with a different integrator, for sampling
1229                         #   The reference channel data
1230                         # This is used to derive the offset value for self.reference_level, used above
1231                         #
1232                         if (self.switch_mode == True):          
1233                                 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)
1234                         
1235                 return
1236         
1237         #
1238         # Setup dual-channel (two antenna, usual orthogonal polarity probes in the same waveguide)
1239         #
1240         def setup_dual(self, setimode):
1241                 
1242                 self.setup_radiometer_common(2)
1243                 
1244                 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1245                 self.addchans = gr.add_cc ()
1246                 self.detector = gr.add_ff ()
1247                 self.h_power = gr.complex_to_mag_squared()
1248                 self.v_power = gr.complex_to_mag_squared()
1249                 self.connect (self.u, self.di)
1250                 
1251                 if (self.use_notches == True):
1252                         self.connect((self.di, 0), self.notch_filt1, (self.addchans, 0))
1253                         self.connect((self.di, 1), self.notch_filt2, (self.addchans, 1))
1254                 else:
1255                         #
1256                         # For spectral, adding the two channels works, assuming no gross
1257                         #       phase or amplitude error
1258                         self.connect ((self.di, 0), (self.addchans, 0))
1259                         self.connect ((self.di, 1), (self.addchans, 1))
1260                 
1261                 #
1262                 # Connect heads of spectral and total-power chains
1263                 #
1264                 if (self.use_notches == False):
1265                         self.head = self.di
1266                 else:
1267                         self.head = (self.notch_filt1, self.notch_filt2)
1268                         
1269                 self.shead = self.addchans
1270                 
1271                 if (setimode == False):
1272                         #
1273                         # For dual-polarization mode, we compute the sum of the
1274                         #       powers on each channel, after they've been detected
1275                         #
1276                         self.detector = gr.add_ff()
1277                         
1278                         #
1279                         # In dual-polarization mode, we compute things a little differently
1280                         # In effect, we have two radiometer chains, terminating in an adder
1281                         #
1282                         if self.use_notches == True:
1283                                 self.connect(self.notch_filt1, self.h_power)
1284                                 self.connect(self.notch_filt2, self.v_power)
1285                         else:
1286                                 self.connect((self.head, 0), self.h_power)
1287                                 self.connect((self.head, 1), self.v_power)
1288                         self.connect(self.h_power, (self.detector, 0))
1289                         self.connect(self.v_power, (self.detector, 1))
1290                         self.connect(self.detector, self.mute, self.reference_level,
1291                                 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1292                         self.connect(self.cal_offs, self.probe)
1293                         self.connect(self.shead, self.scope)
1294                         
1295                         #
1296                         # Add a side-chain detector chain, with a different integrator, for sampling
1297                         #   The reference channel data
1298                         # This is used to derive the offset value for self.reference_level, used above
1299                         #
1300                         if (self.switch_mode == True):
1301                                 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)                     
1302                 return
1303         
1304         #
1305         # Setup correlating interferometer mode
1306         #
1307         def setup_interferometer(self, setimode):
1308                 self.setup_radiometer_common(2)
1309                 
1310                 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1311                 self.connect (self.u, self.di)
1312                 self.corr = gr.multiply_cc()
1313                 self.c2f = gr.complex_to_float()
1314                 
1315                 self.shead = (self.di, 0)
1316                 
1317                 # Channel 0 to multiply port 0
1318                 # Channel 1 to multiply port 1
1319                 if (self.use_notches == False):
1320                         self.connect((self.di, 0), (self.corr, 0))
1321                         self.connect((self.di, 1), (self.corr, 1))
1322                 else:
1323                         self.connect((self.di, 0), self.notch_filt1, (self.corr, 0))
1324                         self.connect((self.di, 1), self.notch_filt2, (self.corr, 0))
1325                 
1326                 #
1327                 # Multiplier (correlator) to complex-to-float, followed by integrator, etc
1328                 #
1329                 self.connect(self.corr, self.c2f, self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1330                 
1331                 #
1332                 # FFT scope gets only 1 channel
1333                 #  FIX THIS, by cross-correlating the *outputs* of two different FFTs, then display
1334                 #  Funky!
1335                 #
1336                 self.connect(self.shead, self.scope)
1337                 
1338                 #
1339                 # Output of correlator/integrator chain to probe
1340                 #
1341                 self.connect(self.cal_offs, self.probe)
1342                 
1343                 return
1344         
1345         #
1346         # Setup SETI mode
1347         #
1348         def setup_seti(self):
1349                 self.connect (self.shead, self.fft_bandpass, self.scope)
1350                 return
1351         
1352         def setup_usrp(self):
1353                 
1354                 if (self.usrp2 == False):
1355                         if (self.dual_mode == False and self.interferometer == False):
1356                                 if (self.decim > 4):
1357                                         self.u = usrp.source_c(decim_rate=self.decim,fusb_block_size=8192)
1358                                 else:
1359                                         self.u = usrp.source_c(decim_rate=self.decim,fusb_block_size=8192, fpga_filename="std_4rx_0tx.rbf")
1360                                 self.u.set_mux(usrp.determine_rx_mux_value(self.u, self.rx_subdev_spec))
1361                                 # determine the daughterboard subdevice we're using
1362                                 self.subdev[0] = usrp.selected_subdev(self.u, self.rx_subdev_spec)
1363                                 self.subdev[1] = self.subdev[0]
1364                                 self.cardtype = self.subdev[0].dbid()
1365                         else:
1366                                 self.u=usrp.source_c(decim_rate=self.decim, nchan=2,fusb_block_size=8192)
1367                                 self.subdev[0] = usrp.selected_subdev(self.u, (0, 0))
1368                                 self.subdev[1] = usrp.selected_subdev(self.u, (1, 0))
1369                                 self.cardtype = self.subdev[0].dbid()
1370                                 self.u.set_mux(0x32103210)
1371                                 c1 = self.subdev[0].name()
1372                                 c2 = self.subdev[1].name()
1373                                 if (c1 != c2):
1374                                         print "Must have identical cardtypes for --dual_mode or --interferometer"
1375                                         sys.exit(1)
1376                                 #
1377                                 # Set 8-bit mode
1378                                 #
1379                                 
1380                                 width = 8
1381                                 shift = 8
1382                                 format = self.u.make_format(width, shift)
1383                                 r = self.u.set_format(format)
1384                 else:
1385                         if (self.dual_mode == True or self.interferometer == True):
1386                                 print "Cannot use dual_mode or interferometer with single USRP2"
1387                                 sys.exit(1)
1388                         self.u = usrp2.source_32fc(self.interface, self.mac_addr)
1389                         self.u.set_decim (self.decim)
1390                         self.cardtype = self.u.daughterboard_id()
1391
1392 def main ():
1393         app = stdgui2.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1394         app.MainLoop()
1395
1396 if __name__ == '__main__':
1397         main ()