Added "Spectral Cursor" functionality into the waterfall display.
[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 2, 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 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         (options, args) = parser.parse_args()
86         if len(args) != 0:
87             parser.print_help()
88             sys.exit(1)
89
90         self.show_debug_info = True
91
92         # Pick up waterfall option
93         self.waterfall = options.waterfall
94
95         # SETI mode stuff
96         self.setimode = options.setimode
97         self.seticounter = 0
98         self.setik = options.setik
99         # Because we force the input rate to be 250Khz, 12.5Khz is
100         #  exactly 1/20th of this, which makes building decimators
101         #  easier.
102         # This also allows larger FFTs to be used without totally-gobbling
103         #  CPU.  With an FFT size of 16384, for example, this bandwidth
104         #  yields a binwidth of 0.762Hz, and plenty of CPU left over
105         #  for other things, like the SETI analysis code.
106         #
107         self.seti_fft_bandwidth = int(options.setibandwidth)
108
109         # Calculate binwidth
110         binwidth = self.seti_fft_bandwidth / options.fft_size
111
112         # Use binwidth, and knowledge of likely chirp rates to set reasonable
113         #  values for SETI analysis code.   We assume that SETI signals will
114         #  chirp at somewhere between 0.10Hz/sec and 0.25Hz/sec.
115         #
116         # upper_limit is the "worst case"--that is, the case for which we have
117         #  wait the longest to actually see any drift, due to the quantizing
118         #  on FFT bins.
119         upper_limit = binwidth / 0.10
120         self.setitimer = int(upper_limit * 2.00)
121
122         # Calculate the CHIRP values based on Hz/sec
123         self.CHIRP_LOWER = 0.10 * self.setitimer
124         self.CHIRP_UPPER = 0.25 * self.setitimer
125
126         # Reset hit counter to 0
127         self.hitcounter = 0
128         # We scan through 1Mhz of bandwidth around the chosen center freq
129         self.seti_freq_range = 1.0e6
130         # Calculate lower edge
131         self.setifreq_lower = options.freq - (self.seti_freq_range/2)
132         self.setifreq_current = options.freq
133         # Calculate upper edge
134         self.setifreq_upper = options.freq + (self.seti_freq_range/2)
135
136         # We change center frequencies every 20 self.setitimer intervals
137         self.setifreq_timer = self.setitimer * 20
138
139         # Create actual timer
140         self.seti_then = time.time()
141
142         # The hits recording array
143         self.nhits = 10
144         self.hits_array = Numeric.zeros((self.nhits,3), Numeric.Float64)
145
146         # Calibration coefficient and offset
147         self.calib_coeff = options.calib_coeff
148         self.calib_offset = options.calib_offset
149
150         self.integ = options.integ
151         self.avg_alpha = options.avg
152         self.gain = options.gain
153         self.decln = options.decln
154
155         # Set initial values for datalogging timed-output
156         self.continuum_then = time.time()
157         self.spectral_then = time.time()
158       
159         # build the graph
160
161         #
162         # If SETI mode, we always run at maximum USRP decimation
163         #
164         if (self.setimode):
165             options.decim = 256
166
167         self.u = usrp.source_c(decim_rate=options.decim)
168         self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
169         self.cardtype = self.u.daughterboard_id(0)
170         # Set initial declination
171         self.decln = options.decln
172
173         # determine the daughterboard subdevice we're using
174         self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
175
176         input_rate = self.u.adc_freq() / self.u.decim_rate()
177
178         #
179         # Set prefix for data files
180         #
181         self.prefix = options.prefix
182
183         #
184         # The lower this number, the fewer sample frames are dropped
185         #  in computing the FFT.  A sampled approach is taken to
186         #  computing the FFT of the incoming data, which reduces
187         #  sensitivity.  Increasing sensitivity inreases CPU loading.
188         #
189         self.fft_rate = options.fft_rate
190
191         self.fft_size = options.fft_size
192
193         # This buffer is used to remember the most-recent FFT display
194         #   values.  Used later by self.write_spectral_data() to write
195         #   spectral data to datalogging files, and by the SETI analysis
196         #   function.
197         #
198         self.fft_outbuf = Numeric.zeros(options.fft_size, Numeric.Float64)
199
200         #
201         # If SETI mode, only look at seti_fft_bandwidth (currently 12.5Khz)
202         #   at a time.
203         #
204         if (self.setimode):
205             self.fft_input_rate = self.seti_fft_bandwidth
206
207             #
208             # Build a decimating bandpass filter
209             #
210             self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
211                input_rate,
212                -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
213                gr.firdes.WIN_HAMMING, 0)
214
215             #
216             # Compute required decimation factor
217             #
218             decimation = int(input_rate/self.fft_input_rate)
219             self.fft_bandpass = gr.fir_filter_ccc (decimation, 
220                 self.fft_input_taps)
221         else:
222             self.fft_input_rate = input_rate
223
224         # Set up FFT display
225         if self.waterfall == False:
226            self.scope = ra_fftsink.ra_fft_sink_c (self, panel, 
227                fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
228                fft_rate=int(self.fft_rate), title="Spectral",  
229                ofunc=self.fft_outfunc, xydfunc=self.xydfunc)
230         else:
231             self.scope = ra_waterfallsink.ra_waterfallsink_c (self, panel,
232                 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
233                 fft_rate=int(self.fft_rate), title="Spectral", ofunc=self.fft_outfunc, xydfunc=self.xydfunc_waterfall)
234
235         # Set up ephemeris data
236         self.locality = ephem.Observer()
237         self.locality.long = str(options.longitude)
238         self.locality.lat = str(options.latitude)
239
240         # Set up stripchart display
241         self.stripsize = int(options.stripsize)
242         if self.setimode == False:
243             self.chart = ra_stripchartsink.stripchart_sink_f (self, panel,
244                 stripsize=self.stripsize,
245                 title="Continuum",
246                 xlabel="LMST Offset (Seconds)",
247                 scaling=1.0, ylabel=options.ylabel,
248                 divbase=options.divbase)
249
250         # Set center frequency
251         self.centerfreq = options.freq
252
253         # Set observing frequency (might be different from actual programmed
254         #    RF frequency)
255         if options.observing == 0.0:
256             self.observing = options.freq
257         else:
258             self.observing = options.observing
259
260         self.bw = input_rate
261
262         # We setup the first two integrators to produce a fixed integration
263         # Down to 1Hz, with output at 1 samples/sec
264         N = input_rate/5000
265
266         # Second stage runs on decimated output of first
267         M = (input_rate/N)
268
269         # Create taps for first integrator
270         t = range(0,N-1)
271         tapsN = []
272         for i in t:
273              tapsN.append(1.0/N)
274
275         # Create taps for second integrator
276         t = range(0,M-1)
277         tapsM = []
278         for i in t:
279             tapsM.append(1.0/M)
280
281         #
282         # The 3rd integrator is variable, and user selectable at runtime
283         # This integrator doesn't decimate, but is used to set the
284         #  final integration time based on the constant 1Hz input samples
285         # The strip chart is fed at a constant 1Hz rate as a result
286         #
287
288         #
289         # Call constructors for receive chains
290         #
291
292         if self.setimode == False:
293             # The three integrators--two FIR filters, and an IIR final filter
294             self.integrator1 = gr.fir_filter_fff (N, tapsN)
295             self.integrator2 = gr.fir_filter_fff (M, tapsM)
296             self.integrator3 = gr.single_pole_iir_filter_ff(1.0)
297     
298             # Split complex USRP stream into a pair of floats
299             self.splitter = gr.complex_to_float (1);
300     
301             # I squarer (detector)
302             self.multI = gr.multiply_ff();
303     
304             # Q squarer (detector)
305             self.multQ = gr.multiply_ff();
306     
307             # Adding squared I and Q to produce instantaneous signal power
308             self.adder = gr.add_ff();
309     
310             # Signal probe
311             self.probe = gr.probe_signal_f();
312     
313             #
314             # Continuum calibration stuff
315             #
316             self.cal_mult = gr.multiply_const_ff(self.calib_coeff);
317             self.cal_offs = gr.add_const_ff(self.calib_offset);
318
319         #
320         # Start connecting configured modules in the receive chain
321         #
322
323         # The scope--handle SETI mode
324         if (self.setimode == False):
325             self.connect(self.u, self.scope)
326         else:
327             self.connect(self.u, self.fft_bandpass, self.scope)
328
329         if self.setimode == False:
330             #
331             # The head of the continuum chain
332             #
333             self.connect(self.u, self.splitter)
334     
335             # Connect splitter outputs to multipliers
336             # First do I^2
337             self.connect((self.splitter, 0), (self.multI,0))
338             self.connect((self.splitter, 0), (self.multI,1))
339     
340             # Then do Q^2
341             self.connect((self.splitter, 1), (self.multQ,0))
342             self.connect((self.splitter, 1), (self.multQ,1))
343     
344             # Then sum the squares
345             self.connect(self.multI, (self.adder,0))
346             self.connect(self.multQ, (self.adder,1))
347     
348             # Connect adder output to two-stages of FIR integrator
349             #   followed by a single stage IIR integrator, and
350             #   the calibrator
351             self.connect(self.adder, self.integrator1, 
352                self.integrator2, self.integrator3, self.cal_mult, 
353                self.cal_offs, self.chart)
354     
355             # Connect calibrator to probe
356             # SPECIAL NOTE:  I'm setting the ground work here
357             #   for completely changing the way local_calibrator
358             #   works, including removing some horrible kludges for
359             #   recording data.
360             # But for now, self.probe() will be used to display the
361             #  current instantaneous integrated detector value
362             self.connect(self.cal_offs, self.probe)
363
364         self._build_gui(vbox)
365
366         # Make GUI agree with command-line
367         self.integ = options.integ
368         if self.setimode == False:
369             self.myform['integration'].set_value(int(options.integ))
370         self.myform['average'].set_value(int(options.avg))
371
372         if self.setimode == False:
373             # Make integrator agree with command line
374             self.set_integration(int(options.integ))
375
376         self.avg_alpha = options.avg
377
378         # Make spectral averager agree with command line
379         if options.avg != 1.0:
380             self.scope.set_avg_alpha(float(1.0/options.avg))
381             self.scope.set_average(True)
382
383         if self.setimode == False:
384             # Set division size
385             self.chart.set_y_per_div(options.division)
386             # Set reference(MAX) level
387             self.chart.set_ref_level(options.reflevel)
388
389         # set initial values
390
391         if options.gain is None:
392             # if no gain was specified, use the mid-point in dB
393             g = self.subdev.gain_range()
394             options.gain = float(g[0]+g[1])/2
395
396         if options.freq is None:
397             # if no freq was specified, use the mid-point
398             r = self.subdev.freq_range()
399             options.freq = float(r[0]+r[1])/2
400
401         # Set the initial gain control
402         self.set_gain(options.gain)
403
404         if not(self.set_freq(options.freq)):
405             self._set_status_msg("Failed to set initial frequency")
406
407         # Set declination
408         self.set_decln (self.decln)
409
410
411         # RF hardware information
412         self.myform['decim'].set_value(self.u.decim_rate())
413         self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
414         self.myform['dbname'].set_value(self.subdev.name())
415
416         # Set analog baseband filtering, if DBS_RX
417         if self.cardtype == usrp_dbid.DBS_RX:
418             lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
419             if lbw < 1.0e6:
420                 lbw = 1.0e6
421             self.subdev.set_bw(lbw)
422
423         # Start the timer for the LMST display and datalogging
424         self.lmst_timer.Start(1000)
425
426
427     def _set_status_msg(self, msg):
428         self.frame.GetStatusBar().SetStatusText(msg, 0)
429
430     def _build_gui(self, vbox):
431
432         def _form_set_freq(kv):
433             # Adjust current SETI frequency, and limits
434             self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
435             self.setifreq_current = kv['freq']
436             self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)
437
438             # Reset SETI analysis timer
439             self.seti_then = time.time()
440             # Zero-out hits array when changing frequency
441             self.hits_array[:,:] = 0.0
442
443             return self.set_freq(kv['freq'])
444
445         def _form_set_decln(kv):
446             return self.set_decln(kv['decln'])
447
448         # Position the FFT display
449         vbox.Add(self.scope.win, 15, wx.EXPAND)
450
451         if self.setimode == False:
452             # Position the Total-power stripchart
453             vbox.Add(self.chart.win, 15, wx.EXPAND)
454         
455         # add control area at the bottom
456         self.myform = myform = form.form()
457         hbox = wx.BoxSizer(wx.HORIZONTAL)
458         hbox.Add((7,0), 0, wx.EXPAND)
459         vbox1 = wx.BoxSizer(wx.VERTICAL)
460         myform['freq'] = form.float_field(
461             parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
462             callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
463
464         vbox1.Add((4,0), 0, 0)
465
466         myform['lmst_high'] = form.static_text_field(
467             parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
468         vbox1.Add((4,0), 0, 0)
469
470         myform['spec_data'] = form.static_text_field(
471             parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
472         vbox1.Add((4,0), 0, 0)
473
474         vbox2 = wx.BoxSizer(wx.VERTICAL)
475         g = self.subdev.gain_range()
476         myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
477                                            weight=1,
478                                            min=int(g[0]), max=int(g[1]),
479                                            callback=self.set_gain)
480
481         vbox2.Add((4,0), 0, 0)
482         myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2, 
483                     label="Spectral Averaging (FFT frames)", weight=1, min=1, max=2000, callback=self.set_averaging)
484
485         vbox2.Add((4,0), 0, 0)
486
487         if self.setimode == False:
488             myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
489                    label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)
490
491             vbox2.Add((4,0), 0, 0)
492
493         myform['decln'] = form.float_field(
494             parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
495             callback=myform.check_input_and_call(_form_set_decln))
496         vbox2.Add((4,0), 0, 0)
497
498         buttonbox = wx.BoxSizer(wx.HORIZONTAL)
499         vbox.Add(buttonbox, 0, wx.CENTER)
500         hbox.Add(vbox1, 0, 0)
501         hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
502         vbox.Add(hbox, 0, wx.EXPAND)
503
504         self._build_subpanel(vbox)
505
506         self.lmst_timer = wx.PyTimer(self.lmst_timeout)
507         #self.lmst_timeout()
508
509
510     def _build_subpanel(self, vbox_arg):
511         # build a secondary information panel (sometimes hidden)
512
513         # FIXME figure out how to have this be a subpanel that is always
514         # created, but has its visibility controlled by foo.Show(True/False)
515         
516         if not(self.show_debug_info):
517             return
518
519         panel = self.panel
520         vbox = vbox_arg
521         myform = self.myform
522
523         #panel = wx.Panel(self.panel, -1)
524         #vbox = wx.BoxSizer(wx.VERTICAL)
525
526         hbox = wx.BoxSizer(wx.HORIZONTAL)
527         hbox.Add((5,0), 0)
528         myform['decim'] = form.static_float_field(
529             parent=panel, sizer=hbox, label="Decim")
530
531         hbox.Add((5,0), 1)
532         myform['fs@usb'] = form.static_float_field(
533             parent=panel, sizer=hbox, label="Fs@USB")
534
535         hbox.Add((5,0), 1)
536         myform['dbname'] = form.static_text_field(
537             parent=panel, sizer=hbox)
538
539         hbox.Add((5,0), 1)
540         myform['baseband'] = form.static_float_field(
541             parent=panel, sizer=hbox, label="Analog BB")
542
543         hbox.Add((5,0), 1)
544         myform['ddc'] = form.static_float_field(
545             parent=panel, sizer=hbox, label="DDC")
546
547         hbox.Add((5,0), 0)
548         vbox.Add(hbox, 0, wx.EXPAND)
549
550         
551         
552     def set_freq(self, target_freq):
553         """
554         Set the center frequency we're interested in.
555
556         @param target_freq: frequency in Hz
557         @rypte: bool
558
559         Tuning is a two step process.  First we ask the front-end to
560         tune as close to the desired frequency as it can.  Then we use
561         the result of that operation and our target_frequency to
562         determine the value for the digital down converter.
563         """
564         #
565         # Everything except BASIC_RX should support usrp.tune()
566         #
567         if not (self.cardtype == usrp_dbid.BASIC_RX):
568             r = usrp.tune(self.u, 0, self.subdev, target_freq)
569         else:
570             r = self.u.set_rx_freq(0, target_freq)
571             f = self.u.rx_freq(0)
572             if abs(f-target_freq) > 2.0e3:
573                 r = 0
574         if r:
575             self.myform['freq'].set_value(target_freq)     # update displayed value
576             #
577             # Make sure calibrator knows our target freq
578             #
579
580             # Remember centerfreq---used for doppler calcs
581             delta = self.centerfreq - target_freq
582             self.centerfreq = target_freq
583             self.observing -= delta
584             self.scope.set_baseband_freq (self.observing)
585
586             self.myform['baseband'].set_value(r.baseband_freq)
587             self.myform['ddc'].set_value(r.dxc_freq)
588
589             return True
590
591         return False
592
593     def set_decln(self, dec):
594         self.decln = dec
595         self.myform['decln'].set_value(dec)     # update displayed value
596
597     def set_gain(self, gain):
598         self.myform['gain'].set_value(gain)     # update displayed value
599         self.subdev.set_gain(gain)
600         self.gain = gain
601
602     def set_averaging(self, avval):
603         self.myform['average'].set_value(avval)
604         self.scope.set_avg_alpha(1.0/(avval))
605         self.scope.set_average(True)
606         self.avg_alpha = avval
607
608     def set_integration(self, integval):
609         if self.setimode == False:
610             self.integrator3.set_taps(1.0/integval)
611         self.myform['integration'].set_value(integval)
612         self.integ = integval
613
614     #
615     # Timeout function
616     # Used to update LMST display, as well as current
617     #  continuum value
618     #
619     # We also write external data-logging files here
620     #
621     def lmst_timeout(self):
622          self.locality.date = ephem.now()
623          if self.setimode == False:
624              x = self.probe.level()
625          sidtime = self.locality.sidereal_time()
626          # LMST
627          s = str(ephem.hours(sidtime))
628          # Continuum detector value
629          if self.setimode == False:
630              sx = "%7.4f" % x
631              s = s + "\nDet: " + str(sx)
632          else:
633              sx = "%2d" % self.hitcounter
634              sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
635              s = s + "\nHits: " + str(sx) + "\nCh lim: " + str(sy)
636          self.myform['lmst_high'].set_value(s)
637
638          #
639          # Write data out to recording files
640          #
641          if self.setimode == False:
642              self.write_continuum_data(x,sidtime)
643              self.write_spectral_data(self.fft_outbuf,sidtime)
644
645          else:
646              self.seti_analysis(self.fft_outbuf,sidtime)
647              now = time.time()
648              if ((now - self.seti_then) > self.setifreq_timer):
649                  self.seti_then = now
650                  self.setifreq_current = self.setifreq_current + self.fft_input_rate
651                  if (self.setifreq_current > self.setifreq_upper):
652                      self.setifreq_current = self.setifreq_lower
653                  self.set_freq(self.setifreq_current)
654                  # Make sure we zero-out the hits array when changing
655                  #   frequency.
656                  self.hits_array[:,:] = 0.0
657
658     def fft_outfunc(self,data,l):
659         self.fft_outbuf=data
660
661     def write_continuum_data(self,data,sidtime):
662     
663         # Create localtime structure for producing filename
664         foo = time.localtime()
665         pfx = self.prefix
666         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
667            foo.tm_mon, foo.tm_mday, foo.tm_hour)
668     
669         # Open the data file, appending
670         continuum_file = open (filenamestr+".tpdat","a")
671       
672         flt = "%6.3f" % data
673         inter = self.decln
674         integ = self.integ
675         fc = self.observing
676         fc = fc / 1000000
677         bw = self.bw
678         bw = bw / 1000000
679         ga = self.gain
680     
681         now = time.time()
682     
683         #
684         # If time to write full header info (saves storage this way)
685         #
686         if (now - self.continuum_then > 20):
687             self.continuum_then = now
688         
689             continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
690             continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
691             continuum_file.write(",Ga="+str(ga)+"\n")
692         else:
693             continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
694     
695         continuum_file.close()
696         return(data)
697
698     def write_spectral_data(self,data,sidtime):
699     
700         now = time.time()
701         delta = 10
702                 
703         # If time to write out spectral data
704         # We don't write this out every time, in order to
705         #   save disk space.  Since the spectral data are
706         #   typically heavily averaged, writing this data
707         #   "once in a while" is OK.
708         #
709         if (now - self.spectral_then >= delta):
710             self.spectral_then = now
711
712             # Get localtime structure to make filename from
713             foo = time.localtime()
714         
715             pfx = self.prefix
716             filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
717                foo.tm_mon, foo.tm_mday, foo.tm_hour)
718     
719             # Open the file
720             spectral_file = open (filenamestr+".sdat","a")
721       
722             # Setup data fields to be written
723             r = data
724             inter = self.decln
725             fc = self.observing
726             fc = fc / 1000000
727             bw = self.bw
728             bw = bw / 1000000
729             av = self.avg_alpha
730
731             # Write those fields
732             spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
733             spectral_file.write(" "+str(r)+"\n")
734             spectral_file.close()
735             return(data)
736     
737         return(data)
738
739     def seti_analysis(self,fftbuf,sidtime):
740         l = len(fftbuf)
741         x = 0
742         hits = []
743         if self.seticounter < self.setitimer:
744             self.seticounter = self.seticounter + 1
745             return
746         else:
747             self.seticounter = 0
748
749         # Run through FFT output buffer, computing standard deviation (Sigma)
750         avg = 0
751         # First compute average
752         for i in range(0,l):
753             avg = avg + fftbuf[i]
754         avg = avg / l
755
756         sigma = 0.0
757         # Then compute standard deviation (Sigma)
758         for i in range(0,l):
759             d = fftbuf[i] - avg
760             sigma = sigma + (d*d)
761
762         sigma = Numeric.sqrt(sigma/l)
763
764         #
765         # Snarfle through the FFT output buffer again, looking for
766         #    outlying data points
767
768         start_f = self.observing - (self.fft_input_rate/2)
769         current_f = start_f
770         f_incr = self.fft_input_rate / l
771         l = len(fftbuf)
772         hit = -1
773
774         # -nyquist to DC
775         for i in range(l/2,l):
776             #
777             # If current FFT buffer has an item that exceeds the specified
778             #  sigma
779             #
780             if ((fftbuf[i] - avg) > (self.setik * sigma)):
781                 hits.append(current_f)
782             current_f = current_f + f_incr
783
784         # DC to nyquist
785         for i in range(0,l/2):
786             #
787             # If current FFT buffer has an item that exceeds the specified
788             #  sigma
789             #
790             if ((fftbuf[i] - avg) > (self.setik * sigma)):
791                 hits.append(current_f)
792             current_f = current_f + f_incr
793
794         if (len(hits) <= 0):
795             return
796
797         if (len(hits) > self.nhits):
798             return
799
800
801         #
802         # Run through all three hit buffers, computing difference between
803         #   frequencies found there, if they're all within the chirp limits
804         #   declare a good hit
805         #
806         good_hit = 0
807         good_hit = False
808         for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
809             f_d1 = abs(self.hits_array[i,0] - hits[i])
810             f_d2 = abs(self.hits_array[i,1] - self.hits_array[i,0])
811             f_d3 = abs(self.hits_array[i,2] - self.hits_array[i,1])
812             if (self.seti_isahit ([f_d1, f_d2, f_d3])):
813                 good_hit = True
814                 self.hitcounter = self.hitcounter + 1
815                 break
816
817         if (good_hit):
818             self.write_hits(hits,sidtime)
819
820         # Save 'n shuffle hits
821         self.hits_array[:,2] = self.hits_array[:,1]
822         self.hits_array[:,1] = self.hits_array[:,0]
823
824         for i in range(0,len(hits)):
825             self.hits_array[i,0] = hits[i]
826
827         return
828
829     def seti_isahit(self,fdiffs):
830         truecount = 0
831
832         for i in range(0,len(fdiffs)):
833             if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
834                 truecount = truecount + 1
835
836         if truecount == len(fdiffs):
837             return (True)
838         else:
839             return (False)
840
841     def write_hits(self,hits,sidtime):
842         # Create localtime structure for producing filename
843         foo = time.localtime()
844         pfx = self.prefix
845         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
846            foo.tm_mon, foo.tm_mday, foo.tm_hour)
847     
848         # Open the data file, appending
849         hits_file = open (filenamestr+".seti","a")
850         hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" "+str(hits)+"\n")
851         hits_file.close()
852         return
853
854     def xydfunc(self,xyv):
855         magn = int(Numeric.log10(self.observing))
856         if (magn == 6 or magn == 7 or magn == 8):
857             magn = 6
858         dfreq = xyv[0] * pow(10.0,magn)
859         ratio = self.observing / dfreq
860         vs = 1.0 - ratio
861         vs *= 299792.0
862         if magn >= 9:
863            xhz = "Ghz"
864         elif magn >= 6:
865            xhz = "Mhz"
866         elif magn <= 5:
867            xhz =  "Khz"
868         s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
869         s2 = "\n%.3fkm/s" % vs
870         self.myform['spec_data'].set_value(s+s2)
871
872     def xydfunc_waterfall(self,pos):
873         lower = self.observing - (self.seti_fft_bandwidth / 2)
874         upper = self.observing + (self.seti_fft_bandwidth / 2)
875         binwidth = self.seti_fft_bandwidth / 1024
876         s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
877         self.myform['spec_data'].set_value(s)
878
879     def toggle_cal(self):
880         if (self.calstate == True):
881           self.calstate = False
882           self.u.write_io(0,0,(1<<15))
883           self.calibrator.SetLabel("Calibration Source: Off")
884         else:
885           self.calstate = True
886           self.u.write_io(0,(1<<15),(1<<15))
887           self.calibrator.SetLabel("Calibration Source: On")
888
889     def toggle_annotation(self):
890         if (self.annotate_state == True):
891           self.annotate_state = False
892           self.annotation.SetLabel("Annotation: Off")
893         else:
894           self.annotate_state = True
895           self.annotation.SetLabel("Annotation: On")
896         
897
898 def main ():
899     app = stdgui.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
900     app.MainLoop()
901
902 if __name__ == '__main__':
903     main ()