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, waterfallsink
29 from optparse import OptionParser
37 class continuum_calibration(gr.feval_dd):
39 str = globals()["calibration_codelet"]
43 class app_flow_graph(stdgui2.std_top_block):
44 def __init__(self, frame, panel, vbox, argv):
45 stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)
50 parser = OptionParser(option_class=eng_option)
51 parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0, 0),
52 help="select USRP Rx side A or B (default=A)")
53 parser.add_option("-d", "--decim", type="int", default=16,
54 help="set fgpa decimation rate to DECIM [default=%default]")
55 parser.add_option("-f", "--freq", type="eng_float", default=None,
56 help="set frequency to FREQ", metavar="FREQ")
57 parser.add_option("-a", "--avg", type="eng_float", default=1.0,
58 help="set spectral averaging alpha")
59 parser.add_option("-i", "--integ", type="eng_float", default=1.0,
60 help="set integration time")
61 parser.add_option("-g", "--gain", type="eng_float", default=None,
62 help="set gain in dB (default is midpoint)")
63 parser.add_option("-l", "--reflevel", type="eng_float", default=30.0,
64 help="Set Total power reference level")
65 parser.add_option("-y", "--division", type="eng_float", default=0.5,
66 help="Set Total power Y division size")
67 parser.add_option("-e", "--longitude", type="eng_float", default=-76.02, help="Set Observer Longitude")
68 parser.add_option("-c", "--latitude", type="eng_float", default=44.85, help="Set Observer Latitude")
69 parser.add_option("-o", "--observing", type="eng_float", default=0.0,
70 help="Set observing frequency")
71 parser.add_option("-x", "--ylabel", default="dB", help="Y axis label")
72 parser.add_option("-z", "--divbase", type="eng_float", default=0.025, help="Y Division increment base")
73 parser.add_option("-v", "--stripsize", type="eng_float", default=2400, help="Size of stripchart, in 2Hz samples")
74 parser.add_option("-F", "--fft_size", type="eng_float", default=1024, help="Size of FFT")
76 parser.add_option("-N", "--decln", type="eng_float", default=999.99, help="Observing declination")
77 parser.add_option("-X", "--prefix", default="./")
78 parser.add_option("-M", "--fft_rate", type="eng_float", default=8.0, help="FFT Rate")
79 parser.add_option("-A", "--calib_coeff", type="eng_float", default=1.0, help="Calibration coefficient")
80 parser.add_option("-B", "--calib_offset", type="eng_float", default=0.0, help="Calibration coefficient")
81 parser.add_option("-W", "--waterfall", action="store_true", default=False, help="Use Waterfall FFT display")
82 parser.add_option("-S", "--setimode", action="store_true", default=False, help="Enable SETI processing of spectral data")
83 parser.add_option("-K", "--setik", type="eng_float", default=1.5, help="K value for SETI analysis")
84 parser.add_option("-T", "--setibandwidth", type="eng_float", default=12500, help="Instantaneous SETI observing bandwidth--must be divisor of 250Khz")
85 parser.add_option("-n", "--notches", action="store_true", default=False,
86 help="Notches appear after all other arguments")
87 parser.add_option("-Q", "--seti_range", type="eng_float", default=1.0e6, help="Total scan width, in Hz for SETI scans")
88 (options, args) = parser.parse_args()
90 self.notches = Numeric.zeros(64,Numeric.Float64)
91 if len(args) != 0 and options.notches == False:
95 if len(args) == 0 and options.notches != False:
99 self.use_notches = options.notches
101 # Get notch locations
104 self.notches[j] = float(i)
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 # If SETI mode, we always run at maximum USRP decimation
196 self.u = usrp.source_c(decim_rate=options.decim)
197 self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
198 # Set initial declination
199 self.decln = options.decln
201 # determine the daughterboard subdevice we're using
202 self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
203 self.cardtype = self.subdev.dbid()
205 input_rate = self.u.adc_freq() / self.u.decim_rate()
208 # Set prefix for data files
210 self.prefix = options.prefix
213 # The lower this number, the fewer sample frames are dropped
214 # in computing the FFT. A sampled approach is taken to
215 # computing the FFT of the incoming data, which reduces
216 # sensitivity. Increasing sensitivity inreases CPU loading.
218 self.fft_rate = options.fft_rate
220 self.fft_size = int(options.fft_size)
222 # This buffer is used to remember the most-recent FFT display
223 # values. Used later by self.write_spectral_data() to write
224 # spectral data to datalogging files, and by the SETI analysis
227 self.fft_outbuf = Numeric.zeros(self.fft_size, Numeric.Float64)
230 # If SETI mode, only look at seti_fft_bandwidth
234 self.fft_input_rate = self.seti_fft_bandwidth
237 # Build a decimating bandpass filter
239 self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
241 -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
242 gr.firdes.WIN_HAMMING, 0)
245 # Compute required decimation factor
247 decimation = int(input_rate/self.fft_input_rate)
248 self.fft_bandpass = gr.fir_filter_ccc (decimation,
251 self.fft_input_rate = input_rate
254 if self.waterfall == False:
255 self.scope = ra_fftsink.ra_fft_sink_c (panel,
256 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
257 fft_rate=int(self.fft_rate), title="Spectral",
258 ofunc=self.fft_outfunc, xydfunc=self.xydfunc)
260 self.scope = ra_waterfallsink.waterfall_sink_c (panel,
261 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
262 fft_rate=int(self.fft_rate), title="Spectral", ofunc=self.fft_outfunc, size=(1100, 600), xydfunc=self.xydfunc, ref_level=0, span=10)
264 # Set up ephemeris data
265 self.locality = ephem.Observer()
266 self.locality.long = str(options.longitude)
267 self.locality.lat = str(options.latitude)
268 # We make notes about Sunset/Sunrise in Continuum log files
269 self.sun = ephem.Sun()
272 # Set up stripchart display
273 self.stripsize = int(options.stripsize)
274 if self.setimode == False:
275 self.chart = ra_stripchartsink.stripchart_sink_f (panel,
276 stripsize=self.stripsize,
278 xlabel="LMST Offset (Seconds)",
279 scaling=1.0, ylabel=options.ylabel,
280 divbase=options.divbase)
282 # Set center frequency
283 self.centerfreq = options.freq
285 # Set observing frequency (might be different from actual programmed
287 if options.observing == 0.0:
288 self.observing = options.freq
290 self.observing = options.observing
294 # We setup the first two integrators to produce a fixed integration
295 # Down to 1Hz, with output at 1 samples/sec
298 # Second stage runs on decimated output of first
301 # Create taps for first integrator
307 # Create taps for second integrator
314 # The 3rd integrator is variable, and user selectable at runtime
315 # This integrator doesn't decimate, but is used to set the
316 # final integration time based on the constant 1Hz input samples
317 # The strip chart is fed at a constant 1Hz rate as a result
321 # Call constructors for receive chains
324 if self.setimode == False:
325 # The three integrators--two FIR filters, and an IIR final filter
326 self.integrator1 = gr.fir_filter_fff (N, tapsN)
327 self.integrator2 = gr.fir_filter_fff (M, tapsM)
328 self.integrator3 = gr.single_pole_iir_filter_ff(1.0)
331 self.detector = gr.complex_to_mag_squared()
335 self.probe = gr.probe_signal_f();
338 # Continuum calibration stuff
340 x = self.calib_coeff/100.0
341 self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0);
342 self.cal_offs = gr.add_const_ff(self.calib_offset*(x*8000));
344 if self.use_notches == True:
345 self.compute_notch_taps(self.notches)
346 self.notch_filt = gr.fft_filter_ccc(1, self.notch_taps)
349 # Start connecting configured modules in the receive chain
352 # The scope--handle SETI mode
353 if (self.setimode == False):
354 if (self.use_notches == True):
355 self.connect(self.u, self.notch_filt, self.scope)
357 self.connect(self.u, self.scope)
359 if (self.use_notches == True):
360 self.connect(self.u, self.notch_filt,
361 self.fft_bandpass, self.scope)
363 self.connect(self.u, self.fft_bandpass, self.scope)
365 if self.setimode == False:
366 if (self.use_notches == True):
367 self.connect(self.notch_filt, self.detector,
368 self.integrator1, self.integrator2,
369 self.integrator3, self.cal_mult, self.cal_offs, self.chart)
371 self.connect(self.u, self.detector,
372 self.integrator1, self.integrator2,
373 self.integrator3, self.cal_mult, self.cal_offs, self.chart)
375 # current instantaneous integrated detector value
376 self.connect(self.cal_offs, self.probe)
378 self._build_gui(vbox)
380 # Make GUI agree with command-line
381 self.integ = options.integ
382 if self.setimode == False:
383 self.myform['integration'].set_value(int(options.integ))
384 self.myform['offset'].set_value(self.calib_offset)
385 self.myform['dcgain'].set_value(self.calib_coeff)
386 self.myform['average'].set_value(int(options.avg))
389 if self.setimode == False:
390 # Make integrator agree with command line
391 self.set_integration(int(options.integ))
393 self.avg_alpha = options.avg
395 # Make spectral averager agree with command line
396 if options.avg != 1.0:
397 self.scope.set_avg_alpha(float(1.0/options.avg))
398 self.scope.set_average(True)
400 if self.setimode == False:
402 self.chart.set_y_per_div(options.division)
403 # Set reference(MAX) level
404 self.chart.set_ref_level(options.reflevel)
408 if options.gain is None:
409 # if no gain was specified, use the mid-point in dB
410 g = self.subdev.gain_range()
411 options.gain = float(g[0]+g[1])/2
413 if options.freq is None:
414 # if no freq was specified, use the mid-point
415 r = self.subdev.freq_range()
416 options.freq = float(r[0]+r[1])/2
418 # Set the initial gain control
419 self.set_gain(options.gain)
421 if not(self.set_freq(options.freq)):
422 self._set_status_msg("Failed to set initial frequency")
425 self.set_decln (self.decln)
428 # RF hardware information
429 self.myform['decim'].set_value(self.u.decim_rate())
430 self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
431 self.myform['dbname'].set_value(self.subdev.name())
433 # Set analog baseband filtering, if DBS_RX
434 if self.cardtype in (usrp_dbid.DBS_RX, usrp_dbid.DBS_RX_REV_2_1):
435 lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
438 self.subdev.set_bw(lbw)
440 # Start the timer for the LMST display and datalogging
441 self.lmst_timer.Start(1000)
444 def _set_status_msg(self, msg):
445 self.frame.GetStatusBar().SetStatusText(msg, 0)
447 def _build_gui(self, vbox):
449 def _form_set_freq(kv):
450 # Adjust current SETI frequency, and limits
451 self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
452 self.setifreq_current = kv['freq']
453 self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)
455 # Reset SETI analysis timer
456 self.seti_then = time.time()
457 # Zero-out hits array when changing frequency
458 self.hits_array[:,:] = 0.0
459 self.hit_intensities[:,:] = -60.0
461 return self.set_freq(kv['freq'])
463 def _form_set_decln(kv):
464 return self.set_decln(kv['decln'])
466 # Position the FFT display
467 vbox.Add(self.scope.win, 15, wx.EXPAND)
469 if self.setimode == False:
470 # Position the Total-power stripchart
471 vbox.Add(self.chart.win, 15, wx.EXPAND)
473 # add control area at the bottom
474 self.myform = myform = form.form()
475 hbox = wx.BoxSizer(wx.HORIZONTAL)
476 hbox.Add((7,0), 0, wx.EXPAND)
477 vbox1 = wx.BoxSizer(wx.VERTICAL)
478 myform['freq'] = form.float_field(
479 parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
480 callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
482 vbox1.Add((4,0), 0, 0)
484 myform['lmst_high'] = form.static_text_field(
485 parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
486 vbox1.Add((4,0), 0, 0)
488 if self.setimode == False:
489 myform['spec_data'] = form.static_text_field(
490 parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
491 vbox1.Add((4,0), 0, 0)
493 vbox2 = wx.BoxSizer(wx.VERTICAL)
494 if self.setimode == False:
495 vbox3 = wx.BoxSizer(wx.VERTICAL)
496 g = self.subdev.gain_range()
497 myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
499 min=int(g[0]), max=int(g[1]),
500 callback=self.set_gain)
502 vbox2.Add((4,0), 0, 0)
503 if self.setimode == True:
507 myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2,
508 label="Spectral Averaging (FFT frames)", weight=1, min=1, max=max_savg, callback=self.set_averaging)
510 # Set up scan control button when in SETI mode
511 if (self.setimode == True):
512 # SETI scanning control
513 buttonbox = wx.BoxSizer(wx.HORIZONTAL)
514 self.scan_control = form.button_with_callback(self.panel,
516 callback=self.toggle_scanning)
518 buttonbox.Add(self.scan_control, 0, wx.CENTER)
519 vbox2.Add(buttonbox, 0, wx.CENTER)
521 vbox2.Add((4,0), 0, 0)
523 if self.setimode == False:
524 myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
525 label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)
527 vbox2.Add((4,0), 0, 0)
529 myform['decln'] = form.float_field(
530 parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
531 callback=myform.check_input_and_call(_form_set_decln))
532 vbox2.Add((4,0), 0, 0)
534 if self.setimode == False:
535 myform['offset'] = form.slider_field(parent=self.panel, sizer=vbox3,
536 label="Post-Detector Offset", weight=1, min=-750, max=750,
537 callback=self.set_pd_offset)
538 vbox3.Add((2,0), 0, 0)
539 myform['dcgain'] = form.slider_field(parent=self.panel, sizer=vbox3,
540 label="Post-Detector Gain", weight=1, min=1, max=100,
541 callback=self.set_pd_gain)
542 vbox3.Add((2,0), 0, 0)
543 hbox.Add(vbox1, 0, 0)
544 hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
546 if self.setimode == False:
547 hbox.Add(vbox3, wx.ALIGN_RIGHT, 0)
549 vbox.Add(hbox, 0, wx.EXPAND)
551 self._build_subpanel(vbox)
553 self.lmst_timer = wx.PyTimer(self.lmst_timeout)
557 def _build_subpanel(self, vbox_arg):
558 # build a secondary information panel (sometimes hidden)
560 # FIXME figure out how to have this be a subpanel that is always
561 # created, but has its visibility controlled by foo.Show(True/False)
563 if not(self.show_debug_info):
570 #panel = wx.Panel(self.panel, -1)
571 #vbox = wx.BoxSizer(wx.VERTICAL)
573 hbox = wx.BoxSizer(wx.HORIZONTAL)
575 myform['decim'] = form.static_float_field(
576 parent=panel, sizer=hbox, label="Decim")
579 myform['fs@usb'] = form.static_float_field(
580 parent=panel, sizer=hbox, label="Fs@USB")
583 myform['dbname'] = form.static_text_field(
584 parent=panel, sizer=hbox)
587 myform['baseband'] = form.static_float_field(
588 parent=panel, sizer=hbox, label="Analog BB")
591 myform['ddc'] = form.static_float_field(
592 parent=panel, sizer=hbox, label="DDC")
595 vbox.Add(hbox, 0, wx.EXPAND)
599 def set_freq(self, target_freq):
601 Set the center frequency we're interested in.
603 @param target_freq: frequency in Hz
606 Tuning is a two step process. First we ask the front-end to
607 tune as close to the desired frequency as it can. Then we use
608 the result of that operation and our target_frequency to
609 determine the value for the digital down converter.
612 # Everything except BASIC_RX should support usrp.tune()
614 if not (self.cardtype == usrp_dbid.BASIC_RX):
615 r = usrp.tune(self.u, 0, self.subdev, target_freq)
617 r = self.u.set_rx_freq(0, target_freq)
618 f = self.u.rx_freq(0)
619 if abs(f-target_freq) > 2.0e3:
622 self.myform['freq'].set_value(target_freq) # update displayed value
624 # Make sure calibrator knows our target freq
627 # Remember centerfreq---used for doppler calcs
628 delta = self.centerfreq - target_freq
629 self.centerfreq = target_freq
630 self.observing -= delta
631 self.scope.set_baseband_freq (self.observing)
633 self.myform['baseband'].set_value(r.baseband_freq)
634 self.myform['ddc'].set_value(r.dxc_freq)
636 if self.use_notches == True:
637 self.compute_notch_taps(self.notches)
638 self.notch_filt.set_taps(self.notch_taps)
644 def set_decln(self, dec):
646 self.myform['decln'].set_value(dec) # update displayed value
648 def set_gain(self, gain):
649 self.myform['gain'].set_value(gain) # update displayed value
650 self.subdev.set_gain(gain)
653 def set_averaging(self, avval):
654 self.myform['average'].set_value(avval)
655 self.scope.set_avg_alpha(1.0/(avval))
656 self.scope.set_average(True)
657 self.avg_alpha = avval
659 def set_integration(self, integval):
660 if self.setimode == False:
661 self.integrator3.set_taps(1.0/integval)
662 self.myform['integration'].set_value(integval)
663 self.integ = integval
667 # Used to update LMST display, as well as current
670 # We also write external data-logging files here
672 def lmst_timeout(self):
673 self.locality.date = ephem.now()
674 if self.setimode == False:
675 x = self.probe.level()
676 sidtime = self.locality.sidereal_time()
678 s = str(ephem.hours(sidtime)) + " " + self.sunstate
679 # Continuum detector value
680 if self.setimode == False:
682 s = s + "\nDet: " + str(sx)
684 sx = "%2d" % self.hitcounter
685 s1 = "%2d" % self.s1hitcounter
686 s2 = "%2d" % self.s2hitcounter
687 sa = "%4.2f" % self.avgdelta
688 sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
689 s = s + "\nHits: " + str(sx) + "\nS1:" + str(s1) + " S2:" + str(s2)
690 s = s + "\nAv D: " + str(sa) + "\nCh lim: " + str(sy)
692 self.myform['lmst_high'].set_value(s)
695 # Write data out to recording files
697 if self.setimode == False:
698 self.write_continuum_data(x,sidtime)
699 self.write_spectral_data(self.fft_outbuf,sidtime)
702 self.seti_analysis(self.fft_outbuf,sidtime)
704 if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
706 self.setifreq_current = self.setifreq_current + self.fft_input_rate
707 if (self.setifreq_current > self.setifreq_upper):
708 self.setifreq_current = self.setifreq_lower
709 self.set_freq(self.setifreq_current)
710 # Make sure we zero-out the hits array when changing
712 self.hits_array[:,:] = 0.0
713 self.hit_intensities[:,:] = 0.0
715 def fft_outfunc(self,data,l):
718 def write_continuum_data(self,data,sidtime):
720 # Create localtime structure for producing filename
721 foo = time.localtime()
723 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
724 foo.tm_mon, foo.tm_mday, foo.tm_hour)
726 # Open the data file, appending
727 continuum_file = open (filenamestr+".tpdat","a")
741 # If time to write full header info (saves storage this way)
743 if (now - self.continuum_then > 20):
744 self.sun.compute(self.locality)
748 if ((self.sun.rise_time < enow) and (enow < self.sun.set_time)):
751 self.continuum_then = now
753 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
754 continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
755 continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
757 continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
759 continuum_file.close()
762 def write_spectral_data(self,data,sidtime):
767 # If time to write out spectral data
768 # We don't write this out every time, in order to
769 # save disk space. Since the spectral data are
770 # typically heavily averaged, writing this data
771 # "once in a while" is OK.
773 if (now - self.spectral_then >= delta):
774 self.spectral_then = now
776 # Get localtime structure to make filename from
777 foo = time.localtime()
780 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
781 foo.tm_mon, foo.tm_mday, foo.tm_hour)
784 spectral_file = open (filenamestr+".sdat","a")
786 # Setup data fields to be written
796 spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
797 spectral_file.write (" [ ")
799 spectral_file.write(" "+str(r))
801 spectral_file.write(" ]\n")
802 spectral_file.close()
807 def seti_analysis(self,fftbuf,sidtime):
812 if self.seticounter < self.setitimer:
813 self.seticounter = self.seticounter + 1
818 # Run through FFT output buffer, computing standard deviation (Sigma)
820 # First compute average
822 avg = avg + fftbuf[i]
826 # Then compute standard deviation (Sigma)
829 sigma = sigma + (d*d)
831 sigma = Numeric.sqrt(sigma/l)
834 # Snarfle through the FFT output buffer again, looking for
835 # outlying data points
837 start_f = self.observing - (self.fft_input_rate/2)
840 f_incr = self.fft_input_rate / l
844 for i in range(l/2,l):
846 # If current FFT buffer has an item that exceeds the specified
849 if ((fftbuf[i] - avg) > (self.setik * sigma)):
850 hits.append(current_f)
851 hit_intensities.append(fftbuf[i])
852 current_f = current_f + f_incr
855 for i in range(0,l/2):
857 # If current FFT buffer has an item that exceeds the specified
860 if ((fftbuf[i] - avg) > (self.setik * sigma)):
861 hits.append(current_f)
862 hit_intensities.append(fftbuf[i])
863 current_f = current_f + f_incr
871 # OK, so we have some hits in the FFT buffer
872 # They'll have a rather substantial gauntlet to run before
873 # being declared a real "hit"
877 self.s1hitcounter = self.s1hitcounter + len(hits)
879 # Weed out buffers with an excessive number of
880 # signals above Sigma
881 if (len(hits) > self.nhits):
885 # Weed out FFT buffers with apparent multiple narrowband signals
886 # separated significantly in frequency. This means that a
887 # single signal spanning multiple bins is OK, but a buffer that
888 # has multiple, apparently-separate, signals isn't OK.
892 for i in range(1,len(hits)):
893 if ((hits[i] - last) > (f_incr*3.0)):
898 self.s2hitcounter = self.s2hitcounter + ns2
901 # Run through all available hit buffers, computing difference between
902 # frequencies found there, if they're all within the chirp limits
906 f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
909 for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
910 f_ds[0] = abs(self.hits_array[i,0] - hits[i])
911 for j in range(1,len(f_ds)):
912 f_ds[j] = abs(self.hits_array[i,j] - self.hits_array[i,0])
913 avg_delta = avg_delta + f_ds[j]
916 if (self.seti_isahit (f_ds)):
918 self.hitcounter = self.hitcounter + 1
921 if (avg_delta/k < (self.seti_fft_bandwidth/2)):
922 self.avgdelta = avg_delta / k
924 # Save 'n shuffle hits
925 # Old hit buffers percolate through the hit buffers
926 # (there are self.nhitlines of these buffers)
927 # and then drop off the end
928 # A consequence is that while the nhitlines buffers are filling,
929 # you can get some absurd values for self.avgdelta, because some
930 # of the buffers are full of zeros
931 for i in range(self.nhitlines,1):
932 self.hits_array[:,i] = self.hits_array[:,i-1]
933 self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
935 for i in range(0,len(hits)):
936 self.hits_array[i,0] = hits[i]
937 self.hit_intensities[i,0] = hit_intensities[i]
939 # Finally, write the hits/intensities buffer
941 self.write_hits(sidtime)
945 def seti_isahit(self,fdiffs):
948 for i in range(0,len(fdiffs)):
949 if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
950 truecount = truecount + 1
952 if truecount == len(fdiffs):
957 def write_hits(self,sidtime):
958 # Create localtime structure for producing filename
959 foo = time.localtime()
961 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year,
962 foo.tm_mon, foo.tm_mday, foo.tm_hour)
964 # Open the data file, appending
965 hits_file = open (filenamestr+".seti","a")
967 # Write sidtime first
968 hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
971 # Then write the hits/hit intensities buffers with enough
972 # "syntax" to allow parsing by external (not yet written!)
975 for i in range(0,self.nhitlines):
977 for j in range(0,self.nhits):
978 hits_file.write(str(self.hits_array[j,i])+":")
979 hits_file.write(str(self.hit_intensities[j,i])+",")
980 hits_file.write("\n")
984 def xydfunc(self,xyv):
985 if self.setimode == True:
987 magn = int(Numeric.log10(self.observing))
988 if (magn == 6 or magn == 7 or magn == 8):
990 dfreq = xyv[0] * pow(10.0,magn)
991 ratio = self.observing / dfreq
1000 s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
1001 s2 = "\n%.3fkm/s" % vs
1002 self.myform['spec_data'].set_value(s+s2)
1004 def xydfunc_waterfall(self,pos):
1005 lower = self.observing - (self.seti_fft_bandwidth / 2)
1006 upper = self.observing + (self.seti_fft_bandwidth / 2)
1007 binwidth = self.seti_fft_bandwidth / 1024
1008 s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
1009 self.myform['spec_data'].set_value(s)
1011 def toggle_cal(self):
1012 if (self.calstate == True):
1013 self.calstate = False
1014 self.u.write_io(0,0,(1<<15))
1015 self.calibrator.SetLabel("Calibration Source: Off")
1017 self.calstate = True
1018 self.u.write_io(0,(1<<15),(1<<15))
1019 self.calibrator.SetLabel("Calibration Source: On")
1021 def toggle_annotation(self):
1022 if (self.annotate_state == True):
1023 self.annotate_state = False
1024 self.annotation.SetLabel("Annotation: Off")
1026 self.annotate_state = True
1027 self.annotation.SetLabel("Annotation: On")
1029 # Turn scanning on/off
1030 # Called-back by "Recording" button
1032 def toggle_scanning(self):
1033 # Current scanning? Flip state
1034 if (self.scanning == True):
1035 self.scanning = False
1036 self.scan_control.SetLabel("Scan: Off")
1039 self.scanning = True
1040 self.scan_control.SetLabel("Scan: On ")
1042 def set_pd_offset(self,offs):
1043 self.myform['offset'].set_value(offs)
1044 self.calib_offset=offs
1045 x = self.calib_coeff / 100.0
1046 self.cal_offs.set_k(offs*(x*8000))
1048 def set_pd_gain(self,gain):
1049 self.myform['dcgain'].set_value(gain)
1050 self.cal_mult.set_k(gain*0.01)
1051 self.calib_coeff = gain
1053 self.cal_offs.set_k(self.calib_offset*(x*8000))
1055 def compute_notch_taps(self,notchlist):
1057 tmptaps = Numeric.zeros(NOTCH_TAPS,Numeric.Complex64)
1058 binwidth = self.bw / NOTCH_TAPS
1060 for i in range(0,NOTCH_TAPS):
1061 tmptaps[i] = complex(1.0,0.0)
1064 diff = i - self.observing
1068 idx = diff / binwidth
1070 if (idx < 0 or idx > (NOTCH_TAPS/2)):
1072 tmptaps[idx] = complex(0.0, 0.0)
1075 idx = -diff / binwidth
1076 idx = (NOTCH_TAPS/2) - idx
1077 idx = int(idx+(NOTCH_TAPS/2))
1078 if (idx < 0 or idx > (NOTCH_TAPS)):
1080 tmptaps[idx] = complex(0.0, 0.0)
1082 self.notch_taps = numpy.fft.ifft(tmptaps)
1085 app = stdgui2.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1088 if __name__ == '__main__':