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 (options, args) = parser.parse_args()
84 self.setimode = options.setimode
85 self.dual_mode = options.dual_mode
86 self.interferometer = options.interferometer
87 self.normal_mode = False
89 for modes in (self.dual_mode, self.interferometer):
91 modecount = modecount + 1
94 print "must select only 1 of --dual_mode, or --interferometer"
97 self.chartneeded = True
99 if (self.setimode == True):
100 self.chartneeded = False
102 if (self.setimode == True and self.interferometer == True):
103 print "can't pick both --setimode and --interferometer"
107 self.normal_mode = True
109 self.show_debug_info = True
111 # Pick up waterfall option
112 self.waterfall = options.waterfall
115 self.setimode = options.setimode
117 self.setik = options.setik
118 self.seti_fft_bandwidth = int(options.setibandwidth)
121 binwidth = self.seti_fft_bandwidth / options.fft_size
123 # Use binwidth, and knowledge of likely chirp rates to set reasonable
124 # values for SETI analysis code. We assume that SETI signals will
125 # chirp at somewhere between 0.10Hz/sec and 0.25Hz/sec.
127 # upper_limit is the "worst case"--that is, the case for which we have
128 # to wait the longest to actually see any drift, due to the quantizing
130 upper_limit = binwidth / 0.10
131 self.setitimer = int(upper_limit * 2.00)
134 # Calculate the CHIRP values based on Hz/sec
135 self.CHIRP_LOWER = 0.10 * self.setitimer
136 self.CHIRP_UPPER = 0.25 * self.setitimer
138 # Reset hit counters to 0
140 self.s1hitcounter = 0
141 self.s2hitcounter = 0
143 # We scan through 2Mhz of bandwidth around the chosen center freq
144 self.seti_freq_range = options.seti_range
145 # Calculate lower edge
146 self.setifreq_lower = options.freq - (self.seti_freq_range/2)
147 self.setifreq_current = options.freq
148 # Calculate upper edge
149 self.setifreq_upper = options.freq + (self.seti_freq_range/2)
151 # Maximum "hits" in a line
154 # Number of lines for analysis
157 # We change center frequencies based on nhitlines and setitimer
158 self.setifreq_timer = self.setitimer * (self.nhitlines * 5)
160 # Create actual timer
161 self.seti_then = time.time()
163 # The hits recording array
164 self.hits_array = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
165 self.hit_intensities = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
166 # Calibration coefficient and offset
167 self.calib_coeff = options.calib_coeff
168 self.calib_offset = options.calib_offset
169 if self.calib_offset < -750:
170 self.calib_offset = -750
171 if self.calib_offset > 750:
172 self.calib_offset = 750
174 if self.calib_coeff < 1:
176 if self.calib_coeff > 100:
177 self.calib_coeff = 100
179 self.integ = options.integ
180 self.avg_alpha = options.avg
181 self.gain = options.gain
182 self.decln = options.decln
184 # Set initial values for datalogging timed-output
185 self.continuum_then = time.time()
186 self.spectral_then = time.time()
191 self.subdev = [(0, 0), (0,0)]
194 # If SETI mode, we always run at maximum USRP decimation
199 if (self.dual_mode == False and self.interferometer == False):
200 self.u = usrp.source_c(decim_rate=options.decim)
201 self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
202 # determine the daughterboard subdevice we're using
203 self.subdev[0] = usrp.selected_subdev(self.u, options.rx_subdev_spec)
204 self.subdev[1] = self.subdev[0]
205 self.cardtype = self.subdev[0].dbid()
207 self.u=usrp.source_c(decim_rate=options.decim, nchan=2)
208 self.subdev[0] = usrp.selected_subdev(self.u, (0, 0))
209 self.subdev[1] = usrp.selected_subdev(self.u, (1, 0))
210 self.cardtype = self.subdev[0].dbid()
211 self.u.set_mux(0x32103210)
212 c1 = self.subdev[0].name()
213 c2 = self.subdev[1].name()
215 print "Must have identical cardtypes for --dual_mode or --interferometer"
222 format = self.u.make_format(width, shift)
223 r = self.u.set_format(format)
225 # Set initial declination
226 self.decln = options.decln
228 input_rate = self.u.adc_freq() / self.u.decim_rate()
231 # Set prefix for data files
233 self.prefix = options.prefix
236 # The lower this number, the fewer sample frames are dropped
237 # in computing the FFT. A sampled approach is taken to
238 # computing the FFT of the incoming data, which reduces
239 # sensitivity. Increasing sensitivity inreases CPU loading.
241 self.fft_rate = options.fft_rate
243 self.fft_size = int(options.fft_size)
245 # This buffer is used to remember the most-recent FFT display
246 # values. Used later by self.write_spectral_data() to write
247 # spectral data to datalogging files, and by the SETI analysis
250 self.fft_outbuf = Numeric.zeros(self.fft_size, Numeric.Float64)
253 # If SETI mode, only look at seti_fft_bandwidth
257 self.fft_input_rate = self.seti_fft_bandwidth
260 # Build a decimating bandpass filter
262 self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
264 -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
265 gr.firdes.WIN_HAMMING, 0)
268 # Compute required decimation factor
270 decimation = int(input_rate/self.fft_input_rate)
271 self.fft_bandpass = gr.fir_filter_ccc (decimation,
274 self.fft_input_rate = input_rate
277 if self.waterfall == False:
278 self.scope = ra_fftsink.ra_fft_sink_c (panel,
279 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
280 fft_rate=int(self.fft_rate), title="Spectral",
281 ofunc=self.fft_outfunc, xydfunc=self.xydfunc)
283 self.scope = ra_waterfallsink.waterfall_sink_c (panel,
284 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
285 fft_rate=int(self.fft_rate), title="Spectral", ofunc=self.fft_outfunc, size=(1100, 600), xydfunc=self.xydfunc, ref_level=0, span=10)
287 # Set up ephemeris data
288 self.locality = ephem.Observer()
289 self.locality.long = str(options.longitude)
290 self.locality.lat = str(options.latitude)
292 # We make notes about Sunset/Sunrise in Continuum log files
293 self.sun = ephem.Sun()
296 # Set up stripchart display
298 if (self.dual_mode != False):
299 tit = "H+V Continuum"
300 if (self.interferometer != False):
301 tit = "East x West Correlation"
302 self.stripsize = int(options.stripsize)
303 if self.chartneeded == True:
304 self.chart = ra_stripchartsink.stripchart_sink_f (panel,
305 stripsize=self.stripsize,
307 xlabel="LMST Offset (Seconds)",
308 scaling=1.0, ylabel=options.ylabel,
309 divbase=options.divbase)
311 # Set center frequency
312 self.centerfreq = options.freq
314 # Set observing frequency (might be different from actual programmed
316 if options.observing == 0.0:
317 self.observing = options.freq
319 self.observing = options.observing
321 # Remember our input bandwidth
326 # The strip chart is fed at a constant 1Hz rate
330 # Call constructors for receive chains
333 if (self.dual_mode == True):
334 self.setup_dual (self.setimode)
336 if (self.interferometer == True):
337 self.setup_interferometer(self.setimode)
339 if (self.normal_mode == True):
340 self.setup_normal(self.setimode)
342 if (self.setimode == True):
345 self._build_gui(vbox)
347 # Make GUI agree with command-line
348 self.integ = options.integ
349 if self.setimode == False:
350 self.myform['integration'].set_value(int(options.integ))
351 self.myform['offset'].set_value(self.calib_offset)
352 self.myform['dcgain'].set_value(self.calib_coeff)
353 self.myform['average'].set_value(int(options.avg))
356 if self.setimode == False:
357 # Make integrator agree with command line
358 self.set_integration(int(options.integ))
360 self.avg_alpha = options.avg
362 # Make spectral averager agree with command line
363 if options.avg != 1.0:
364 self.scope.set_avg_alpha(float(1.0/options.avg))
365 self.scope.set_average(True)
367 if self.setimode == False:
369 self.chart.set_y_per_div(options.division)
370 # Set reference(MAX) level
371 self.chart.set_ref_level(options.reflevel)
375 if options.gain is None:
376 # if no gain was specified, use the mid-point in dB
377 g = self.subdev[0].gain_range()
378 options.gain = float(g[0]+g[1])/2
380 if options.freq is None:
381 # if no freq was specified, use the mid-point
382 r = self.subdev[0].freq_range()
383 options.freq = float(r[0]+r[1])/2
385 # Set the initial gain control
386 self.set_gain(options.gain)
388 if not(self.set_freq(options.freq)):
389 self._set_status_msg("Failed to set initial frequency")
392 self.set_decln (self.decln)
395 # RF hardware information
396 self.myform['decim'].set_value(self.u.decim_rate())
397 self.myform['USB BW'].set_value(self.u.adc_freq() / self.u.decim_rate())
398 if (self.dual_mode == True):
399 self.myform['dbname'].set_value(self.subdev[0].name()+'/'+self.subdev[1].name())
401 self.myform['dbname'].set_value(self.subdev[0].name())
403 # Set analog baseband filtering, if DBS_RX
404 if self.cardtype in (usrp_dbid.DBS_RX, usrp_dbid.DBS_RX_REV_2_1):
405 lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
408 self.subdev[0].set_bw(lbw)
409 self.subdev[1].set_bw(lbw)
411 # Start the timer for the LMST display and datalogging
412 self.lmst_timer.Start(1000)
415 def _set_status_msg(self, msg):
416 self.frame.GetStatusBar().SetStatusText(msg, 0)
418 def _build_gui(self, vbox):
420 def _form_set_freq(kv):
421 # Adjust current SETI frequency, and limits
422 self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
423 self.setifreq_current = kv['freq']
424 self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)
426 # Reset SETI analysis timer
427 self.seti_then = time.time()
428 # Zero-out hits array when changing frequency
429 self.hits_array[:,:] = 0.0
430 self.hit_intensities[:,:] = -60.0
432 return self.set_freq(kv['freq'])
434 def _form_set_decln(kv):
435 return self.set_decln(kv['decln'])
437 # Position the FFT display
438 vbox.Add(self.scope.win, 15, wx.EXPAND)
440 if self.setimode == False:
441 # Position the Total-power stripchart
442 vbox.Add(self.chart.win, 15, wx.EXPAND)
444 # add control area at the bottom
445 self.myform = myform = form.form()
446 hbox = wx.BoxSizer(wx.HORIZONTAL)
447 hbox.Add((7,0), 0, wx.EXPAND)
448 vbox1 = wx.BoxSizer(wx.VERTICAL)
449 myform['freq'] = form.float_field(
450 parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
451 callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
453 vbox1.Add((4,0), 0, 0)
455 myform['lmst_high'] = form.static_text_field(
456 parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
457 vbox1.Add((4,0), 0, 0)
459 if self.setimode == False:
460 myform['spec_data'] = form.static_text_field(
461 parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
462 vbox1.Add((4,0), 0, 0)
464 vbox2 = wx.BoxSizer(wx.VERTICAL)
465 if self.setimode == False:
466 vbox3 = wx.BoxSizer(wx.VERTICAL)
467 g = self.subdev[0].gain_range()
468 myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
470 min=int(g[0]), max=int(g[1]),
471 callback=self.set_gain)
473 vbox2.Add((4,0), 0, 0)
474 if self.setimode == True:
478 myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2,
479 label="Spectral Averaging (FFT frames)", weight=1, min=1, max=max_savg, callback=self.set_averaging)
481 # Set up scan control button when in SETI mode
482 if (self.setimode == True):
483 # SETI scanning control
484 buttonbox = wx.BoxSizer(wx.HORIZONTAL)
485 self.scan_control = form.button_with_callback(self.panel,
487 callback=self.toggle_scanning)
489 buttonbox.Add(self.scan_control, 0, wx.CENTER)
490 vbox2.Add(buttonbox, 0, wx.CENTER)
492 vbox2.Add((4,0), 0, 0)
494 if self.setimode == False:
495 myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
496 label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)
498 vbox2.Add((4,0), 0, 0)
500 myform['decln'] = form.float_field(
501 parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
502 callback=myform.check_input_and_call(_form_set_decln))
503 vbox2.Add((4,0), 0, 0)
505 if self.setimode == False:
506 myform['offset'] = form.slider_field(parent=self.panel, sizer=vbox3,
507 label="Post-Detector Offset", weight=1, min=-750, max=750,
508 callback=self.set_pd_offset)
509 vbox3.Add((2,0), 0, 0)
510 myform['dcgain'] = form.slider_field(parent=self.panel, sizer=vbox3,
511 label="Post-Detector Gain", weight=1, min=1, max=100,
512 callback=self.set_pd_gain)
513 vbox3.Add((2,0), 0, 0)
514 hbox.Add(vbox1, 0, 0)
515 hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
517 if self.setimode == False:
518 hbox.Add(vbox3, wx.ALIGN_RIGHT, 0)
520 vbox.Add(hbox, 0, wx.EXPAND)
522 self._build_subpanel(vbox)
524 self.lmst_timer = wx.PyTimer(self.lmst_timeout)
528 def _build_subpanel(self, vbox_arg):
529 # build a secondary information panel (sometimes hidden)
531 # FIXME figure out how to have this be a subpanel that is always
532 # created, but has its visibility controlled by foo.Show(True/False)
534 if not(self.show_debug_info):
541 #panel = wx.Panel(self.panel, -1)
542 #vbox = wx.BoxSizer(wx.VERTICAL)
544 hbox = wx.BoxSizer(wx.HORIZONTAL)
546 myform['decim'] = form.static_float_field(
547 parent=panel, sizer=hbox, label="Decim")
550 myform['USB BW'] = form.static_float_field(
551 parent=panel, sizer=hbox, label="USB BW")
554 myform['dbname'] = form.static_text_field(
555 parent=panel, sizer=hbox)
558 myform['baseband'] = form.static_float_field(
559 parent=panel, sizer=hbox, label="Analog BB")
562 myform['ddc'] = form.static_float_field(
563 parent=panel, sizer=hbox, label="DDC")
566 vbox.Add(hbox, 0, wx.EXPAND)
570 def set_freq(self, target_freq):
572 Set the center frequency we're interested in.
574 @param target_freq: frequency in Hz
577 Tuning is a two step process. First we ask the front-end to
578 tune as close to the desired frequency as it can. Then we use
579 the result of that operation and our target_frequency to
580 determine the value for the digital down converter.
583 # Everything except BASIC_RX should support usrp.tune()
585 if not (self.cardtype == usrp_dbid.BASIC_RX):
586 r = usrp.tune(self.u, self.subdev[0]._which, self.subdev[0], target_freq)
587 r = usrp.tune(self.u, self.subdev[1]._which, self.subdev[1], target_freq)
589 r = self.u.set_rx_freq(0, target_freq)
590 f = self.u.rx_freq(0)
591 if abs(f-target_freq) > 2.0e3:
594 self.myform['freq'].set_value(target_freq) # update displayed value
596 # Make sure calibrator knows our target freq
599 # Remember centerfreq---used for doppler calcs
600 delta = self.centerfreq - target_freq
601 self.centerfreq = target_freq
602 self.observing -= delta
603 self.scope.set_baseband_freq (self.observing)
605 self.myform['baseband'].set_value(r.baseband_freq)
606 self.myform['ddc'].set_value(r.dxc_freq)
612 def set_decln(self, dec):
614 self.myform['decln'].set_value(dec) # update displayed value
616 def set_gain(self, gain):
617 self.myform['gain'].set_value(gain) # update displayed value
618 self.subdev[0].set_gain(gain)
619 self.subdev[1].set_gain(gain)
622 def set_averaging(self, avval):
623 self.myform['average'].set_value(avval)
624 self.scope.set_avg_alpha(1.0/(avval))
625 self.scope.set_average(True)
626 self.avg_alpha = avval
628 def set_integration(self, integval):
629 if self.setimode == False:
630 self.integrator.set_taps(1.0/((integval)*(self.bw/2)))
631 self.myform['integration'].set_value(integval)
632 self.integ = integval
636 # Used to update LMST display, as well as current
639 # We also write external data-logging files here
641 def lmst_timeout(self):
642 self.locality.date = ephem.now()
643 if self.setimode == False:
644 x = self.probe.level()
645 sidtime = self.locality.sidereal_time()
647 s = str(ephem.hours(sidtime)) + " " + self.sunstate
648 # Continuum detector value
649 if self.setimode == False:
651 s = s + "\nDet: " + str(sx)
653 sx = "%2d" % self.hitcounter
654 s1 = "%2d" % self.s1hitcounter
655 s2 = "%2d" % self.s2hitcounter
656 sa = "%4.2f" % self.avgdelta
657 sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
658 s = s + "\nHits: " + str(sx) + "\nS1:" + str(s1) + " S2:" + str(s2)
659 s = s + "\nAv D: " + str(sa) + "\nCh lim: " + str(sy)
661 self.myform['lmst_high'].set_value(s)
664 # Write data out to recording files
666 if self.setimode == False:
667 self.write_continuum_data(x,sidtime)
668 self.write_spectral_data(self.fft_outbuf,sidtime)
671 self.seti_analysis(self.fft_outbuf,sidtime)
673 if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
675 self.setifreq_current = self.setifreq_current + self.fft_input_rate
676 if (self.setifreq_current > self.setifreq_upper):
677 self.setifreq_current = self.setifreq_lower
678 self.set_freq(self.setifreq_current)
679 # Make sure we zero-out the hits array when changing
681 self.hits_array[:,:] = 0.0
682 self.hit_intensities[:,:] = 0.0
684 def fft_outfunc(self,data,l):
687 def write_continuum_data(self,data,sidtime):
689 # Create localtime structure for producing filename
690 foo = time.localtime()
692 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
693 foo.tm_mon, foo.tm_mday, foo.tm_hour)
695 # Open the data file, appending
696 continuum_file = open (filenamestr+".tpdat","a")
710 # If time to write full header info (saves storage this way)
712 if (now - self.continuum_then > 20):
713 self.sun.compute(self.locality)
717 if ((self.sun.rise_time < enow) and (enow < self.sun.set_time)):
720 self.continuum_then = now
722 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
723 continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
724 continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
726 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
728 continuum_file.close()
731 def write_spectral_data(self,data,sidtime):
736 # If time to write out spectral data
737 # We don't write this out every time, in order to
738 # save disk space. Since the spectral data are
739 # typically heavily averaged, writing this data
740 # "once in a while" is OK.
742 if (now - self.spectral_then >= delta):
743 self.spectral_then = now
745 # Get localtime structure to make filename from
746 foo = time.localtime()
749 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
750 foo.tm_mon, foo.tm_mday, foo.tm_hour)
753 spectral_file = open (filenamestr+".sdat","a")
755 # Setup data fields to be written
765 spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
766 spectral_file.write (" [ ")
768 spectral_file.write(" "+str(r))
770 spectral_file.write(" ]\n")
771 spectral_file.close()
776 def seti_analysis(self,fftbuf,sidtime):
781 if self.seticounter < self.setitimer:
782 self.seticounter = self.seticounter + 1
787 # Run through FFT output buffer, computing standard deviation (Sigma)
789 # First compute average
791 avg = avg + fftbuf[i]
795 # Then compute standard deviation (Sigma)
798 sigma = sigma + (d*d)
800 sigma = Numeric.sqrt(sigma/l)
803 # Snarfle through the FFT output buffer again, looking for
804 # outlying data points
806 start_f = self.observing - (self.fft_input_rate/2)
809 f_incr = self.fft_input_rate / l
813 for i in range(l/2,l):
815 # If current FFT buffer has an item that exceeds the specified
818 if ((fftbuf[i] - avg) > (self.setik * sigma)):
819 hits.append(current_f)
820 hit_intensities.append(fftbuf[i])
821 current_f = current_f + f_incr
824 for i in range(0,l/2):
826 # If current FFT buffer has an item that exceeds the specified
829 if ((fftbuf[i] - avg) > (self.setik * sigma)):
830 hits.append(current_f)
831 hit_intensities.append(fftbuf[i])
832 current_f = current_f + f_incr
840 # OK, so we have some hits in the FFT buffer
841 # They'll have a rather substantial gauntlet to run before
842 # being declared a real "hit"
846 self.s1hitcounter = self.s1hitcounter + len(hits)
848 # Weed out buffers with an excessive number of
849 # signals above Sigma
850 if (len(hits) > self.nhits):
854 # Weed out FFT buffers with apparent multiple narrowband signals
855 # separated significantly in frequency. This means that a
856 # single signal spanning multiple bins is OK, but a buffer that
857 # has multiple, apparently-separate, signals isn't OK.
861 for i in range(1,len(hits)):
862 if ((hits[i] - last) > (f_incr*3.0)):
867 self.s2hitcounter = self.s2hitcounter + ns2
870 # Run through all available hit buffers, computing difference between
871 # frequencies found there, if they're all within the chirp limits
875 f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
878 for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
879 f_ds[0] = abs(self.hits_array[i,0] - hits[i])
880 for j in range(1,len(f_ds)):
881 f_ds[j] = abs(self.hits_array[i,j] - self.hits_array[i,0])
882 avg_delta = avg_delta + f_ds[j]
885 if (self.seti_isahit (f_ds)):
887 self.hitcounter = self.hitcounter + 1
890 if (avg_delta/k < (self.seti_fft_bandwidth/2)):
891 self.avgdelta = avg_delta / k
893 # Save 'n shuffle hits
894 # Old hit buffers percolate through the hit buffers
895 # (there are self.nhitlines of these buffers)
896 # and then drop off the end
897 # A consequence is that while the nhitlines buffers are filling,
898 # you can get some absurd values for self.avgdelta, because some
899 # of the buffers are full of zeros
900 for i in range(self.nhitlines,1):
901 self.hits_array[:,i] = self.hits_array[:,i-1]
902 self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
904 for i in range(0,len(hits)):
905 self.hits_array[i,0] = hits[i]
906 self.hit_intensities[i,0] = hit_intensities[i]
908 # Finally, write the hits/intensities buffer
910 self.write_hits(sidtime)
914 def seti_isahit(self,fdiffs):
917 for i in range(0,len(fdiffs)):
918 if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
919 truecount = truecount + 1
921 if truecount == len(fdiffs):
926 def write_hits(self,sidtime):
927 # Create localtime structure for producing filename
928 foo = time.localtime()
930 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
931 foo.tm_mon, foo.tm_mday, foo.tm_hour)
933 # Open the data file, appending
934 hits_file = open (filenamestr+".seti","a")
936 # Write sidtime first
937 hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
940 # Then write the hits/hit intensities buffers with enough
941 # "syntax" to allow parsing by external (not yet written!)
944 for i in range(0,self.nhitlines):
946 for j in range(0,self.nhits):
947 hits_file.write(str(self.hits_array[j,i])+":")
948 hits_file.write(str(self.hit_intensities[j,i])+",")
949 hits_file.write("\n")
953 def xydfunc(self,xyv):
954 if self.setimode == True:
956 magn = int(Numeric.log10(self.observing))
957 if (magn == 6 or magn == 7 or magn == 8):
959 dfreq = xyv[0] * pow(10.0,magn)
960 ratio = self.observing / dfreq
969 s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
970 s2 = "\n%.3fkm/s" % vs
971 self.myform['spec_data'].set_value(s+s2)
973 def xydfunc_waterfall(self,pos):
974 lower = self.observing - (self.seti_fft_bandwidth / 2)
975 upper = self.observing + (self.seti_fft_bandwidth / 2)
976 binwidth = self.seti_fft_bandwidth / 1024
977 s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
978 self.myform['spec_data'].set_value(s)
980 def toggle_cal(self):
981 if (self.calstate == True):
982 self.calstate = False
983 self.u.write_io(0,0,(1<<15))
984 self.calibrator.SetLabel("Calibration Source: Off")
987 self.u.write_io(0,(1<<15),(1<<15))
988 self.calibrator.SetLabel("Calibration Source: On")
990 def toggle_annotation(self):
991 if (self.annotate_state == True):
992 self.annotate_state = False
993 self.annotation.SetLabel("Annotation: Off")
995 self.annotate_state = True
996 self.annotation.SetLabel("Annotation: On")
998 # Turn scanning on/off
999 # Called-back by "Recording" button
1001 def toggle_scanning(self):
1002 # Current scanning? Flip state
1003 if (self.scanning == True):
1004 self.scanning = False
1005 self.scan_control.SetLabel("Scan: Off")
1008 self.scanning = True
1009 self.scan_control.SetLabel("Scan: On ")
1011 def set_pd_offset(self,offs):
1012 self.myform['offset'].set_value(offs)
1013 self.calib_offset=offs
1014 x = self.calib_coeff / 100.0
1015 self.cal_offs.set_k(offs*(x*8000))
1017 def set_pd_gain(self,gain):
1018 self.myform['dcgain'].set_value(gain)
1019 self.cal_mult.set_k(gain*0.01)
1020 self.calib_coeff = gain
1022 self.cal_offs.set_k(self.calib_offset*(x*8000))
1024 def compute_notch_taps(self,notchlist):
1026 tmptaps = Numeric.zeros(NOTCH_TAPS,Numeric.Complex64)
1027 binwidth = self.bw / NOTCH_TAPS
1029 for i in range(0,NOTCH_TAPS):
1030 tmptaps[i] = complex(1.0,0.0)
1033 diff = i - self.observing
1037 idx = diff / binwidth
1039 if (idx < 0 or idx > (NOTCH_TAPS/2)):
1041 tmptaps[idx] = complex(0.0, 0.0)
1044 idx = -diff / binwidth
1045 idx = (NOTCH_TAPS/2) - idx
1046 idx = int(idx+(NOTCH_TAPS/2))
1047 if (idx < 0 or idx > (NOTCH_TAPS)):
1049 tmptaps[idx] = complex(0.0, 0.0)
1051 self.notch_taps = numpy.fft.ifft(tmptaps)
1054 # Setup common pieces of radiometer mode
1056 def setup_radiometer_common(self):
1057 # The IIR integration filter for post-detection
1058 self.integrator = gr.single_pole_iir_filter_ff(1.0)
1059 self.integrator.set_taps (1.0/self.bw)
1062 self.probe = gr.probe_signal_f()
1065 # Continuum calibration stuff
1067 x = self.calib_coeff/100.0
1068 self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0)
1069 self.cal_offs = gr.add_const_ff(self.calib_offset*(x*8000))
1072 # Mega decimator after IIR filter
1074 self.keepn = gr.keep_one_in_n(gr.sizeof_float, self.bw)
1078 # Setup ordinary single-channel radiometer mode
1080 def setup_normal(self, setimode):
1085 if setimode == False:
1086 self.detector = gr.complex_to_mag_squared()
1087 self.setup_radiometer_common()
1089 self.connect(self.shead, self.scope)
1091 self.connect(self.head, self.detector,
1092 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1094 self.connect(self.cal_offs, self.probe)
1099 # Setup dual-channel (two antenna, usual orthogonal polarity probes in the same waveguide)
1101 def setup_dual(self, setimode):
1103 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1104 self.addchans = gr.add_cc ()
1105 self.detector = gr.add_ff ()
1106 self.h_power = gr.complex_to_mag_squared()
1107 self.v_power = gr.complex_to_mag_squared()
1108 self.connect (self.u, self.di)
1111 # For spectral, adding the two channels works, assuming no gross
1112 # phase or amplitude error
1113 self.connect ((self.di, 0), (self.addchans, 0))
1114 self.connect ((self.di, 1), (self.addchans, 1))
1117 # Connect heads of spectral and total-power chains
1120 self.shead = self.addchans
1122 if (setimode == False):
1124 self.setup_radiometer_common()
1127 # For dual-polarization mode, we compute the sum of the
1128 # powers on each channel, after they've been detected
1130 self.detector = gr.add_ff()
1132 # In dual-polarization mode, we compute things a little differently
1133 # In effect, we have two radiometer chains, terminating in an adder
1135 self.connect((self.di, 0), self.h_power)
1136 self.connect((self.di, 1), self.v_power)
1137 self.connect(self.h_power, (self.detector, 0))
1138 self.connect(self.v_power, (self.detector, 1))
1139 self.connect(self.detector,
1140 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1141 self.connect(self.cal_offs, self.probe)
1142 self.connect(self.shead, self.scope)
1146 # Setup correlating interferometer mode
1148 def setup_interferometer(self, setimode):
1149 self.setup_radiometer_common()
1151 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1152 self.connect (self.u, self.di)
1153 self.corr = gr.multiply_cc()
1154 self.c2f = gr.complex_to_float()
1156 self.shead = (self.di, 0)
1158 # Channel 0 to multiply port 0
1159 # Channel 1 to multiply port 1
1160 self.connect((self.di, 0), (self.corr, 0))
1161 self.connect((self.di, 1), (self.corr, 1))
1164 # Multiplier (correlator) to complex-to-float, followed by integrator, etc
1166 self.connect(self.corr, self.c2f, self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1169 # FFT scope gets only 1 channel
1170 # FIX THIS, by cross-correlating the *outputs* of two different FFTs, then display
1173 self.connect(self.shead, self.scope)
1176 # Output of correlator/integrator chain to probe
1178 self.connect(self.cal_offs, self.probe)
1185 def setup_seti(self):
1186 self.connect (self.shead, self.fft_bandpass, self.scope)
1192 app = stdgui2.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1195 if __name__ == '__main__':