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