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 == usrp_dbid.DBS_RX:
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
606 r = usrp.tune(self.u, self.subdev[0].which(), self.subdev[0], target_freq)
607 r = usrp.tune(self.u, self.subdev[1].which(), self.subdev[1], target_freq)
609 self.myform['freq'].set_value(target_freq) # update displayed value
611 # Make sure calibrator knows our target freq
614 # Remember centerfreq---used for doppler calcs
615 delta = self.centerfreq - target_freq
616 self.centerfreq = target_freq
617 self.observing -= delta
618 self.scope.set_baseband_freq (self.observing)
619 self.myform['baseband'].set_value(r.baseband_freq)
620 self.myform['ddc'].set_value(r.dxc_freq)
622 if (self.use_notches):
623 self.compute_notch_taps(self.notches)
624 if self.dual_mode == False and self.interferometer == False:
625 self.notch_filt.set_taps(self.notch_taps)
627 self.notch_filt1.set_taps(self.notch_taps)
628 self.notch_filt2.set_taps(self.notch_taps)
634 def set_decln(self, dec):
636 self.myform['decln'].set_value(dec) # update displayed value
638 def set_gain(self, gain):
639 self.myform['gain'].set_value(gain) # update displayed value
640 self.subdev[0].set_gain(gain)
641 self.subdev[1].set_gain(gain)
644 def set_averaging(self, avval):
645 self.myform['average'].set_value(avval)
646 self.scope.set_avg_alpha(1.0/(avval))
647 self.scope.set_average(True)
648 self.avg_alpha = avval
650 def set_integration(self, integval):
651 if self.setimode == False:
652 self.integrator.set_taps(1.0/((integval)*(self.bw/2)))
653 self.myform['integration'].set_value(integval)
654 self.integ = integval
658 # Used to update LMST display, as well as current
661 # We also write external data-logging files here
663 def lmst_timeout(self):
664 self.locality.date = ephem.now()
665 if self.setimode == False:
666 x = self.probe.level()
667 sidtime = self.locality.sidereal_time()
669 s = str(ephem.hours(sidtime)) + " " + self.sunstate
670 # Continuum detector value
671 if self.setimode == False:
673 s = s + "\nDet: " + str(sx)
675 sx = "%2d" % self.hitcounter
676 s1 = "%2d" % self.s1hitcounter
677 s2 = "%2d" % self.s2hitcounter
678 sa = "%4.2f" % self.avgdelta
679 sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
680 s = s + "\nHits: " + str(sx) + "\nS1:" + str(s1) + " S2:" + str(s2)
681 s = s + "\nAv D: " + str(sa) + "\nCh lim: " + str(sy)
683 self.myform['lmst_high'].set_value(s)
686 # Write data out to recording files
688 if self.setimode == False:
689 self.write_continuum_data(x,sidtime)
690 self.write_spectral_data(self.fft_outbuf,sidtime)
693 self.seti_analysis(self.fft_outbuf,sidtime)
695 if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
697 self.setifreq_current = self.setifreq_current + self.fft_input_rate
698 if (self.setifreq_current > self.setifreq_upper):
699 self.setifreq_current = self.setifreq_lower
700 self.set_freq(self.setifreq_current)
701 # Make sure we zero-out the hits array when changing
703 self.hits_array[:,:] = 0.0
704 self.hit_intensities[:,:] = 0.0
706 def other_timeout(self):
707 if (self.switch_state == 0):
708 self.switch_state = 1
710 elif (self.switch_state == 1):
711 self.switch_state = 0
713 if (self.switch_state == 0):
715 self.cmute.set_n(int(1.0e9))
717 elif (self.switch_state == 1):
718 self.mute.set_n(int(1.0e9))
721 if (self.ref_fifo != "@@@@"):
722 self.ref_fifo_file.write(str(self.switch_state)+"\n")
723 self.ref_fifo_file.flush()
725 self.avg_reference_value = self.cprobe.level()
728 # Set reference value
730 self.reference_level.set_k(-1.0 * (self.avg_reference_value/self.reference_divisor))
732 def fft_outfunc(self,data,l):
735 def write_continuum_data(self,data,sidtime):
737 # Create localtime structure for producing filename
738 foo = time.localtime()
740 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
741 foo.tm_mon, foo.tm_mday, foo.tm_hour)
743 # Open the data file, appending
744 continuum_file = open (filenamestr+".tpdat","a")
758 # If time to write full header info (saves storage this way)
760 if (now - self.continuum_then > 20):
761 self.sun.compute(self.locality)
763 sunset = self.locality.next_setting(self.sun)
764 sunrise = self.locality.next_rising(self.sun)
767 if ((sunrise < enow) and (enow < sunset)):
770 self.continuum_then = now
772 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
773 continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
774 continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
776 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
778 continuum_file.close()
781 def write_spectral_data(self,data,sidtime):
786 # If time to write out spectral data
787 # We don't write this out every time, in order to
788 # save disk space. Since the spectral data are
789 # typically heavily averaged, writing this data
790 # "once in a while" is OK.
792 if (now - self.spectral_then >= delta):
793 self.spectral_then = now
795 # Get localtime structure to make filename from
796 foo = time.localtime()
799 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
800 foo.tm_mon, foo.tm_mday, foo.tm_hour)
803 spectral_file = open (filenamestr+".sdat","a")
805 # Setup data fields to be written
815 spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
816 spectral_file.write (" [ ")
818 spectral_file.write(" "+str(r))
820 spectral_file.write(" ]\n")
821 spectral_file.close()
826 def seti_analysis(self,fftbuf,sidtime):
831 if self.seticounter < self.setitimer:
832 self.seticounter = self.seticounter + 1
837 # Run through FFT output buffer, computing standard deviation (Sigma)
839 # First compute average
841 avg = avg + fftbuf[i]
845 # Then compute standard deviation (Sigma)
848 sigma = sigma + (d*d)
850 sigma = Numeric.sqrt(sigma/l)
853 # Snarfle through the FFT output buffer again, looking for
854 # outlying data points
856 start_f = self.observing - (self.fft_input_rate/2)
859 f_incr = self.fft_input_rate / l
863 for i in range(l/2,l):
865 # If current FFT buffer has an item that exceeds the specified
868 if ((fftbuf[i] - avg) > (self.setik * sigma)):
869 hits.append(current_f)
870 hit_intensities.append(fftbuf[i])
871 current_f = current_f + f_incr
874 for i in range(0,l/2):
876 # If current FFT buffer has an item that exceeds the specified
879 if ((fftbuf[i] - avg) > (self.setik * sigma)):
880 hits.append(current_f)
881 hit_intensities.append(fftbuf[i])
882 current_f = current_f + f_incr
890 # OK, so we have some hits in the FFT buffer
891 # They'll have a rather substantial gauntlet to run before
892 # being declared a real "hit"
896 self.s1hitcounter = self.s1hitcounter + len(hits)
898 # Weed out buffers with an excessive number of
899 # signals above Sigma
900 if (len(hits) > self.nhits):
904 # Weed out FFT buffers with apparent multiple narrowband signals
905 # separated significantly in frequency. This means that a
906 # single signal spanning multiple bins is OK, but a buffer that
907 # has multiple, apparently-separate, signals isn't OK.
911 for i in range(1,len(hits)):
912 if ((hits[i] - last) > (f_incr*3.0)):
917 self.s2hitcounter = self.s2hitcounter + ns2
920 # Run through all available hit buffers, computing difference between
921 # frequencies found there, if they're all within the chirp limits
925 f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
928 for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
929 f_ds[0] = abs(self.hits_array[i,0] - hits[i])
930 for j in range(1,len(f_ds)):
931 f_ds[j] = abs(self.hits_array[i,j] - self.hits_array[i,0])
932 avg_delta = avg_delta + f_ds[j]
935 if (self.seti_isahit (f_ds)):
937 self.hitcounter = self.hitcounter + 1
940 if (avg_delta/k < (self.seti_fft_bandwidth/2)):
941 self.avgdelta = avg_delta / k
943 # Save 'n shuffle hits
944 # Old hit buffers percolate through the hit buffers
945 # (there are self.nhitlines of these buffers)
946 # and then drop off the end
947 # A consequence is that while the nhitlines buffers are filling,
948 # you can get some absurd values for self.avgdelta, because some
949 # of the buffers are full of zeros
950 for i in range(self.nhitlines,1):
951 self.hits_array[:,i] = self.hits_array[:,i-1]
952 self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
954 for i in range(0,len(hits)):
955 self.hits_array[i,0] = hits[i]
956 self.hit_intensities[i,0] = hit_intensities[i]
958 # Finally, write the hits/intensities buffer
960 self.write_hits(sidtime)
964 def seti_isahit(self,fdiffs):
967 for i in range(0,len(fdiffs)):
968 if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
969 truecount = truecount + 1
971 if truecount == len(fdiffs):
976 def write_hits(self,sidtime):
977 # Create localtime structure for producing filename
978 foo = time.localtime()
980 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
981 foo.tm_mon, foo.tm_mday, foo.tm_hour)
983 # Open the data file, appending
984 hits_file = open (filenamestr+".seti","a")
986 # Write sidtime first
987 hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
990 # Then write the hits/hit intensities buffers with enough
991 # "syntax" to allow parsing by external (not yet written!)
994 for i in range(0,self.nhitlines):
996 for j in range(0,self.nhits):
997 hits_file.write(str(self.hits_array[j,i])+":")
998 hits_file.write(str(self.hit_intensities[j,i])+",")
999 hits_file.write("\n")
1003 def xydfunc(self,func,xyv):
1004 if self.setimode == True:
1006 magn = int(Numeric.log10(self.observing))
1007 if (magn == 6 or magn == 7 or magn == 8):
1009 dfreq = xyv[0] * pow(10.0,magn)
1011 ratio = self.observing / dfreq
1020 s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
1021 s2 = "\n%.3fkm/s" % vs
1022 self.myform['spec_data'].set_value(s+s2)
1024 tmpnotches = Numeric.zeros(self.NOTCH_TAPS,Numeric.Float64)
1026 if self.use_notches == True:
1027 for i in range(0,len(self.notches)):
1028 if self.notches[i] != 0 and abs(self.notches[i] - dfreq) < ((self.bw/self.NOTCH_TAPS)/2.0):
1032 for i in range(0,len(self.notches)):
1034 tmpnotches[j] = self.notches[i]
1037 for i in range(0,len(tmpnotches)):
1038 if (int(tmpnotches[i]) == 0):
1039 tmpnotches[i] = dfreq
1041 self.notches = tmpnotches
1042 self.compute_notch_taps(self.notches)
1043 if self.dual_mode == False and self.interferometer == False:
1044 self.notch_filt.set_taps(self.notch_taps)
1046 self.notch_filt1.set_taps(self.notch_taps)
1047 self.notch_filt2.set_taps(self.notch_taps)
1049 def xydfunc_waterfall(self,pos):
1050 lower = self.observing - (self.seti_fft_bandwidth / 2)
1051 upper = self.observing + (self.seti_fft_bandwidth / 2)
1052 binwidth = self.seti_fft_bandwidth / 1024
1053 s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
1054 self.myform['spec_data'].set_value(s)
1056 def toggle_cal(self):
1057 if (self.calstate == True):
1058 self.calstate = False
1059 self.u.write_io(0,0,(1<<15))
1060 self.calibrator.SetLabel("Calibration Source: Off")
1062 self.calstate = True
1063 self.u.write_io(0,(1<<15),(1<<15))
1064 self.calibrator.SetLabel("Calibration Source: On")
1066 def toggle_annotation(self):
1067 if (self.annotate_state == True):
1068 self.annotate_state = False
1069 self.annotation.SetLabel("Annotation: Off")
1071 self.annotate_state = True
1072 self.annotation.SetLabel("Annotation: On")
1074 # Turn scanning on/off
1075 # Called-back by "Recording" button
1077 def toggle_scanning(self):
1078 # Current scanning? Flip state
1079 if (self.scanning == True):
1080 self.scanning = False
1081 self.scan_control.SetLabel("Scan: Off")
1084 self.scanning = True
1085 self.scan_control.SetLabel("Scan: On ")
1087 def set_pd_offset(self,offs):
1088 self.myform['offset'].set_value(offs)
1089 self.calib_offset=offs
1090 x = self.calib_coeff / 100.0
1091 self.cal_offs.set_k(offs*(x*8000))
1093 def set_pd_gain(self,gain):
1094 self.myform['dcgain'].set_value(gain)
1095 self.cal_mult.set_k(gain*0.01)
1096 self.calib_coeff = gain
1098 self.cal_offs.set_k(self.calib_offset*(x*8000))
1100 def compute_notch_taps(self,notchlist):
1101 tmptaps = Numeric.zeros(self.NOTCH_TAPS,Numeric.Complex64)
1102 binwidth = self.bw / self.NOTCH_TAPS
1104 for i in range(0,self.NOTCH_TAPS):
1105 tmptaps[i] = complex(1.0,0.0)
1108 diff = i - self.observing
1111 if ((i < (self.observing - self.bw/2)) or (i > (self.observing + self.bw/2))):
1114 idx = diff / binwidth
1117 if (idx < 0 or idx > (self.NOTCH_TAPS/2)):
1119 tmptaps[idx] = complex(0.0, 0.0)
1122 idx = -diff / binwidth
1124 idx = (self.NOTCH_TAPS/2) - idx
1125 idx = int(idx+(self.NOTCH_TAPS/2))
1126 if (idx < 0 or idx >= (self.NOTCH_TAPS)):
1128 tmptaps[idx] = complex(0.0, 0.0)
1130 self.notch_taps = numpy.fft.ifft(tmptaps)
1133 # Setup common pieces of radiometer mode
1135 def setup_radiometer_common(self,n):
1136 # The IIR integration filter for post-detection
1137 self.integrator = gr.single_pole_iir_filter_ff(1.0)
1138 self.integrator.set_taps (1.0/self.bw)
1140 if (self.use_notches == True):
1141 self.compute_notch_taps(self.notches)
1143 self.notch_filt1 = gr.fft_filter_ccc(1, self.notch_taps)
1144 self.notch_filt2 = gr.fft_filter_ccc(1, self.notch_taps)
1146 self.notch_filt = gr.fft_filter_ccc(1, self.notch_taps)
1150 self.probe = gr.probe_signal_f()
1153 # Continuum calibration stuff
1155 x = self.calib_coeff/100.0
1156 self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0)
1157 self.cal_offs = gr.add_const_ff(self.calib_offset*(x*8000))
1160 # Mega decimator after IIR filter
1162 if (self.switch_mode == False):
1163 self.keepn = gr.keep_one_in_n(gr.sizeof_float, self.bw)
1165 self.keepn = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/2))
1168 # For the Dicke-switching scheme
1170 #self.switch = gr.multiply_const_ff(1.0)
1173 if (self.switch_mode == True):
1174 self.vector = gr.vector_sink_f()
1175 self.swkeep = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/3))
1176 self.mute = gr.keep_one_in_n(gr.sizeof_float, 1)
1177 self.cmute = gr.keep_one_in_n(gr.sizeof_float, int(1.0e9))
1178 self.cintegrator = gr.single_pole_iir_filter_ff(1.0/(self.bw/2))
1179 self.cprobe = gr.probe_signal_f()
1181 self.mute = gr.multiply_const_ff(1.0)
1184 self.avg_reference_value = 0.0
1185 self.reference_level = gr.add_const_ff(0.0)
1188 # Setup ordinary single-channel radiometer mode
1190 def setup_normal(self, setimode):
1192 self.setup_radiometer_common(1)
1195 if (self.use_notches == True):
1196 self.shead = self.notch_filt
1200 if setimode == False:
1202 self.detector = gr.complex_to_mag_squared()
1203 self.connect(self.shead, self.scope)
1205 if (self.use_notches == False):
1206 self.connect(self.head, self.detector, self.mute, self.reference_level,
1207 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1209 self.connect(self.head, self.notch_filt, self.detector, self.mute, self.reference_level,
1210 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1212 self.connect(self.cal_offs, self.probe)
1215 # Add a side-chain detector chain, with a different integrator, for sampling
1216 # The reference channel data
1217 # This is used to derive the offset value for self.reference_level, used above
1219 if (self.switch_mode == True):
1220 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)
1225 # Setup dual-channel (two antenna, usual orthogonal polarity probes in the same waveguide)
1227 def setup_dual(self, setimode):
1229 self.setup_radiometer_common(2)
1231 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1232 self.addchans = gr.add_cc ()
1233 self.detector = gr.add_ff ()
1234 self.h_power = gr.complex_to_mag_squared()
1235 self.v_power = gr.complex_to_mag_squared()
1236 self.connect (self.u, self.di)
1238 if (self.use_notches == True):
1239 self.connect((self.di, 0), self.notch_filt1, (self.addchans, 0))
1240 self.connect((self.di, 1), self.notch_filt2, (self.addchans, 1))
1243 # For spectral, adding the two channels works, assuming no gross
1244 # phase or amplitude error
1245 self.connect ((self.di, 0), (self.addchans, 0))
1246 self.connect ((self.di, 1), (self.addchans, 1))
1249 # Connect heads of spectral and total-power chains
1251 if (self.use_notches == False):
1254 self.head = (self.notch_filt1, self.notch_filt2)
1256 self.shead = self.addchans
1258 if (setimode == False):
1260 # For dual-polarization mode, we compute the sum of the
1261 # powers on each channel, after they've been detected
1263 self.detector = gr.add_ff()
1266 # In dual-polarization mode, we compute things a little differently
1267 # In effect, we have two radiometer chains, terminating in an adder
1269 if self.use_notches == True:
1270 self.connect(self.notch_filt1, self.h_power)
1271 self.connect(self.notch_filt2, self.v_power)
1273 self.connect((self.head, 0), self.h_power)
1274 self.connect((self.head, 1), self.v_power)
1275 self.connect(self.h_power, (self.detector, 0))
1276 self.connect(self.v_power, (self.detector, 1))
1277 self.connect(self.detector, self.mute, self.reference_level,
1278 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1279 self.connect(self.cal_offs, self.probe)
1280 self.connect(self.shead, self.scope)
1283 # Add a side-chain detector chain, with a different integrator, for sampling
1284 # The reference channel data
1285 # This is used to derive the offset value for self.reference_level, used above
1287 if (self.switch_mode == True):
1288 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)
1292 # Setup correlating interferometer mode
1294 def setup_interferometer(self, setimode):
1295 self.setup_radiometer_common(2)
1297 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1298 self.connect (self.u, self.di)
1299 self.corr = gr.multiply_cc()
1300 self.c2f = gr.complex_to_float()
1302 self.shead = (self.di, 0)
1304 # Channel 0 to multiply port 0
1305 # Channel 1 to multiply port 1
1306 if (self.use_notches == False):
1307 self.connect((self.di, 0), (self.corr, 0))
1308 self.connect((self.di, 1), (self.corr, 1))
1310 self.connect((self.di, 0), self.notch_filt1, (self.corr, 0))
1311 self.connect((self.di, 1), self.notch_filt2, (self.corr, 0))
1314 # Multiplier (correlator) to complex-to-float, followed by integrator, etc
1316 self.connect(self.corr, self.c2f, self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1319 # FFT scope gets only 1 channel
1320 # FIX THIS, by cross-correlating the *outputs* of two different FFTs, then display
1323 self.connect(self.shead, self.scope)
1326 # Output of correlator/integrator chain to probe
1328 self.connect(self.cal_offs, self.probe)
1335 def setup_seti(self):
1336 self.connect (self.shead, self.fft_bandpass, self.scope)
1339 def setup_usrp(self):
1341 if (self.usrp2 == False):
1342 if (self.dual_mode == False and self.interferometer == False):
1343 if (self.decim > 4):
1344 self.u = usrp.source_c(decim_rate=self.decim,fusb_block_size=8192)
1346 self.u = usrp.source_c(decim_rate=self.decim,fusb_block_size=8192, fpga_filename="std_4rx_0tx.rbf")
1347 self.u.set_mux(usrp.determine_rx_mux_value(self.u, self.rx_subdev_spec))
1348 # determine the daughterboard subdevice we're using
1349 self.subdev[0] = usrp.selected_subdev(self.u, self.rx_subdev_spec)
1350 self.subdev[1] = self.subdev[0]
1351 self.cardtype = self.subdev[0].dbid()
1353 self.u=usrp.source_c(decim_rate=self.decim, nchan=2,fusb_block_size=8192)
1354 self.subdev[0] = usrp.selected_subdev(self.u, (0, 0))
1355 self.subdev[1] = usrp.selected_subdev(self.u, (1, 0))
1356 self.cardtype = self.subdev[0].dbid()
1357 self.u.set_mux(0x32103210)
1358 c1 = self.subdev[0].name()
1359 c2 = self.subdev[1].name()
1361 print "Must have identical cardtypes for --dual_mode or --interferometer"
1369 format = self.u.make_format(width, shift)
1370 r = self.u.set_format(format)
1372 if (self.dual_mode == True or self.interferometer == True):
1373 print "Cannot use dual_mode or interferometer with single USRP2"
1375 self.u = usrp2.source_32fc(self.interface, self.mac_addr)
1376 self.u.set_decim (self.decim)
1377 self.cardtype = self.u.daughterboard_id()
1380 app = stdgui2.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision: 10631 $", nstatus=1)
1383 if __name__ == '__main__':