3 # Copyright 2004,2005,2007 Free Software Foundation, Inc.
5 # This file is part of GNU Radio
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)
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.
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.
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
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)
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)
91 # Added this documentation
93 (options, args) = parser.parse_args()
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
104 self.decim = options.decim
105 self.rx_subdev_spec = options.rx_subdev_spec
107 if (options.interface != None and options.mac_addr != None):
108 self.mac_addr = options.mac_addr
109 self.interface = options.interface
112 self.NOTCH_TAPS = options.notch_taps
113 self.notches = Numeric.zeros(self.NOTCH_TAPS,Numeric.Float64)
114 # Get notch locations
117 self.notches[j] = float(i)
120 self.use_notches = options.notches
122 if (self.ref_fifo != None):
123 self.ref_fifo_file = open (self.ref_fifo, "r")
126 for modes in (self.dual_mode, self.interferometer):
128 modecount = modecount + 1
131 print "must select only 1 of --dual_mode, or --interferometer"
134 self.chartneeded = True
136 if (self.setimode == True):
137 self.chartneeded = False
139 if (self.setimode == True and self.interferometer == True):
140 print "can't pick both --setimode and --interferometer"
143 if (self.setimode == True and self.switch_mode == True):
144 print "can't pick both --setimode and --switch_mode"
147 if (self.interferometer == True and self.switch_mode == True):
148 print "can't pick both --interferometer and --switch_mode"
152 self.normal_mode = True
154 self.show_debug_info = True
156 # Pick up waterfall option
157 self.waterfall = options.waterfall
160 self.setimode = options.setimode
162 self.setik = options.setik
163 self.seti_fft_bandwidth = int(options.setibandwidth)
166 binwidth = self.seti_fft_bandwidth / options.fft_size
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.
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
175 upper_limit = binwidth / 0.10
176 self.setitimer = int(upper_limit * 2.00)
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
183 # Reset hit counters to 0
185 self.s1hitcounter = 0
186 self.s2hitcounter = 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)
196 # Maximum "hits" in a line
199 # Number of lines for analysis
202 # We change center frequencies based on nhitlines and setitimer
203 self.setifreq_timer = self.setitimer * (self.nhitlines * 5)
205 # Create actual timer
206 self.seti_then = time.time()
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
219 if self.calib_coeff < 1:
221 if self.calib_coeff > 100:
222 self.calib_coeff = 100
224 self.integ = options.integ
225 self.avg_alpha = options.avg
226 self.gain = options.gain
227 self.decln = options.decln
229 # Set initial values for datalogging timed-output
230 self.continuum_then = time.time()
231 self.spectral_then = time.time()
236 self.subdev = [(0, 0), (0,0)]
239 # If SETI mode, we always run at maximum USRP decimation
244 if (self.dual_mode == True and self.decim <= 4):
245 print "Cannot use decim <= 4 with dual_mode"
250 # Set initial declination
251 self.decln = options.decln
253 input_rate = self.u.adc_freq() / self.u.decim_rate()
256 # Set prefix for data files
258 self.prefix = options.prefix
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.
266 self.fft_rate = options.fft_rate
268 self.fft_size = int(options.fft_size)
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
275 self.fft_outbuf = Numeric.zeros(self.fft_size, Numeric.Float64)
278 # If SETI mode, only look at seti_fft_bandwidth
282 self.fft_input_rate = self.seti_fft_bandwidth
285 # Build a decimating bandpass filter
287 self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
289 -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
290 gr.firdes.WIN_HAMMING, 0)
293 # Compute required decimation factor
295 decimation = int(input_rate/self.fft_input_rate)
296 self.fft_bandpass = gr.fir_filter_ccc (decimation,
299 self.fft_input_rate = input_rate
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)
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)
312 # Set up ephemeris data
313 self.locality = ephem.Observer()
314 self.locality.long = str(options.longitude)
315 self.locality.lat = str(options.latitude)
317 # We make notes about Sunset/Sunrise in Continuum log files
318 self.sun = ephem.Sun()
321 # Set up stripchart display
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,
332 xlabel="LMST Offset (Seconds)",
333 scaling=1.0, ylabel=options.ylabel,
334 divbase=options.divbase)
336 # Set center frequency
337 self.centerfreq = options.freq
339 # Set observing frequency (might be different from actual programmed
341 if options.observing == 0.0:
342 self.observing = options.freq
344 self.observing = options.observing
346 # Remember our input bandwidth
351 # The strip chart is fed at a constant 1Hz rate
355 # Call constructors for receive chains
358 if (self.dual_mode == True):
359 self.setup_dual (self.setimode)
361 if (self.interferometer == True):
362 self.setup_interferometer(self.setimode)
364 if (self.normal_mode == True):
365 self.setup_normal(self.setimode)
367 if (self.setimode == True):
370 self._build_gui(vbox)
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))
381 if self.setimode == False:
382 # Make integrator agree with command line
383 self.set_integration(int(options.integ))
385 self.avg_alpha = options.avg
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)
392 if self.setimode == False:
394 self.chart.set_y_per_div(options.division)
395 # Set reference(MAX) level
396 self.chart.set_ref_level(options.reflevel)
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
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
410 # Set the initial gain control
411 self.set_gain(options.gain)
413 if not(self.set_freq(options.freq)):
414 self._set_status_msg("Failed to set initial frequency")
417 self.set_decln (self.decln)
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())
426 self.myform['dbname'].set_value(self.subdev[0].name())
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
433 self.subdev[0].set_bw(lbw)
434 self.subdev[1].set_bw(lbw)
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)
442 def _set_status_msg(self, msg):
443 self.frame.GetStatusBar().SetStatusText(msg, 0)
445 def _build_gui(self, vbox):
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)
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
459 return self.set_freq(kv['freq'])
461 def _form_set_decln(kv):
462 return self.set_decln(kv['decln'])
464 # Position the FFT display
465 vbox.Add(self.scope.win, 15, wx.EXPAND)
467 if self.setimode == False:
468 # Position the Total-power stripchart
469 vbox.Add(self.chart.win, 15, wx.EXPAND)
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))
480 vbox1.Add((4,0), 0, 0)
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)
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)
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",
497 min=int(g[0]), max=int(g[1]),
498 callback=self.set_gain)
500 vbox2.Add((4,0), 0, 0)
501 if self.setimode == True:
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)
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,
514 callback=self.toggle_scanning)
516 buttonbox.Add(self.scan_control, 0, wx.CENTER)
517 vbox2.Add(buttonbox, 0, wx.CENTER)
519 vbox2.Add((4,0), 0, 0)
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)
525 vbox2.Add((4,0), 0, 0)
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)
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)
544 if self.setimode == False:
545 hbox.Add(vbox3, wx.ALIGN_RIGHT, 0)
547 vbox.Add(hbox, 0, wx.EXPAND)
549 self._build_subpanel(vbox)
551 self.lmst_timer = wx.PyTimer(self.lmst_timeout)
552 self.other_timer = wx.PyTimer(self.other_timeout)
555 def _build_subpanel(self, vbox_arg):
556 # build a secondary information panel (sometimes hidden)
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)
561 if not(self.show_debug_info):
568 #panel = wx.Panel(self.panel, -1)
569 #vbox = wx.BoxSizer(wx.VERTICAL)
571 hbox = wx.BoxSizer(wx.HORIZONTAL)
573 myform['decim'] = form.static_float_field(
574 parent=panel, sizer=hbox, label="Decim")
577 myform['USB BW'] = form.static_float_field(
578 parent=panel, sizer=hbox, label="USB BW")
581 myform['dbname'] = form.static_text_field(
582 parent=panel, sizer=hbox)
585 myform['baseband'] = form.static_float_field(
586 parent=panel, sizer=hbox, label="Analog BB")
589 myform['ddc'] = form.static_float_field(
590 parent=panel, sizer=hbox, label="DDC")
593 vbox.Add(hbox, 0, wx.EXPAND)
597 def set_freq(self, target_freq):
599 Set the center frequency we're interested in.
601 @param target_freq: frequency in Hz
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.
610 # Everything except BASIC_RX should support usrp.tune()
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)
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:
621 self.myform['freq'].set_value(target_freq) # update displayed value
623 # Make sure calibrator knows our target freq
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)
632 self.myform['baseband'].set_value(r.baseband_freq)
633 self.myform['ddc'].set_value(r.dxc_freq)
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)
640 self.notch_filt1.set_taps(self.notch_taps)
641 self.notch_filt2.set_taps(self.notch_taps)
647 def set_decln(self, dec):
649 self.myform['decln'].set_value(dec) # update displayed value
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)
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
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
671 # Used to update LMST display, as well as current
674 # We also write external data-logging files here
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()
682 s = str(ephem.hours(sidtime)) + " " + self.sunstate
683 # Continuum detector value
684 if self.setimode == False:
686 s = s + "\nDet: " + str(sx)
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)
696 self.myform['lmst_high'].set_value(s)
699 # Write data out to recording files
701 if self.setimode == False:
702 self.write_continuum_data(x,sidtime)
703 self.write_spectral_data(self.fft_outbuf,sidtime)
706 self.seti_analysis(self.fft_outbuf,sidtime)
708 if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
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
716 self.hits_array[:,:] = 0.0
717 self.hit_intensities[:,:] = 0.0
719 def other_timeout(self):
720 if (self.switch_state == 0):
721 self.switch_state = 1
723 elif (self.switch_state == 1):
724 self.switch_state = 0
726 if (self.switch_state == 0):
728 self.cmute.set_n(int(1.0e9))
730 elif (self.switch_state == 1):
731 self.mute.set_n(int(1.0e9))
734 if (self.ref_fifo != "@@@@"):
735 self.ref_fifo_file.write(str(self.switch_state)+"\n")
736 self.ref_fifo_file.flush()
738 self.avg_reference_value = self.cprobe.level()
741 # Set reference value
743 self.reference_level.set_k(-1.0 * (self.avg_reference_value/self.reference_divisor))
745 def fft_outfunc(self,data,l):
748 def write_continuum_data(self,data,sidtime):
750 # Create localtime structure for producing filename
751 foo = time.localtime()
753 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
754 foo.tm_mon, foo.tm_mday, foo.tm_hour)
756 # Open the data file, appending
757 continuum_file = open (filenamestr+".tpdat","a")
771 # If time to write full header info (saves storage this way)
773 if (now - self.continuum_then > 20):
774 self.sun.compute(self.locality)
776 sunset = self.locality.next_setting(self.sun)
777 sunrise = self.locality.next_rising(self.sun)
780 if ((sunrise < enow) and (enow < sunset)):
783 self.continuum_then = now
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")
789 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
791 continuum_file.close()
794 def write_spectral_data(self,data,sidtime):
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.
805 if (now - self.spectral_then >= delta):
806 self.spectral_then = now
808 # Get localtime structure to make filename from
809 foo = time.localtime()
812 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
813 foo.tm_mon, foo.tm_mday, foo.tm_hour)
816 spectral_file = open (filenamestr+".sdat","a")
818 # Setup data fields to be written
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 (" [ ")
831 spectral_file.write(" "+str(r))
833 spectral_file.write(" ]\n")
834 spectral_file.close()
839 def seti_analysis(self,fftbuf,sidtime):
844 if self.seticounter < self.setitimer:
845 self.seticounter = self.seticounter + 1
850 # Run through FFT output buffer, computing standard deviation (Sigma)
852 # First compute average
854 avg = avg + fftbuf[i]
858 # Then compute standard deviation (Sigma)
861 sigma = sigma + (d*d)
863 sigma = Numeric.sqrt(sigma/l)
866 # Snarfle through the FFT output buffer again, looking for
867 # outlying data points
869 start_f = self.observing - (self.fft_input_rate/2)
872 f_incr = self.fft_input_rate / l
876 for i in range(l/2,l):
878 # If current FFT buffer has an item that exceeds the specified
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
887 for i in range(0,l/2):
889 # If current FFT buffer has an item that exceeds the specified
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
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"
909 self.s1hitcounter = self.s1hitcounter + len(hits)
911 # Weed out buffers with an excessive number of
912 # signals above Sigma
913 if (len(hits) > self.nhits):
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.
924 for i in range(1,len(hits)):
925 if ((hits[i] - last) > (f_incr*3.0)):
930 self.s2hitcounter = self.s2hitcounter + ns2
933 # Run through all available hit buffers, computing difference between
934 # frequencies found there, if they're all within the chirp limits
938 f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
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]
948 if (self.seti_isahit (f_ds)):
950 self.hitcounter = self.hitcounter + 1
953 if (avg_delta/k < (self.seti_fft_bandwidth/2)):
954 self.avgdelta = avg_delta / k
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]
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]
971 # Finally, write the hits/intensities buffer
973 self.write_hits(sidtime)
977 def seti_isahit(self,fdiffs):
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
984 if truecount == len(fdiffs):
989 def write_hits(self,sidtime):
990 # Create localtime structure for producing filename
991 foo = time.localtime()
993 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
994 foo.tm_mon, foo.tm_mday, foo.tm_hour)
996 # Open the data file, appending
997 hits_file = open (filenamestr+".seti","a")
999 # Write sidtime first
1000 hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
1003 # Then write the hits/hit intensities buffers with enough
1004 # "syntax" to allow parsing by external (not yet written!)
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")
1016 def xydfunc(self,func,xyv):
1017 if self.setimode == True:
1019 magn = int(Numeric.log10(self.observing))
1020 if (magn == 6 or magn == 7 or magn == 8):
1022 dfreq = xyv[0] * pow(10.0,magn)
1024 ratio = self.observing / dfreq
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)
1037 tmpnotches = Numeric.zeros(self.NOTCH_TAPS,Numeric.Float64)
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):
1045 for i in range(0,len(self.notches)):
1047 tmpnotches[j] = self.notches[i]
1050 for i in range(0,len(tmpnotches)):
1051 if (int(tmpnotches[i]) == 0):
1052 tmpnotches[i] = dfreq
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)
1059 self.notch_filt1.set_taps(self.notch_taps)
1060 self.notch_filt2.set_taps(self.notch_taps)
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)
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")
1075 self.calstate = True
1076 self.u.write_io(0,(1<<15),(1<<15))
1077 self.calibrator.SetLabel("Calibration Source: On")
1079 def toggle_annotation(self):
1080 if (self.annotate_state == True):
1081 self.annotate_state = False
1082 self.annotation.SetLabel("Annotation: Off")
1084 self.annotate_state = True
1085 self.annotation.SetLabel("Annotation: On")
1087 # Turn scanning on/off
1088 # Called-back by "Recording" button
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")
1097 self.scanning = True
1098 self.scan_control.SetLabel("Scan: On ")
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))
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
1111 self.cal_offs.set_k(self.calib_offset*(x*8000))
1113 def compute_notch_taps(self,notchlist):
1114 tmptaps = Numeric.zeros(self.NOTCH_TAPS,Numeric.Complex64)
1115 binwidth = self.bw / self.NOTCH_TAPS
1117 for i in range(0,self.NOTCH_TAPS):
1118 tmptaps[i] = complex(1.0,0.0)
1121 diff = i - self.observing
1124 if ((i < (self.observing - self.bw/2)) or (i > (self.observing + self.bw/2))):
1127 idx = diff / binwidth
1130 if (idx < 0 or idx > (self.NOTCH_TAPS/2)):
1132 tmptaps[idx] = complex(0.0, 0.0)
1135 idx = -diff / binwidth
1137 idx = (self.NOTCH_TAPS/2) - idx
1138 idx = int(idx+(self.NOTCH_TAPS/2))
1139 if (idx < 0 or idx >= (self.NOTCH_TAPS)):
1141 tmptaps[idx] = complex(0.0, 0.0)
1143 self.notch_taps = numpy.fft.ifft(tmptaps)
1146 # Setup common pieces of radiometer mode
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)
1153 if (self.use_notches == True):
1154 self.compute_notch_taps(self.notches)
1156 self.notch_filt1 = gr.fft_filter_ccc(1, self.notch_taps)
1157 self.notch_filt2 = gr.fft_filter_ccc(1, self.notch_taps)
1159 self.notch_filt = gr.fft_filter_ccc(1, self.notch_taps)
1163 self.probe = gr.probe_signal_f()
1166 # Continuum calibration stuff
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))
1173 # Mega decimator after IIR filter
1175 if (self.switch_mode == False):
1176 self.keepn = gr.keep_one_in_n(gr.sizeof_float, self.bw)
1178 self.keepn = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/2))
1181 # For the Dicke-switching scheme
1183 #self.switch = gr.multiply_const_ff(1.0)
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()
1194 self.mute = gr.multiply_const_ff(1.0)
1197 self.avg_reference_value = 0.0
1198 self.reference_level = gr.add_const_ff(0.0)
1201 # Setup ordinary single-channel radiometer mode
1203 def setup_normal(self, setimode):
1205 self.setup_radiometer_common(1)
1208 if (self.use_notches == True):
1209 self.shead = self.notch_filt
1213 if setimode == False:
1215 self.detector = gr.complex_to_mag_squared()
1216 self.connect(self.shead, self.scope)
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)
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)
1225 self.connect(self.cal_offs, self.probe)
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
1232 if (self.switch_mode == True):
1233 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)
1238 # Setup dual-channel (two antenna, usual orthogonal polarity probes in the same waveguide)
1240 def setup_dual(self, setimode):
1242 self.setup_radiometer_common(2)
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)
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))
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))
1262 # Connect heads of spectral and total-power chains
1264 if (self.use_notches == False):
1267 self.head = (self.notch_filt1, self.notch_filt2)
1269 self.shead = self.addchans
1271 if (setimode == False):
1273 # For dual-polarization mode, we compute the sum of the
1274 # powers on each channel, after they've been detected
1276 self.detector = gr.add_ff()
1279 # In dual-polarization mode, we compute things a little differently
1280 # In effect, we have two radiometer chains, terminating in an adder
1282 if self.use_notches == True:
1283 self.connect(self.notch_filt1, self.h_power)
1284 self.connect(self.notch_filt2, self.v_power)
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)
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
1300 if (self.switch_mode == True):
1301 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)
1305 # Setup correlating interferometer mode
1307 def setup_interferometer(self, setimode):
1308 self.setup_radiometer_common(2)
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()
1315 self.shead = (self.di, 0)
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))
1323 self.connect((self.di, 0), self.notch_filt1, (self.corr, 0))
1324 self.connect((self.di, 1), self.notch_filt2, (self.corr, 0))
1327 # Multiplier (correlator) to complex-to-float, followed by integrator, etc
1329 self.connect(self.corr, self.c2f, self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1332 # FFT scope gets only 1 channel
1333 # FIX THIS, by cross-correlating the *outputs* of two different FFTs, then display
1336 self.connect(self.shead, self.scope)
1339 # Output of correlator/integrator chain to probe
1341 self.connect(self.cal_offs, self.probe)
1348 def setup_seti(self):
1349 self.connect (self.shead, self.fft_bandpass, self.scope)
1352 def setup_usrp(self):
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)
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()
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()
1374 print "Must have identical cardtypes for --dual_mode or --interferometer"
1382 format = self.u.make_format(width, shift)
1383 r = self.u.set_format(format)
1385 if (self.dual_mode == True or self.interferometer == True):
1386 print "Cannot use dual_mode or interferometer with single USRP2"
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()
1393 app = stdgui2.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1396 if __name__ == '__main__':