]> git.gag.com Git - debian/gnuradio/blob - gr-radio-astronomy/src/python/usrp_ra_receiver.py
Added an experimental feature for listing notch frequencies on the command line
[debian/gnuradio] / gr-radio-astronomy / src / python / usrp_ra_receiver.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2004,2005 Free Software Foundation, Inc.
4
5 # This file is part of GNU Radio
6
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)
10 # any later version.
11
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.
16
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.
21
22
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 stdgui, ra_fftsink, ra_stripchartsink, ra_waterfallsink, form, slider
29 from optparse import OptionParser
30 import wx
31 import sys
32 import Numeric 
33 import time
34 import FFT
35 import ephem
36
37 class continuum_calibration(gr.feval_dd):
38     def eval(self, x):
39         str = globals()["calibration_codelet"]
40         exec(str)
41         return(x)
42
43 class app_flow_graph(stdgui.gui_flow_graph):
44     def __init__(self, frame, panel, vbox, argv):
45         stdgui.gui_flow_graph.__init__(self)
46
47         self.frame = frame
48         self.panel = panel
49         
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")
75
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         (options, args) = parser.parse_args()
88
89         self.notches = Numeric.zeros(64,Numeric.Float64)
90         if len(args) != 0 and options.notches == False:
91             parser.print_help()
92             sys.exit(1)
93
94         if len(args) == 0 and options.notches != False:
95             parser.print_help()
96             sys.exit()
97
98         self.use_notches = options.notches
99
100         # Get notch locations
101         j = 0
102         for i in args:
103             self.notches[j] = float(i)
104             j = j+1
105
106         self.notch_count = j
107
108         self.show_debug_info = True
109
110         # Pick up waterfall option
111         self.waterfall = options.waterfall
112
113         # SETI mode stuff
114         self.setimode = options.setimode
115         self.seticounter = 0
116         self.setik = options.setik
117         # Because we force the input rate to be 250Khz, 12.5Khz is
118         #  exactly 1/20th of this, which makes building decimators
119         #  easier.
120         # This also allows larger FFTs to be used without totally-gobbling
121         #  CPU.  With an FFT size of 16384, for example, this bandwidth
122         #  yields a binwidth of 0.762Hz, and plenty of CPU left over
123         #  for other things, like the SETI analysis code.
124         #
125         self.seti_fft_bandwidth = int(options.setibandwidth)
126
127         # Calculate binwidth
128         binwidth = self.seti_fft_bandwidth / options.fft_size
129
130         # Use binwidth, and knowledge of likely chirp rates to set reasonable
131         #  values for SETI analysis code.   We assume that SETI signals will
132         #  chirp at somewhere between 0.10Hz/sec and 0.25Hz/sec.
133         #
134         # upper_limit is the "worst case"--that is, the case for which we have
135         #  wait the longest to actually see any drift, due to the quantizing
136         #  on FFT bins.
137         upper_limit = binwidth / 0.10
138         self.setitimer = int(upper_limit * 2.00)
139         self.scanning = True
140
141         # Calculate the CHIRP values based on Hz/sec
142         self.CHIRP_LOWER = 0.10 * self.setitimer
143         self.CHIRP_UPPER = 0.25 * self.setitimer
144
145         # Reset hit counter to 0
146         self.hitcounter = 0
147         # We scan through 1Mhz of bandwidth around the chosen center freq
148         self.seti_freq_range = 1.0e6
149         # Calculate lower edge
150         self.setifreq_lower = options.freq - (self.seti_freq_range/2)
151         self.setifreq_current = options.freq
152         # Calculate upper edge
153         self.setifreq_upper = options.freq + (self.seti_freq_range/2)
154
155         # We change center frequencies every 10 self.setitimer intervals
156         self.setifreq_timer = self.setitimer * 10
157
158         # Create actual timer
159         self.seti_then = time.time()
160
161         # The hits recording array
162         self.nhits = 10
163         self.nhitlines = 3
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
173
174         if self.calib_coeff < 1:
175             self.calib_offset = 1
176         if self.calib_coeff > 100:
177             self.calib_offset = 100
178
179         self.integ = options.integ
180         self.avg_alpha = options.avg
181         self.gain = options.gain
182         self.decln = options.decln
183
184         # Set initial values for datalogging timed-output
185         self.continuum_then = time.time()
186         self.spectral_then = time.time()
187       
188         # build the graph
189
190         #
191         # If SETI mode, we always run at maximum USRP decimation
192         #
193         if (self.setimode):
194             options.decim = 256
195
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
200
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()
204
205         input_rate = self.u.adc_freq() / self.u.decim_rate()
206
207         #
208         # Set prefix for data files
209         #
210         self.prefix = options.prefix
211
212         #
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.
217         #
218         self.fft_rate = options.fft_rate
219
220         self.fft_size = int(options.fft_size)
221
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
225         #   function.
226         #
227         self.fft_outbuf = Numeric.zeros(self.fft_size, Numeric.Float64)
228
229         #
230         # If SETI mode, only look at seti_fft_bandwidth (currently 12.5Khz)
231         #   at a time.
232         #
233         if (self.setimode):
234             self.fft_input_rate = self.seti_fft_bandwidth
235
236             #
237             # Build a decimating bandpass filter
238             #
239             self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
240                input_rate,
241                -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
242                gr.firdes.WIN_HAMMING, 0)
243
244             #
245             # Compute required decimation factor
246             #
247             decimation = int(input_rate/self.fft_input_rate)
248             self.fft_bandpass = gr.fir_filter_ccc (decimation, 
249                 self.fft_input_taps)
250         else:
251             self.fft_input_rate = input_rate
252
253         # Set up FFT display
254         if self.waterfall == False:
255            self.scope = ra_fftsink.ra_fft_sink_c (self, 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)
259         else:
260             self.scope = ra_waterfallsink.ra_waterfallsink_c (self, 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, xydfunc=self.xydfunc_waterfall)
263
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()
270         self.sunstate = "??"
271
272         # Set up stripchart display
273         self.stripsize = int(options.stripsize)
274         if self.setimode == False:
275             self.chart = ra_stripchartsink.stripchart_sink_f (self, panel,
276                 stripsize=self.stripsize,
277                 title="Continuum",
278                 xlabel="LMST Offset (Seconds)",
279                 scaling=1.0, ylabel=options.ylabel,
280                 divbase=options.divbase)
281
282         # Set center frequency
283         self.centerfreq = options.freq
284
285         # Set observing frequency (might be different from actual programmed
286         #    RF frequency)
287         if options.observing == 0.0:
288             self.observing = options.freq
289         else:
290             self.observing = options.observing
291
292         self.bw = input_rate
293
294         # We setup the first two integrators to produce a fixed integration
295         # Down to 1Hz, with output at 1 samples/sec
296         N = input_rate/5000
297
298         # Second stage runs on decimated output of first
299         M = (input_rate/N)
300
301         # Create taps for first integrator
302         t = range(0,N-1)
303         tapsN = []
304         for i in t:
305              tapsN.append(1.0/N)
306
307         # Create taps for second integrator
308         t = range(0,M-1)
309         tapsM = []
310         for i in t:
311             tapsM.append(1.0/M)
312
313         #
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
318         #
319
320         #
321         # Call constructors for receive chains
322         #
323
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)
329     
330             # The detector
331             self.detector = gr.complex_to_mag_squared()
332
333     
334             # Signal probe
335             self.probe = gr.probe_signal_f();
336     
337             #
338             # Continuum calibration stuff
339             #
340             self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0);
341             self.cal_offs = gr.add_const_ff(self.calib_offset*4000);
342
343             if self.use_notches == True:
344                 NOTCH_TAPS = 256
345                 tmptaps = Numeric.zeros(NOTCH_TAPS,Numeric.Complex64)
346                 binwidth = self.bw / NOTCH_TAPS
347
348                 for i in range(0,NOTCH_TAPS):
349                     tmptaps[i] = complex(1.0,0.0)
350
351                 for i in self.notches:
352                     diff = i - self.observing
353                     if i == 0:
354                         break
355                     if (diff > 0):
356                         idx = diff / binwidth
357                         idx = idx + 1
358                         tmptaps[int(idx)] = complex(0.0, 0.0)
359                     if (diff < 0):
360                         idx = -diff / binwidth
361                         idx = (NOTCH_TAPS/2) - idx
362                         idx = int(idx+(NOTCH_TAPS/2))
363                         tmptaps[idx] = complex(0.0, 0.0)
364     
365                     self.notch_taps = FFT.inverse_fft(tmptaps)
366                     self.notch_filt = gr.fft_filter_ccc(1, self.notch_taps)
367
368         #
369         # Start connecting configured modules in the receive chain
370         #
371
372         # The scope--handle SETI mode
373         if (self.setimode == False):
374             if (self.use_notches == True):
375                 self.connect(self.u, self.notch_filt, self.scope)
376             else:
377                 self.connect(self.u, self.scope)
378         else:
379             if (self.use_notches == True):
380                 self.connect(self.u, self.notch_filt, 
381                     self.fft_bandpass, self.scope)
382             else:
383                 self.connect(self.u, self.fft_bandpass, self.scope)
384
385         if self.setimode == False:
386             if (self.use_notches == True):
387                 self.connect(self.notch_filt, self.detector, 
388                     self.integrator1, self.integrator2,
389                     self.integrator3, self.cal_mult, self.cal_offs, self.chart)
390             else:
391                 self.connect(self.u, self.detector, 
392                     self.integrator1, self.integrator2,
393                     self.integrator3, self.cal_mult, self.cal_offs, self.chart)
394     
395             #  current instantaneous integrated detector value
396             self.connect(self.cal_offs, self.probe)
397
398         self._build_gui(vbox)
399
400         # Make GUI agree with command-line
401         self.integ = options.integ
402         if self.setimode == False:
403             self.myform['integration'].set_value(int(options.integ))
404             self.myform['offset'].set_value(self.calib_offset)
405             self.myform['dcgain'].set_value(self.calib_coeff)
406         self.myform['average'].set_value(int(options.avg))
407
408
409         if self.setimode == False:
410             # Make integrator agree with command line
411             self.set_integration(int(options.integ))
412
413         self.avg_alpha = options.avg
414
415         # Make spectral averager agree with command line
416         if options.avg != 1.0:
417             self.scope.set_avg_alpha(float(1.0/options.avg))
418             self.scope.set_average(True)
419
420         if self.setimode == False:
421             # Set division size
422             self.chart.set_y_per_div(options.division)
423             # Set reference(MAX) level
424             self.chart.set_ref_level(options.reflevel)
425
426         # set initial values
427
428         if options.gain is None:
429             # if no gain was specified, use the mid-point in dB
430             g = self.subdev.gain_range()
431             options.gain = float(g[0]+g[1])/2
432
433         if options.freq is None:
434             # if no freq was specified, use the mid-point
435             r = self.subdev.freq_range()
436             options.freq = float(r[0]+r[1])/2
437
438         # Set the initial gain control
439         self.set_gain(options.gain)
440
441         if not(self.set_freq(options.freq)):
442             self._set_status_msg("Failed to set initial frequency")
443
444         # Set declination
445         self.set_decln (self.decln)
446
447
448         # RF hardware information
449         self.myform['decim'].set_value(self.u.decim_rate())
450         self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
451         self.myform['dbname'].set_value(self.subdev.name())
452
453         # Set analog baseband filtering, if DBS_RX
454         if self.cardtype in (usrp_dbid.DBS_RX, usrp_dbid.DBS_RX_REV_2_1):
455             lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
456             if lbw < 1.0e6:
457                 lbw = 1.0e6
458             self.subdev.set_bw(lbw)
459
460         # Start the timer for the LMST display and datalogging
461         self.lmst_timer.Start(1000)
462
463
464     def _set_status_msg(self, msg):
465         self.frame.GetStatusBar().SetStatusText(msg, 0)
466
467     def _build_gui(self, vbox):
468
469         def _form_set_freq(kv):
470             # Adjust current SETI frequency, and limits
471             self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
472             self.setifreq_current = kv['freq']
473             self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)
474
475             # Reset SETI analysis timer
476             self.seti_then = time.time()
477             # Zero-out hits array when changing frequency
478             self.hits_array[:,:] = 0.0
479             self.hit_intensities[:,:] = -60.0
480
481             return self.set_freq(kv['freq'])
482
483         def _form_set_decln(kv):
484             return self.set_decln(kv['decln'])
485
486         # Position the FFT display
487         vbox.Add(self.scope.win, 15, wx.EXPAND)
488
489         if self.setimode == False:
490             # Position the Total-power stripchart
491             vbox.Add(self.chart.win, 15, wx.EXPAND)
492         
493         # add control area at the bottom
494         self.myform = myform = form.form()
495         hbox = wx.BoxSizer(wx.HORIZONTAL)
496         hbox.Add((7,0), 0, wx.EXPAND)
497         vbox1 = wx.BoxSizer(wx.VERTICAL)
498         myform['freq'] = form.float_field(
499             parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
500             callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
501
502         vbox1.Add((4,0), 0, 0)
503
504         myform['lmst_high'] = form.static_text_field(
505             parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
506         vbox1.Add((4,0), 0, 0)
507
508         myform['spec_data'] = form.static_text_field(
509             parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
510         vbox1.Add((4,0), 0, 0)
511
512         vbox2 = wx.BoxSizer(wx.VERTICAL)
513         if self.setimode == False:
514             vbox3 = wx.BoxSizer(wx.VERTICAL)
515         g = self.subdev.gain_range()
516         myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
517                                            weight=1,
518                                            min=int(g[0]), max=int(g[1]),
519                                            callback=self.set_gain)
520
521         vbox2.Add((4,0), 0, 0)
522         myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2, 
523                     label="Spectral Averaging (FFT frames)", weight=1, min=1, max=3000, callback=self.set_averaging)
524
525         # Set up scan control button when in SETI mode
526         if (self.setimode == True):
527                 # SETI scanning control
528                 buttonbox = wx.BoxSizer(wx.HORIZONTAL)
529                 self.scan_control = form.button_with_callback(self.panel,
530                       label="Scan: On ",
531                       callback=self.toggle_scanning)
532         
533                 buttonbox.Add(self.scan_control, 0, wx.CENTER)
534                 vbox2.Add(buttonbox, 0, wx.CENTER)
535
536         vbox2.Add((4,0), 0, 0)
537
538         if self.setimode == False:
539             myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
540                    label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)
541
542             vbox2.Add((4,0), 0, 0)
543
544         myform['decln'] = form.float_field(
545             parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
546             callback=myform.check_input_and_call(_form_set_decln))
547         vbox2.Add((4,0), 0, 0)
548
549         if self.setimode == False:
550             myform['offset'] = form.slider_field(parent=self.panel, sizer=vbox3,
551                 label="Post-Detector Offset", weight=1, min=-750, max=750, 
552                 callback=self.set_pd_offset)
553             vbox3.Add((2,0), 0, 0)
554             myform['dcgain'] = form.slider_field(parent=self.panel, sizer=vbox3,
555                 label="Post-Detector Gain", weight=1, min=1, max=100, 
556                 callback=self.set_pd_gain)
557             vbox3.Add((2,0), 0, 0)
558         hbox.Add(vbox1, 0, 0)
559         hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
560
561         if self.setimode == False:
562             hbox.Add(vbox3, wx.ALIGN_RIGHT, 0)
563
564         vbox.Add(hbox, 0, wx.EXPAND)
565
566         self._build_subpanel(vbox)
567
568         self.lmst_timer = wx.PyTimer(self.lmst_timeout)
569         #self.lmst_timeout()
570
571
572     def _build_subpanel(self, vbox_arg):
573         # build a secondary information panel (sometimes hidden)
574
575         # FIXME figure out how to have this be a subpanel that is always
576         # created, but has its visibility controlled by foo.Show(True/False)
577         
578         if not(self.show_debug_info):
579             return
580
581         panel = self.panel
582         vbox = vbox_arg
583         myform = self.myform
584
585         #panel = wx.Panel(self.panel, -1)
586         #vbox = wx.BoxSizer(wx.VERTICAL)
587
588         hbox = wx.BoxSizer(wx.HORIZONTAL)
589         hbox.Add((5,0), 0)
590         myform['decim'] = form.static_float_field(
591             parent=panel, sizer=hbox, label="Decim")
592
593         hbox.Add((5,0), 1)
594         myform['fs@usb'] = form.static_float_field(
595             parent=panel, sizer=hbox, label="Fs@USB")
596
597         hbox.Add((5,0), 1)
598         myform['dbname'] = form.static_text_field(
599             parent=panel, sizer=hbox)
600
601         hbox.Add((5,0), 1)
602         myform['baseband'] = form.static_float_field(
603             parent=panel, sizer=hbox, label="Analog BB")
604
605         hbox.Add((5,0), 1)
606         myform['ddc'] = form.static_float_field(
607             parent=panel, sizer=hbox, label="DDC")
608
609         hbox.Add((5,0), 0)
610         vbox.Add(hbox, 0, wx.EXPAND)
611
612         
613         
614     def set_freq(self, target_freq):
615         """
616         Set the center frequency we're interested in.
617
618         @param target_freq: frequency in Hz
619         @rypte: bool
620
621         Tuning is a two step process.  First we ask the front-end to
622         tune as close to the desired frequency as it can.  Then we use
623         the result of that operation and our target_frequency to
624         determine the value for the digital down converter.
625         """
626         #
627         # Everything except BASIC_RX should support usrp.tune()
628         #
629         if not (self.cardtype == usrp_dbid.BASIC_RX):
630             r = usrp.tune(self.u, 0, self.subdev, target_freq)
631         else:
632             r = self.u.set_rx_freq(0, target_freq)
633             f = self.u.rx_freq(0)
634             if abs(f-target_freq) > 2.0e3:
635                 r = 0
636         if r:
637             self.myform['freq'].set_value(target_freq)     # update displayed value
638             #
639             # Make sure calibrator knows our target freq
640             #
641
642             # Remember centerfreq---used for doppler calcs
643             delta = self.centerfreq - target_freq
644             self.centerfreq = target_freq
645             self.observing -= delta
646             self.scope.set_baseband_freq (self.observing)
647
648             self.myform['baseband'].set_value(r.baseband_freq)
649             self.myform['ddc'].set_value(r.dxc_freq)
650
651             return True
652
653         return False
654
655     def set_decln(self, dec):
656         self.decln = dec
657         self.myform['decln'].set_value(dec)     # update displayed value
658
659     def set_gain(self, gain):
660         self.myform['gain'].set_value(gain)     # update displayed value
661         self.subdev.set_gain(gain)
662         self.gain = gain
663
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
669
670     def set_integration(self, integval):
671         if self.setimode == False:
672             self.integrator3.set_taps(1.0/integval)
673         self.myform['integration'].set_value(integval)
674         self.integ = integval
675
676     #
677     # Timeout function
678     # Used to update LMST display, as well as current
679     #  continuum value
680     #
681     # We also write external data-logging files here
682     #
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()
688          # LMST
689          s = str(ephem.hours(sidtime)) + " " + self.sunstate
690          # Continuum detector value
691          if self.setimode == False:
692              sx = "%7.4f" % x
693              s = s + "\nDet: " + str(sx)
694          else:
695              sx = "%2d" % self.hitcounter
696              sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
697              s = s + "\nHits: " + str(sx) + "\nCh lim: " + str(sy)
698          self.myform['lmst_high'].set_value(s)
699
700          #
701          # Write data out to recording files
702          #
703          if self.setimode == False:
704              self.write_continuum_data(x,sidtime)
705              self.write_spectral_data(self.fft_outbuf,sidtime)
706
707          else:
708              self.seti_analysis(self.fft_outbuf,sidtime)
709              now = time.time()
710              if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
711                  self.seti_then = now
712                  self.setifreq_current = self.setifreq_current + self.fft_input_rate
713                  if (self.setifreq_current > self.setifreq_upper):
714                      self.setifreq_current = self.setifreq_lower
715                  self.set_freq(self.setifreq_current)
716                  # Make sure we zero-out the hits array when changing
717                  #   frequency.
718                  self.hits_array[:,:] = 0.0
719                  self.hit_intensities[:,:] = 0.0
720
721     def fft_outfunc(self,data,l):
722         self.fft_outbuf=data
723
724     def write_continuum_data(self,data,sidtime):
725     
726         # Create localtime structure for producing filename
727         foo = time.localtime()
728         pfx = self.prefix
729         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
730            foo.tm_mon, foo.tm_mday, foo.tm_hour)
731     
732         # Open the data file, appending
733         continuum_file = open (filenamestr+".tpdat","a")
734       
735         flt = "%6.3f" % data
736         inter = self.decln
737         integ = self.integ
738         fc = self.observing
739         fc = fc / 1000000
740         bw = self.bw
741         bw = bw / 1000000
742         ga = self.gain
743     
744         now = time.time()
745     
746         #
747         # If time to write full header info (saves storage this way)
748         #
749         if (now - self.continuum_then > 20):
750             self.sun.compute(self.locality)
751             enow = ephem.now()
752             sun_insky = "Down"
753             self.sunstate = "Dn"
754             if ((self.sun.rise_time < enow) and (enow < self.sun.set_time)):
755                sun_insky = "Up"
756                self.sunstate = "Up"
757             self.continuum_then = now
758         
759             continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
760             continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
761             continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
762         else:
763             continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
764     
765         continuum_file.close()
766         return(data)
767
768     def write_spectral_data(self,data,sidtime):
769     
770         now = time.time()
771         delta = 10
772                 
773         # If time to write out spectral data
774         # We don't write this out every time, in order to
775         #   save disk space.  Since the spectral data are
776         #   typically heavily averaged, writing this data
777         #   "once in a while" is OK.
778         #
779         if (now - self.spectral_then >= delta):
780             self.spectral_then = now
781
782             # Get localtime structure to make filename from
783             foo = time.localtime()
784         
785             pfx = self.prefix
786             filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
787                foo.tm_mon, foo.tm_mday, foo.tm_hour)
788     
789             # Open the file
790             spectral_file = open (filenamestr+".sdat","a")
791       
792             # Setup data fields to be written
793             r = data
794             inter = self.decln
795             fc = self.observing
796             fc = fc / 1000000
797             bw = self.bw
798             bw = bw / 1000000
799             av = self.avg_alpha
800
801             # Write those fields
802             spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
803             spectral_file.write(" "+str(r)+"\n")
804             spectral_file.close()
805             return(data)
806     
807         return(data)
808
809     def seti_analysis(self,fftbuf,sidtime):
810         l = len(fftbuf)
811         x = 0
812         hits = []
813         hit_intensities = []
814         if self.seticounter < self.setitimer:
815             self.seticounter = self.seticounter + 1
816             return
817         else:
818             self.seticounter = 0
819
820         # Run through FFT output buffer, computing standard deviation (Sigma)
821         avg = 0
822         # First compute average
823         for i in range(0,l):
824             avg = avg + fftbuf[i]
825         avg = avg / l
826
827         sigma = 0.0
828         # Then compute standard deviation (Sigma)
829         for i in range(0,l):
830             d = fftbuf[i] - avg
831             sigma = sigma + (d*d)
832
833         sigma = Numeric.sqrt(sigma/l)
834
835         #
836         # Snarfle through the FFT output buffer again, looking for
837         #    outlying data points
838
839         start_f = self.observing - (self.fft_input_rate/2)
840         current_f = start_f
841         f_incr = self.fft_input_rate / l
842         l = len(fftbuf)
843         hit = -1
844
845         # -nyquist to DC
846         for i in range(l/2,l):
847             #
848             # If current FFT buffer has an item that exceeds the specified
849             #  sigma
850             #
851             if ((fftbuf[i] - avg) > (self.setik * sigma)):
852                 hits.append(current_f)
853                 hit_intensities.append(fftbuf[i])
854             current_f = current_f + f_incr
855
856         # DC to nyquist
857         for i in range(0,l/2):
858             #
859             # If current FFT buffer has an item that exceeds the specified
860             #  sigma
861             #
862             if ((fftbuf[i] - avg) > (self.setik * sigma)):
863                 hits.append(current_f)
864                 hit_intensities.append(fftbuf[i])
865             current_f = current_f + f_incr
866
867         # No hits
868         if (len(hits) <= 0):
869             return
870
871         #
872         # OK, so we have some hits in the FFT buffer
873         #   They'll have a rather substantial gauntlet to run before
874         #   being declared a real "hit"
875         #
876
877         # Weed out buffers with an excessive number of strong signals
878         if (len(hits) > self.nhits):
879             return
880
881         # Weed out FFT buffers with apparent multiple narrowband signals
882         #   separated significantly in frequency.  This means that a
883         #   single signal spanning multiple bins is OK, but a buffer that
884         #   has multiple, apparently-separate, signals isn't OK.
885         #
886         last = hits[0]
887         for i in range(1,len(hits)):
888             if ((hits[i] - last) > (f_incr*2.0)):
889                 return
890             last = hits[i]
891
892         #
893         # Run through all three hit buffers, computing difference between
894         #   frequencies found there, if they're all within the chirp limits
895         #   declare a good hit
896         #
897         good_hit = 0
898         good_hit = False
899         for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
900             f_d1 = abs(self.hits_array[i,0] - hits[i])
901             f_d2 = abs(self.hits_array[i,1] - self.hits_array[i,0])
902             f_d3 = abs(self.hits_array[i,2] - self.hits_array[i,1])
903             if (self.seti_isahit ([f_d1, f_d2, f_d3])):
904                 good_hit = True
905                 self.hitcounter = self.hitcounter + 1
906                 break
907
908
909         # Save 'n shuffle hits
910         for i in range(self.nhitlines,1):
911             self.hits_array[:,i] = self.hits_array[:,i-1]
912             self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
913
914         for i in range(0,len(hits)):
915             self.hits_array[i,0] = hits[i]
916             self.hit_intensities[i,0] = hit_intensities[i]
917
918         # Finally, write the hits/intensities buffer
919         if (good_hit):
920             self.write_hits(sidtime)
921
922         return
923
924     def seti_isahit(self,fdiffs):
925         truecount = 0
926
927         for i in range(0,len(fdiffs)):
928             if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
929                 truecount = truecount + 1
930
931         if truecount == len(fdiffs):
932             return (True)
933         else:
934             return (False)
935
936     def write_hits(self,sidtime):
937         # Create localtime structure for producing filename
938         foo = time.localtime()
939         pfx = self.prefix
940         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
941            foo.tm_mon, foo.tm_mday, foo.tm_hour)
942     
943         # Open the data file, appending
944         hits_file = open (filenamestr+".seti","a")
945
946         # Write sidtime first
947         hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
948
949         #
950         # Then write the hits/hit intensities buffers with enough
951         #   "syntax" to allow parsing by external (not yet written!)
952         #   "stuff".
953         #
954         for i in range(0,self.nhitlines):
955             hits_file.write(" ")
956             for j in range(0,self.nhits):
957                 hits_file.write(str(self.hits_array[j,i])+":")
958                 hits_file.write(str(self.hit_intensities[j,i])+",")
959         hits_file.write("\n")
960         hits_file.close()
961         return
962
963     def xydfunc(self,xyv):
964         magn = int(Numeric.log10(self.observing))
965         if (magn == 6 or magn == 7 or magn == 8):
966             magn = 6
967         dfreq = xyv[0] * pow(10.0,magn)
968         ratio = self.observing / dfreq
969         vs = 1.0 - ratio
970         vs *= 299792.0
971         if magn >= 9:
972            xhz = "Ghz"
973         elif magn >= 6:
974            xhz = "Mhz"
975         elif magn <= 5:
976            xhz =  "Khz"
977         s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
978         s2 = "\n%.3fkm/s" % vs
979         self.myform['spec_data'].set_value(s+s2)
980
981     def xydfunc_waterfall(self,pos):
982         lower = self.observing - (self.seti_fft_bandwidth / 2)
983         upper = self.observing + (self.seti_fft_bandwidth / 2)
984         binwidth = self.seti_fft_bandwidth / 1024
985         s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
986         self.myform['spec_data'].set_value(s)
987
988     def toggle_cal(self):
989         if (self.calstate == True):
990           self.calstate = False
991           self.u.write_io(0,0,(1<<15))
992           self.calibrator.SetLabel("Calibration Source: Off")
993         else:
994           self.calstate = True
995           self.u.write_io(0,(1<<15),(1<<15))
996           self.calibrator.SetLabel("Calibration Source: On")
997
998     def toggle_annotation(self):
999         if (self.annotate_state == True):
1000           self.annotate_state = False
1001           self.annotation.SetLabel("Annotation: Off")
1002         else:
1003           self.annotate_state = True
1004           self.annotation.SetLabel("Annotation: On")
1005     #
1006     # Turn scanning on/off
1007     # Called-back by "Recording" button
1008     #
1009     def toggle_scanning(self):
1010         # Current scanning?  Flip state
1011         if (self.scanning == True):
1012           self.scanning = False
1013           self.scan_control.SetLabel("Scan: Off")
1014         # Not scanning
1015         else:
1016           self.scanning = True
1017           self.scan_control.SetLabel("Scan: On ")
1018
1019     def set_pd_offset(self,offs):
1020          self.myform['offset'].set_value(offs)
1021          self.calib_offset=offs
1022          self.cal_offs.set_k(offs*4000)
1023
1024     def set_pd_gain(self,gain):
1025          self.myform['dcgain'].set_value(gain)
1026          self.cal_mult.set_k(gain*0.01)
1027          self.calib_coeff = gain
1028
1029 def main ():
1030     app = stdgui.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1031     app.MainLoop()
1032
1033 if __name__ == '__main__':
1034     main ()