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="@@@@")
85 parser.add_option("-h", "--notch_taps", type="int", default=64, help="Number of notch taps")
86 parser.add_option("-n", "--notches", action="store_true",
87 default=False, help="Notch frequencies after all other args")
88 (options, args) = parser.parse_args()
90 self.setimode = options.setimode
91 self.dual_mode = options.dual_mode
92 self.interferometer = options.interferometer
93 self.normal_mode = False
94 self.switch_mode = options.switch_mode
96 self.reference_divisor = options.reference_divisor
97 self.ref_fifo = options.ref_fifo
99 self.NOTCH_TAPS = options.notch_taps
100 self.notches = Numeric.zeros(self.NOTCH_TAPS,Numeric.Float64)
101 # Get notch locations
104 self.notches[j] = float(i)
107 self.use_notches = options.notches
109 if (self.ref_fifo != "@@@@"):
110 self.ref_fifo_file = open (self.ref_fifo, "w")
113 for modes in (self.dual_mode, self.interferometer):
115 modecount = modecount + 1
118 print "must select only 1 of --dual_mode, or --interferometer"
121 self.chartneeded = True
123 if (self.setimode == True):
124 self.chartneeded = False
126 if (self.setimode == True and self.interferometer == True):
127 print "can't pick both --setimode and --interferometer"
130 if (self.setimode == True and self.switch_mode == True):
131 print "can't pick both --setimode and --switch_mode"
134 if (self.interferometer == True and self.switch_mode == True):
135 print "can't pick both --interferometer and --switch_mode"
139 self.normal_mode = True
141 self.show_debug_info = True
143 # Pick up waterfall option
144 self.waterfall = options.waterfall
147 self.setimode = options.setimode
149 self.setik = options.setik
150 self.seti_fft_bandwidth = int(options.setibandwidth)
153 binwidth = self.seti_fft_bandwidth / options.fft_size
155 # Use binwidth, and knowledge of likely chirp rates to set reasonable
156 # values for SETI analysis code. We assume that SETI signals will
157 # chirp at somewhere between 0.10Hz/sec and 0.25Hz/sec.
159 # upper_limit is the "worst case"--that is, the case for which we have
160 # to wait the longest to actually see any drift, due to the quantizing
162 upper_limit = binwidth / 0.10
163 self.setitimer = int(upper_limit * 2.00)
166 # Calculate the CHIRP values based on Hz/sec
167 self.CHIRP_LOWER = 0.10 * self.setitimer
168 self.CHIRP_UPPER = 0.25 * self.setitimer
170 # Reset hit counters to 0
172 self.s1hitcounter = 0
173 self.s2hitcounter = 0
175 # We scan through 2Mhz of bandwidth around the chosen center freq
176 self.seti_freq_range = options.seti_range
177 # Calculate lower edge
178 self.setifreq_lower = options.freq - (self.seti_freq_range/2)
179 self.setifreq_current = options.freq
180 # Calculate upper edge
181 self.setifreq_upper = options.freq + (self.seti_freq_range/2)
183 # Maximum "hits" in a line
186 # Number of lines for analysis
189 # We change center frequencies based on nhitlines and setitimer
190 self.setifreq_timer = self.setitimer * (self.nhitlines * 5)
192 # Create actual timer
193 self.seti_then = time.time()
195 # The hits recording array
196 self.hits_array = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
197 self.hit_intensities = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
198 # Calibration coefficient and offset
199 self.calib_coeff = options.calib_coeff
200 self.calib_offset = options.calib_offset
201 if self.calib_offset < -750:
202 self.calib_offset = -750
203 if self.calib_offset > 750:
204 self.calib_offset = 750
206 if self.calib_coeff < 1:
208 if self.calib_coeff > 100:
209 self.calib_coeff = 100
211 self.integ = options.integ
212 self.avg_alpha = options.avg
213 self.gain = options.gain
214 self.decln = options.decln
216 # Set initial values for datalogging timed-output
217 self.continuum_then = time.time()
218 self.spectral_then = time.time()
223 self.subdev = [(0, 0), (0,0)]
226 # If SETI mode, we always run at maximum USRP decimation
231 if (self.dual_mode == False and self.interferometer == False):
232 self.u = usrp.source_c(decim_rate=options.decim,fusb_block_size=8192)
233 self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
234 # determine the daughterboard subdevice we're using
235 self.subdev[0] = usrp.selected_subdev(self.u, options.rx_subdev_spec)
236 self.subdev[1] = self.subdev[0]
237 self.cardtype = self.subdev[0].dbid()
239 self.u=usrp.source_c(decim_rate=options.decim, nchan=2,fusb_block_size=8192)
240 self.subdev[0] = usrp.selected_subdev(self.u, (0, 0))
241 self.subdev[1] = usrp.selected_subdev(self.u, (1, 0))
242 self.cardtype = self.subdev[0].dbid()
243 self.u.set_mux(0x32103210)
244 c1 = self.subdev[0].name()
245 c2 = self.subdev[1].name()
247 print "Must have identical cardtypes for --dual_mode or --interferometer"
254 format = self.u.make_format(width, shift)
255 r = self.u.set_format(format)
257 # Set initial declination
258 self.decln = options.decln
260 input_rate = self.u.adc_freq() / self.u.decim_rate()
263 # Set prefix for data files
265 self.prefix = options.prefix
268 # The lower this number, the fewer sample frames are dropped
269 # in computing the FFT. A sampled approach is taken to
270 # computing the FFT of the incoming data, which reduces
271 # sensitivity. Increasing sensitivity inreases CPU loading.
273 self.fft_rate = options.fft_rate
275 self.fft_size = int(options.fft_size)
277 # This buffer is used to remember the most-recent FFT display
278 # values. Used later by self.write_spectral_data() to write
279 # spectral data to datalogging files, and by the SETI analysis
282 self.fft_outbuf = Numeric.zeros(self.fft_size, Numeric.Float64)
285 # If SETI mode, only look at seti_fft_bandwidth
289 self.fft_input_rate = self.seti_fft_bandwidth
292 # Build a decimating bandpass filter
294 self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
296 -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
297 gr.firdes.WIN_HAMMING, 0)
300 # Compute required decimation factor
302 decimation = int(input_rate/self.fft_input_rate)
303 self.fft_bandpass = gr.fir_filter_ccc (decimation,
306 self.fft_input_rate = input_rate
309 if self.waterfall == False:
310 self.scope = ra_fftsink.ra_fft_sink_c (panel,
311 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
312 fft_rate=int(self.fft_rate), title="Spectral",
313 ofunc=self.fft_outfunc, xydfunc=self.xydfunc)
315 self.scope = ra_waterfallsink.waterfall_sink_c (panel,
316 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
317 fft_rate=int(self.fft_rate), title="Spectral", ofunc=self.fft_outfunc, size=(1100, 600), xydfunc=self.xydfunc, ref_level=0, span=10)
319 # Set up ephemeris data
320 self.locality = ephem.Observer()
321 self.locality.long = str(options.longitude)
322 self.locality.lat = str(options.latitude)
324 # We make notes about Sunset/Sunrise in Continuum log files
325 self.sun = ephem.Sun()
328 # Set up stripchart display
330 if (self.dual_mode != False):
331 tit = "H+V Continuum"
332 if (self.interferometer != False):
333 tit = "East x West Correlation"
334 self.stripsize = int(options.stripsize)
335 if self.chartneeded == True:
336 self.chart = ra_stripchartsink.stripchart_sink_f (panel,
337 stripsize=self.stripsize,
339 xlabel="LMST Offset (Seconds)",
340 scaling=1.0, ylabel=options.ylabel,
341 divbase=options.divbase)
343 # Set center frequency
344 self.centerfreq = options.freq
346 # Set observing frequency (might be different from actual programmed
348 if options.observing == 0.0:
349 self.observing = options.freq
351 self.observing = options.observing
353 # Remember our input bandwidth
358 # The strip chart is fed at a constant 1Hz rate
362 # Call constructors for receive chains
365 if (self.dual_mode == True):
366 self.setup_dual (self.setimode)
368 if (self.interferometer == True):
369 self.setup_interferometer(self.setimode)
371 if (self.normal_mode == True):
372 self.setup_normal(self.setimode)
374 if (self.setimode == True):
377 self._build_gui(vbox)
379 # Make GUI agree with command-line
380 self.integ = options.integ
381 if self.setimode == False:
382 self.myform['integration'].set_value(int(options.integ))
383 self.myform['offset'].set_value(self.calib_offset)
384 self.myform['dcgain'].set_value(self.calib_coeff)
385 self.myform['average'].set_value(int(options.avg))
388 if self.setimode == False:
389 # Make integrator agree with command line
390 self.set_integration(int(options.integ))
392 self.avg_alpha = options.avg
394 # Make spectral averager agree with command line
395 if options.avg != 1.0:
396 self.scope.set_avg_alpha(float(1.0/options.avg))
397 self.scope.set_average(True)
399 if self.setimode == False:
401 self.chart.set_y_per_div(options.division)
402 # Set reference(MAX) level
403 self.chart.set_ref_level(options.reflevel)
407 if options.gain is None:
408 # if no gain was specified, use the mid-point in dB
409 g = self.subdev[0].gain_range()
410 options.gain = float(g[0]+g[1])/2
412 if options.freq is None:
413 # if no freq was specified, use the mid-point
414 r = self.subdev[0].freq_range()
415 options.freq = float(r[0]+r[1])/2
417 # Set the initial gain control
418 self.set_gain(options.gain)
420 if not(self.set_freq(options.freq)):
421 self._set_status_msg("Failed to set initial frequency")
424 self.set_decln (self.decln)
427 # RF hardware information
428 self.myform['decim'].set_value(self.u.decim_rate())
429 self.myform['USB BW'].set_value(self.u.adc_freq() / self.u.decim_rate())
430 if (self.dual_mode == True):
431 self.myform['dbname'].set_value(self.subdev[0].name()+'/'+self.subdev[1].name())
433 self.myform['dbname'].set_value(self.subdev[0].name())
435 # Set analog baseband filtering, if DBS_RX
436 if self.cardtype in (usrp_dbid.DBS_RX, usrp_dbid.DBS_RX_REV_2_1):
437 lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
440 self.subdev[0].set_bw(lbw)
441 self.subdev[1].set_bw(lbw)
443 # Start the timer for the LMST display and datalogging
444 self.lmst_timer.Start(1000)
445 if (self.switch_mode == True):
446 self.other_timer.Start(330)
449 def _set_status_msg(self, msg):
450 self.frame.GetStatusBar().SetStatusText(msg, 0)
452 def _build_gui(self, vbox):
454 def _form_set_freq(kv):
455 # Adjust current SETI frequency, and limits
456 self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
457 self.setifreq_current = kv['freq']
458 self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)
460 # Reset SETI analysis timer
461 self.seti_then = time.time()
462 # Zero-out hits array when changing frequency
463 self.hits_array[:,:] = 0.0
464 self.hit_intensities[:,:] = -60.0
466 return self.set_freq(kv['freq'])
468 def _form_set_decln(kv):
469 return self.set_decln(kv['decln'])
471 # Position the FFT display
472 vbox.Add(self.scope.win, 15, wx.EXPAND)
474 if self.setimode == False:
475 # Position the Total-power stripchart
476 vbox.Add(self.chart.win, 15, wx.EXPAND)
478 # add control area at the bottom
479 self.myform = myform = form.form()
480 hbox = wx.BoxSizer(wx.HORIZONTAL)
481 hbox.Add((7,0), 0, wx.EXPAND)
482 vbox1 = wx.BoxSizer(wx.VERTICAL)
483 myform['freq'] = form.float_field(
484 parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
485 callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
487 vbox1.Add((4,0), 0, 0)
489 myform['lmst_high'] = form.static_text_field(
490 parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
491 vbox1.Add((4,0), 0, 0)
493 if self.setimode == False:
494 myform['spec_data'] = form.static_text_field(
495 parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
496 vbox1.Add((4,0), 0, 0)
498 vbox2 = wx.BoxSizer(wx.VERTICAL)
499 if self.setimode == False:
500 vbox3 = wx.BoxSizer(wx.VERTICAL)
501 g = self.subdev[0].gain_range()
502 myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
504 min=int(g[0]), max=int(g[1]),
505 callback=self.set_gain)
507 vbox2.Add((4,0), 0, 0)
508 if self.setimode == True:
512 myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2,
513 label="Spectral Averaging (FFT frames)", weight=1, min=1, max=max_savg, callback=self.set_averaging)
515 # Set up scan control button when in SETI mode
516 if (self.setimode == True):
517 # SETI scanning control
518 buttonbox = wx.BoxSizer(wx.HORIZONTAL)
519 self.scan_control = form.button_with_callback(self.panel,
521 callback=self.toggle_scanning)
523 buttonbox.Add(self.scan_control, 0, wx.CENTER)
524 vbox2.Add(buttonbox, 0, wx.CENTER)
526 vbox2.Add((4,0), 0, 0)
528 if self.setimode == False:
529 myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
530 label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)
532 vbox2.Add((4,0), 0, 0)
534 myform['decln'] = form.float_field(
535 parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
536 callback=myform.check_input_and_call(_form_set_decln))
537 vbox2.Add((4,0), 0, 0)
539 if self.setimode == False:
540 myform['offset'] = form.slider_field(parent=self.panel, sizer=vbox3,
541 label="Post-Detector Offset", weight=1, min=-750, max=750,
542 callback=self.set_pd_offset)
543 vbox3.Add((2,0), 0, 0)
544 myform['dcgain'] = form.slider_field(parent=self.panel, sizer=vbox3,
545 label="Post-Detector Gain", weight=1, min=1, max=100,
546 callback=self.set_pd_gain)
547 vbox3.Add((2,0), 0, 0)
548 hbox.Add(vbox1, 0, 0)
549 hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
551 if self.setimode == False:
552 hbox.Add(vbox3, wx.ALIGN_RIGHT, 0)
554 vbox.Add(hbox, 0, wx.EXPAND)
556 self._build_subpanel(vbox)
558 self.lmst_timer = wx.PyTimer(self.lmst_timeout)
559 self.other_timer = wx.PyTimer(self.other_timeout)
562 def _build_subpanel(self, vbox_arg):
563 # build a secondary information panel (sometimes hidden)
565 # FIXME figure out how to have this be a subpanel that is always
566 # created, but has its visibility controlled by foo.Show(True/False)
568 if not(self.show_debug_info):
575 #panel = wx.Panel(self.panel, -1)
576 #vbox = wx.BoxSizer(wx.VERTICAL)
578 hbox = wx.BoxSizer(wx.HORIZONTAL)
580 myform['decim'] = form.static_float_field(
581 parent=panel, sizer=hbox, label="Decim")
584 myform['USB BW'] = form.static_float_field(
585 parent=panel, sizer=hbox, label="USB BW")
588 myform['dbname'] = form.static_text_field(
589 parent=panel, sizer=hbox)
592 myform['baseband'] = form.static_float_field(
593 parent=panel, sizer=hbox, label="Analog BB")
596 myform['ddc'] = form.static_float_field(
597 parent=panel, sizer=hbox, label="DDC")
600 vbox.Add(hbox, 0, wx.EXPAND)
604 def set_freq(self, target_freq):
606 Set the center frequency we're interested in.
608 @param target_freq: frequency in Hz
611 Tuning is a two step process. First we ask the front-end to
612 tune as close to the desired frequency as it can. Then we use
613 the result of that operation and our target_frequency to
614 determine the value for the digital down converter.
617 # Everything except BASIC_RX should support usrp.tune()
619 if not (self.cardtype == usrp_dbid.BASIC_RX):
620 r = usrp.tune(self.u, self.subdev[0].which(), self.subdev[0], target_freq)
621 r = usrp.tune(self.u, self.subdev[1].which(), self.subdev[1], target_freq)
623 r = self.u.set_rx_freq(0, target_freq)
624 f = self.u.rx_freq(0)
625 if abs(f-target_freq) > 2.0e3:
628 self.myform['freq'].set_value(target_freq) # update displayed value
630 # Make sure calibrator knows our target freq
633 # Remember centerfreq---used for doppler calcs
634 delta = self.centerfreq - target_freq
635 self.centerfreq = target_freq
636 self.observing -= delta
637 self.scope.set_baseband_freq (self.observing)
639 self.myform['baseband'].set_value(r.baseband_freq)
640 self.myform['ddc'].set_value(r.dxc_freq)
642 if (self.use_notches):
643 self.compute_notch_taps(self.notches)
644 if self.dual_mode == False and self.interferometer == False:
645 self.notch_filt.set_taps(self.notch_taps)
647 self.notch_filt1.set_taps(self.notch_taps)
648 self.notch_filt2.set_taps(self.notch_taps)
654 def set_decln(self, dec):
656 self.myform['decln'].set_value(dec) # update displayed value
658 def set_gain(self, gain):
659 self.myform['gain'].set_value(gain) # update displayed value
660 self.subdev[0].set_gain(gain)
661 self.subdev[1].set_gain(gain)
664 def set_averaging(self, avval):
665 self.myform['average'].set_value(avval)
666 self.scope.set_avg_alpha(1.0/(avval))
667 self.scope.set_average(True)
668 self.avg_alpha = avval
670 def set_integration(self, integval):
671 if self.setimode == False:
672 self.integrator.set_taps(1.0/((integval)*(self.bw/2)))
673 self.myform['integration'].set_value(integval)
674 self.integ = integval
678 # Used to update LMST display, as well as current
681 # We also write external data-logging files here
683 def lmst_timeout(self):
684 self.locality.date = ephem.now()
685 if self.setimode == False:
686 x = self.probe.level()
687 sidtime = self.locality.sidereal_time()
689 s = str(ephem.hours(sidtime)) + " " + self.sunstate
690 # Continuum detector value
691 if self.setimode == False:
693 s = s + "\nDet: " + str(sx)
695 sx = "%2d" % self.hitcounter
696 s1 = "%2d" % self.s1hitcounter
697 s2 = "%2d" % self.s2hitcounter
698 sa = "%4.2f" % self.avgdelta
699 sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
700 s = s + "\nHits: " + str(sx) + "\nS1:" + str(s1) + " S2:" + str(s2)
701 s = s + "\nAv D: " + str(sa) + "\nCh lim: " + str(sy)
703 self.myform['lmst_high'].set_value(s)
706 # Write data out to recording files
708 if self.setimode == False:
709 self.write_continuum_data(x,sidtime)
710 self.write_spectral_data(self.fft_outbuf,sidtime)
713 self.seti_analysis(self.fft_outbuf,sidtime)
715 if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
717 self.setifreq_current = self.setifreq_current + self.fft_input_rate
718 if (self.setifreq_current > self.setifreq_upper):
719 self.setifreq_current = self.setifreq_lower
720 self.set_freq(self.setifreq_current)
721 # Make sure we zero-out the hits array when changing
723 self.hits_array[:,:] = 0.0
724 self.hit_intensities[:,:] = 0.0
726 def other_timeout(self):
727 if (self.switch_state == 0):
728 self.switch_state = 1
730 elif (self.switch_state == 1):
731 self.switch_state = 0
733 if (self.switch_state == 0):
735 self.cmute.set_n(int(1.0e9))
737 elif (self.switch_state == 1):
738 self.mute.set_n(int(1.0e9))
741 if (self.ref_fifo != "@@@@"):
742 self.ref_fifo_file.write(str(self.switch_state)+"\n")
743 self.ref_fifo_file.flush()
745 self.avg_reference_value = self.cprobe.level()
748 # Set reference value
750 self.reference_level.set_k(-1.0 * (self.avg_reference_value/self.reference_divisor))
752 def fft_outfunc(self,data,l):
755 def write_continuum_data(self,data,sidtime):
757 # Create localtime structure for producing filename
758 foo = time.localtime()
760 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
761 foo.tm_mon, foo.tm_mday, foo.tm_hour)
763 # Open the data file, appending
764 continuum_file = open (filenamestr+".tpdat","a")
778 # If time to write full header info (saves storage this way)
780 if (now - self.continuum_then > 20):
781 self.sun.compute(self.locality)
783 sunset = self.locality.next_setting(self.sun)
784 sunrise = self.locality.next_rising(self.sun)
787 if ((sunrise < enow) and (enow < sunset)):
790 self.continuum_then = now
792 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
793 continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
794 continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
796 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
798 continuum_file.close()
801 def write_spectral_data(self,data,sidtime):
806 # If time to write out spectral data
807 # We don't write this out every time, in order to
808 # save disk space. Since the spectral data are
809 # typically heavily averaged, writing this data
810 # "once in a while" is OK.
812 if (now - self.spectral_then >= delta):
813 self.spectral_then = now
815 # Get localtime structure to make filename from
816 foo = time.localtime()
819 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
820 foo.tm_mon, foo.tm_mday, foo.tm_hour)
823 spectral_file = open (filenamestr+".sdat","a")
825 # Setup data fields to be written
835 spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
836 spectral_file.write (" [ ")
838 spectral_file.write(" "+str(r))
840 spectral_file.write(" ]\n")
841 spectral_file.close()
846 def seti_analysis(self,fftbuf,sidtime):
851 if self.seticounter < self.setitimer:
852 self.seticounter = self.seticounter + 1
857 # Run through FFT output buffer, computing standard deviation (Sigma)
859 # First compute average
861 avg = avg + fftbuf[i]
865 # Then compute standard deviation (Sigma)
868 sigma = sigma + (d*d)
870 sigma = Numeric.sqrt(sigma/l)
873 # Snarfle through the FFT output buffer again, looking for
874 # outlying data points
876 start_f = self.observing - (self.fft_input_rate/2)
879 f_incr = self.fft_input_rate / l
883 for i in range(l/2,l):
885 # If current FFT buffer has an item that exceeds the specified
888 if ((fftbuf[i] - avg) > (self.setik * sigma)):
889 hits.append(current_f)
890 hit_intensities.append(fftbuf[i])
891 current_f = current_f + f_incr
894 for i in range(0,l/2):
896 # If current FFT buffer has an item that exceeds the specified
899 if ((fftbuf[i] - avg) > (self.setik * sigma)):
900 hits.append(current_f)
901 hit_intensities.append(fftbuf[i])
902 current_f = current_f + f_incr
910 # OK, so we have some hits in the FFT buffer
911 # They'll have a rather substantial gauntlet to run before
912 # being declared a real "hit"
916 self.s1hitcounter = self.s1hitcounter + len(hits)
918 # Weed out buffers with an excessive number of
919 # signals above Sigma
920 if (len(hits) > self.nhits):
924 # Weed out FFT buffers with apparent multiple narrowband signals
925 # separated significantly in frequency. This means that a
926 # single signal spanning multiple bins is OK, but a buffer that
927 # has multiple, apparently-separate, signals isn't OK.
931 for i in range(1,len(hits)):
932 if ((hits[i] - last) > (f_incr*3.0)):
937 self.s2hitcounter = self.s2hitcounter + ns2
940 # Run through all available hit buffers, computing difference between
941 # frequencies found there, if they're all within the chirp limits
945 f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
948 for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
949 f_ds[0] = abs(self.hits_array[i,0] - hits[i])
950 for j in range(1,len(f_ds)):
951 f_ds[j] = abs(self.hits_array[i,j] - self.hits_array[i,0])
952 avg_delta = avg_delta + f_ds[j]
955 if (self.seti_isahit (f_ds)):
957 self.hitcounter = self.hitcounter + 1
960 if (avg_delta/k < (self.seti_fft_bandwidth/2)):
961 self.avgdelta = avg_delta / k
963 # Save 'n shuffle hits
964 # Old hit buffers percolate through the hit buffers
965 # (there are self.nhitlines of these buffers)
966 # and then drop off the end
967 # A consequence is that while the nhitlines buffers are filling,
968 # you can get some absurd values for self.avgdelta, because some
969 # of the buffers are full of zeros
970 for i in range(self.nhitlines,1):
971 self.hits_array[:,i] = self.hits_array[:,i-1]
972 self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
974 for i in range(0,len(hits)):
975 self.hits_array[i,0] = hits[i]
976 self.hit_intensities[i,0] = hit_intensities[i]
978 # Finally, write the hits/intensities buffer
980 self.write_hits(sidtime)
984 def seti_isahit(self,fdiffs):
987 for i in range(0,len(fdiffs)):
988 if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
989 truecount = truecount + 1
991 if truecount == len(fdiffs):
996 def write_hits(self,sidtime):
997 # Create localtime structure for producing filename
998 foo = time.localtime()
1000 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
1001 foo.tm_mon, foo.tm_mday, foo.tm_hour)
1003 # Open the data file, appending
1004 hits_file = open (filenamestr+".seti","a")
1006 # Write sidtime first
1007 hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
1010 # Then write the hits/hit intensities buffers with enough
1011 # "syntax" to allow parsing by external (not yet written!)
1014 for i in range(0,self.nhitlines):
1015 hits_file.write(" ")
1016 for j in range(0,self.nhits):
1017 hits_file.write(str(self.hits_array[j,i])+":")
1018 hits_file.write(str(self.hit_intensities[j,i])+",")
1019 hits_file.write("\n")
1023 def xydfunc(self,func,xyv):
1024 if self.setimode == True:
1026 magn = int(Numeric.log10(self.observing))
1027 if (magn == 6 or magn == 7 or magn == 8):
1029 dfreq = xyv[0] * pow(10.0,magn)
1031 ratio = self.observing / dfreq
1040 s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
1041 s2 = "\n%.3fkm/s" % vs
1042 self.myform['spec_data'].set_value(s+s2)
1044 tmpnotches = Numeric.zeros(self.NOTCH_TAPS,Numeric.Float64)
1046 if self.use_notches == True:
1047 for i in range(0,len(self.notches)):
1048 if self.notches[i] != 0 and abs(self.notches[i] - dfreq) < ((self.bw/self.NOTCH_TAPS)/2.0):
1052 for i in range(0,len(self.notches)):
1054 tmpnotches[j] = self.notches[i]
1057 for i in range(0,len(tmpnotches)):
1058 if (int(tmpnotches[i]) == 0):
1059 tmpnotches[i] = dfreq
1061 self.notches = tmpnotches
1062 self.compute_notch_taps(self.notches)
1063 if self.dual_mode == False and self.interferometer == False:
1064 self.notch_filt.set_taps(self.notch_taps)
1066 self.notch_filt1.set_taps(self.notch_taps)
1067 self.notch_filt2.set_taps(self.notch_taps)
1069 def xydfunc_waterfall(self,pos):
1070 lower = self.observing - (self.seti_fft_bandwidth / 2)
1071 upper = self.observing + (self.seti_fft_bandwidth / 2)
1072 binwidth = self.seti_fft_bandwidth / 1024
1073 s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
1074 self.myform['spec_data'].set_value(s)
1076 def toggle_cal(self):
1077 if (self.calstate == True):
1078 self.calstate = False
1079 self.u.write_io(0,0,(1<<15))
1080 self.calibrator.SetLabel("Calibration Source: Off")
1082 self.calstate = True
1083 self.u.write_io(0,(1<<15),(1<<15))
1084 self.calibrator.SetLabel("Calibration Source: On")
1086 def toggle_annotation(self):
1087 if (self.annotate_state == True):
1088 self.annotate_state = False
1089 self.annotation.SetLabel("Annotation: Off")
1091 self.annotate_state = True
1092 self.annotation.SetLabel("Annotation: On")
1094 # Turn scanning on/off
1095 # Called-back by "Recording" button
1097 def toggle_scanning(self):
1098 # Current scanning? Flip state
1099 if (self.scanning == True):
1100 self.scanning = False
1101 self.scan_control.SetLabel("Scan: Off")
1104 self.scanning = True
1105 self.scan_control.SetLabel("Scan: On ")
1107 def set_pd_offset(self,offs):
1108 self.myform['offset'].set_value(offs)
1109 self.calib_offset=offs
1110 x = self.calib_coeff / 100.0
1111 self.cal_offs.set_k(offs*(x*8000))
1113 def set_pd_gain(self,gain):
1114 self.myform['dcgain'].set_value(gain)
1115 self.cal_mult.set_k(gain*0.01)
1116 self.calib_coeff = gain
1118 self.cal_offs.set_k(self.calib_offset*(x*8000))
1120 def compute_notch_taps(self,notchlist):
1121 tmptaps = Numeric.zeros(self.NOTCH_TAPS,Numeric.Complex64)
1122 binwidth = self.bw / self.NOTCH_TAPS
1124 for i in range(0,self.NOTCH_TAPS):
1125 tmptaps[i] = complex(1.0,0.0)
1128 diff = i - self.observing
1131 if ((i < (self.observing - self.bw/2)) or (i > (self.observing + self.bw/2))):
1134 idx = diff / binwidth
1137 if (idx < 0 or idx > (self.NOTCH_TAPS/2)):
1139 tmptaps[idx] = complex(0.0, 0.0)
1142 idx = -diff / binwidth
1144 idx = (self.NOTCH_TAPS/2) - idx
1145 idx = int(idx+(self.NOTCH_TAPS/2))
1146 if (idx < 0 or idx >= (self.NOTCH_TAPS)):
1148 tmptaps[idx] = complex(0.0, 0.0)
1150 self.notch_taps = numpy.fft.ifft(tmptaps)
1153 # Setup common pieces of radiometer mode
1155 def setup_radiometer_common(self,n):
1156 # The IIR integration filter for post-detection
1157 self.integrator = gr.single_pole_iir_filter_ff(1.0)
1158 self.integrator.set_taps (1.0/self.bw)
1160 if (self.use_notches == True):
1161 self.compute_notch_taps(self.notches)
1163 self.notch_filt1 = gr.fft_filter_ccc(1, self.notch_taps)
1164 self.notch_filt2 = gr.fft_filter_ccc(1, self.notch_taps)
1166 self.notch_filt = gr.fft_filter_ccc(1, self.notch_taps)
1170 self.probe = gr.probe_signal_f()
1173 # Continuum calibration stuff
1175 x = self.calib_coeff/100.0
1176 self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0)
1177 self.cal_offs = gr.add_const_ff(self.calib_offset*(x*8000))
1180 # Mega decimator after IIR filter
1182 if (self.switch_mode == False):
1183 self.keepn = gr.keep_one_in_n(gr.sizeof_float, self.bw)
1185 self.keepn = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/2))
1188 # For the Dicke-switching scheme
1190 #self.switch = gr.multiply_const_ff(1.0)
1193 if (self.switch_mode == True):
1194 self.vector = gr.vector_sink_f()
1195 self.swkeep = gr.keep_one_in_n(gr.sizeof_float, int(self.bw/3))
1196 self.mute = gr.keep_one_in_n(gr.sizeof_float, 1)
1197 self.cmute = gr.keep_one_in_n(gr.sizeof_float, int(1.0e9))
1198 self.cintegrator = gr.single_pole_iir_filter_ff(1.0/(self.bw/2))
1199 self.cprobe = gr.probe_signal_f()
1201 self.mute = gr.multiply_const_ff(1.0)
1204 self.avg_reference_value = 0.0
1205 self.reference_level = gr.add_const_ff(0.0)
1208 # Setup ordinary single-channel radiometer mode
1210 def setup_normal(self, setimode):
1212 self.setup_radiometer_common(1)
1215 if (self.use_notches == True):
1216 self.shead = self.notch_filt
1220 if setimode == False:
1222 self.detector = gr.complex_to_mag_squared()
1223 self.connect(self.shead, self.scope)
1225 if (self.use_notches == False):
1226 self.connect(self.head, self.detector, self.mute, self.reference_level,
1227 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1229 self.connect(self.head, self.notch_filt, self.detector, self.mute, self.reference_level,
1230 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1232 self.connect(self.cal_offs, self.probe)
1235 # Add a side-chain detector chain, with a different integrator, for sampling
1236 # The reference channel data
1237 # This is used to derive the offset value for self.reference_level, used above
1239 if (self.switch_mode == True):
1240 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)
1245 # Setup dual-channel (two antenna, usual orthogonal polarity probes in the same waveguide)
1247 def setup_dual(self, setimode):
1249 self.setup_radiometer_common(2)
1251 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1252 self.addchans = gr.add_cc ()
1253 self.detector = gr.add_ff ()
1254 self.h_power = gr.complex_to_mag_squared()
1255 self.v_power = gr.complex_to_mag_squared()
1256 self.connect (self.u, self.di)
1258 if (self.use_notches == True):
1259 self.connect((self.di, 0), self.notch_filt1, (self.addchans, 0))
1260 self.connect((self.di, 1), self.notch_filt2, (self.addchans, 1))
1263 # For spectral, adding the two channels works, assuming no gross
1264 # phase or amplitude error
1265 self.connect ((self.di, 0), (self.addchans, 0))
1266 self.connect ((self.di, 1), (self.addchans, 1))
1269 # Connect heads of spectral and total-power chains
1271 if (self.use_notches == False):
1274 self.head = (self.notch_filt1, self.notch_filt2)
1276 self.shead = self.addchans
1278 if (setimode == False):
1280 # For dual-polarization mode, we compute the sum of the
1281 # powers on each channel, after they've been detected
1283 self.detector = gr.add_ff()
1286 # In dual-polarization mode, we compute things a little differently
1287 # In effect, we have two radiometer chains, terminating in an adder
1289 if self.use_notches == True:
1290 self.connect(self.notch_filt1, self.h_power)
1291 self.connect(self.notch_filt2, self.v_power)
1293 self.connect((self.head, 0), self.h_power)
1294 self.connect((self.head, 1), self.v_power)
1295 self.connect(self.h_power, (self.detector, 0))
1296 self.connect(self.v_power, (self.detector, 1))
1297 self.connect(self.detector, self.mute, self.reference_level,
1298 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1299 self.connect(self.cal_offs, self.probe)
1300 self.connect(self.shead, self.scope)
1303 # Add a side-chain detector chain, with a different integrator, for sampling
1304 # The reference channel data
1305 # This is used to derive the offset value for self.reference_level, used above
1307 if (self.switch_mode == True):
1308 self.connect(self.detector, self.cmute, self.cintegrator, self.swkeep, self.cprobe)
1312 # Setup correlating interferometer mode
1314 def setup_interferometer(self, setimode):
1315 self.setup_radiometer_common(2)
1317 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1318 self.connect (self.u, self.di)
1319 self.corr = gr.multiply_cc()
1320 self.c2f = gr.complex_to_float()
1322 self.shead = (self.di, 0)
1324 # Channel 0 to multiply port 0
1325 # Channel 1 to multiply port 1
1326 if (self.use_notches == False):
1327 self.connect((self.di, 0), (self.corr, 0))
1328 self.connect((self.di, 1), (self.corr, 1))
1330 self.connect((self.di, 0), self.notch_filt1, (self.corr, 0))
1331 self.connect((self.di, 1), self.notch_filt2, (self.corr, 0))
1334 # Multiplier (correlator) to complex-to-float, followed by integrator, etc
1336 self.connect(self.corr, self.c2f, self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1339 # FFT scope gets only 1 channel
1340 # FIX THIS, by cross-correlating the *outputs* of two different FFTs, then display
1343 self.connect(self.shead, self.scope)
1346 # Output of correlator/integrator chain to probe
1348 self.connect(self.cal_offs, self.probe)
1355 def setup_seti(self):
1356 self.connect (self.shead, self.fft_bandpass, self.scope)
1362 app = stdgui2.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1365 if __name__ == '__main__':