Removed a diagnostics print
[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, waterfallsink
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         parser.add_option("-Q", "--seti_range", type="eng_float", default=1.0e6, help="Total scan width, in Hz for SETI scans")
88         (options, args) = parser.parse_args()
89
90         self.notches = Numeric.zeros(64,Numeric.Float64)
91         if len(args) != 0 and options.notches == False:
92             parser.print_help()
93             sys.exit(1)
94
95         if len(args) == 0 and options.notches != False:
96             parser.print_help()
97             sys.exit()
98
99         self.use_notches = options.notches
100
101         # Get notch locations
102         j = 0
103         for i in args:
104             self.notches[j] = float(i)
105             j = j+1
106
107         self.notch_count = j
108
109         self.show_debug_info = True
110
111         # Pick up waterfall option
112         self.waterfall = options.waterfall
113
114         # SETI mode stuff
115         self.setimode = options.setimode
116         self.seticounter = 0
117         self.setik = options.setik
118         self.seti_fft_bandwidth = int(options.setibandwidth)
119
120         # Calculate binwidth
121         binwidth = self.seti_fft_bandwidth / options.fft_size
122
123         # Use binwidth, and knowledge of likely chirp rates to set reasonable
124         #  values for SETI analysis code.   We assume that SETI signals will
125         #  chirp at somewhere between 0.10Hz/sec and 0.25Hz/sec.
126         #
127         # upper_limit is the "worst case"--that is, the case for which we have
128         #  to wait the longest to actually see any drift, due to the quantizing
129         #  on FFT bins.
130         upper_limit = binwidth / 0.10
131         self.setitimer = int(upper_limit * 2.00)
132         self.scanning = True
133
134         # Calculate the CHIRP values based on Hz/sec
135         self.CHIRP_LOWER = 0.10 * self.setitimer
136         self.CHIRP_UPPER = 0.25 * self.setitimer
137
138         # Reset hit counters to 0
139         self.hitcounter = 0
140         self.s1hitcounter = 0
141         self.s2hitcounter = 0
142         self.avgdelta = 0
143         # We scan through 2Mhz of bandwidth around the chosen center freq
144         self.seti_freq_range = options.seti_range
145         # Calculate lower edge
146         self.setifreq_lower = options.freq - (self.seti_freq_range/2)
147         self.setifreq_current = options.freq
148         # Calculate upper edge
149         self.setifreq_upper = options.freq + (self.seti_freq_range/2)
150
151         # Maximum "hits" in a line
152         self.nhits = 20
153
154         # Number of lines for analysis
155         self.nhitlines = 4
156
157         # We change center frequencies based on nhitlines and setitimer
158         self.setifreq_timer = self.setitimer * (self.nhitlines * 5)
159
160         # Create actual timer
161         self.seti_then = time.time()
162
163         # The hits recording array
164         self.hits_array = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
165         self.hit_intensities = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
166         # Calibration coefficient and offset
167         self.calib_coeff = options.calib_coeff
168         self.calib_offset = options.calib_offset
169         if self.calib_offset < -750:
170             self.calib_offset = -750
171         if self.calib_offset > 750:
172             self.calib_offset = 750
173
174         if self.calib_coeff < 1:
175             self.calib_coeff = 1
176         if self.calib_coeff > 100:
177             self.calib_coeff = 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
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.waterfall_sink_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, size=(1100, 600), xydfunc=self.xydfunc, ref_level=0, span=10)
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             x = self.calib_coeff/100.0
341             self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0);
342             self.cal_offs = gr.add_const_ff(self.calib_offset*(x*8000));
343
344             if self.use_notches == True:
345                 self.compute_notch_taps(self.notches)
346                 self.notch_filt = gr.fft_filter_ccc(1, self.notch_taps)
347
348         #
349         # Start connecting configured modules in the receive chain
350         #
351
352         # The scope--handle SETI mode
353         if (self.setimode == False):
354             if (self.use_notches == True):
355                 self.connect(self.u, self.notch_filt, self.scope)
356             else:
357                 self.connect(self.u, self.scope)
358         else:
359             if (self.use_notches == True):
360                 self.connect(self.u, self.notch_filt, 
361                     self.fft_bandpass, self.scope)
362             else:
363                 self.connect(self.u, self.fft_bandpass, self.scope)
364
365         if self.setimode == False:
366             if (self.use_notches == True):
367                 self.connect(self.notch_filt, self.detector, 
368                     self.integrator1, self.integrator2,
369                     self.integrator3, self.cal_mult, self.cal_offs, self.chart)
370             else:
371                 self.connect(self.u, self.detector, 
372                     self.integrator1, self.integrator2,
373                     self.integrator3, self.cal_mult, self.cal_offs, self.chart)
374     
375             #  current instantaneous integrated detector value
376             self.connect(self.cal_offs, self.probe)
377
378         self._build_gui(vbox)
379
380         # Make GUI agree with command-line
381         self.integ = options.integ
382         if self.setimode == False:
383             self.myform['integration'].set_value(int(options.integ))
384             self.myform['offset'].set_value(self.calib_offset)
385             self.myform['dcgain'].set_value(self.calib_coeff)
386         self.myform['average'].set_value(int(options.avg))
387
388
389         if self.setimode == False:
390             # Make integrator agree with command line
391             self.set_integration(int(options.integ))
392
393         self.avg_alpha = options.avg
394
395         # Make spectral averager agree with command line
396         if options.avg != 1.0:
397             self.scope.set_avg_alpha(float(1.0/options.avg))
398             self.scope.set_average(True)
399
400         if self.setimode == False:
401             # Set division size
402             self.chart.set_y_per_div(options.division)
403             # Set reference(MAX) level
404             self.chart.set_ref_level(options.reflevel)
405
406         # set initial values
407
408         if options.gain is None:
409             # if no gain was specified, use the mid-point in dB
410             g = self.subdev.gain_range()
411             options.gain = float(g[0]+g[1])/2
412
413         if options.freq is None:
414             # if no freq was specified, use the mid-point
415             r = self.subdev.freq_range()
416             options.freq = float(r[0]+r[1])/2
417
418         # Set the initial gain control
419         self.set_gain(options.gain)
420
421         if not(self.set_freq(options.freq)):
422             self._set_status_msg("Failed to set initial frequency")
423
424         # Set declination
425         self.set_decln (self.decln)
426
427
428         # RF hardware information
429         self.myform['decim'].set_value(self.u.decim_rate())
430         self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
431         self.myform['dbname'].set_value(self.subdev.name())
432
433         # Set analog baseband filtering, if DBS_RX
434         if self.cardtype in (usrp_dbid.DBS_RX, usrp_dbid.DBS_RX_REV_2_1):
435             lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
436             if lbw < 1.0e6:
437                 lbw = 1.0e6
438             self.subdev.set_bw(lbw)
439
440         # Start the timer for the LMST display and datalogging
441         self.lmst_timer.Start(1000)
442
443
444     def _set_status_msg(self, msg):
445         self.frame.GetStatusBar().SetStatusText(msg, 0)
446
447     def _build_gui(self, vbox):
448
449         def _form_set_freq(kv):
450             # Adjust current SETI frequency, and limits
451             self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
452             self.setifreq_current = kv['freq']
453             self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)
454
455             # Reset SETI analysis timer
456             self.seti_then = time.time()
457             # Zero-out hits array when changing frequency
458             self.hits_array[:,:] = 0.0
459             self.hit_intensities[:,:] = -60.0
460
461             return self.set_freq(kv['freq'])
462
463         def _form_set_decln(kv):
464             return self.set_decln(kv['decln'])
465
466         # Position the FFT display
467         vbox.Add(self.scope.win, 15, wx.EXPAND)
468
469         if self.setimode == False:
470             # Position the Total-power stripchart
471             vbox.Add(self.chart.win, 15, wx.EXPAND)
472         
473         # add control area at the bottom
474         self.myform = myform = form.form()
475         hbox = wx.BoxSizer(wx.HORIZONTAL)
476         hbox.Add((7,0), 0, wx.EXPAND)
477         vbox1 = wx.BoxSizer(wx.VERTICAL)
478         myform['freq'] = form.float_field(
479             parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
480             callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
481
482         vbox1.Add((4,0), 0, 0)
483
484         myform['lmst_high'] = form.static_text_field(
485             parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
486         vbox1.Add((4,0), 0, 0)
487
488         if self.setimode == False:
489             myform['spec_data'] = form.static_text_field(
490                 parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
491             vbox1.Add((4,0), 0, 0)
492
493         vbox2 = wx.BoxSizer(wx.VERTICAL)
494         if self.setimode == False:
495             vbox3 = wx.BoxSizer(wx.VERTICAL)
496         g = self.subdev.gain_range()
497         myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
498                                            weight=1,
499                                            min=int(g[0]), max=int(g[1]),
500                                            callback=self.set_gain)
501
502         vbox2.Add((4,0), 0, 0)
503         if self.setimode == True:
504             max_savg = 100
505         else:
506             max_savg = 3000
507         myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2, 
508                     label="Spectral Averaging (FFT frames)", weight=1, min=1, max=max_savg, callback=self.set_averaging)
509
510         # Set up scan control button when in SETI mode
511         if (self.setimode == True):
512                 # SETI scanning control
513                 buttonbox = wx.BoxSizer(wx.HORIZONTAL)
514                 self.scan_control = form.button_with_callback(self.panel,
515                       label="Scan: On ",
516                       callback=self.toggle_scanning)
517         
518                 buttonbox.Add(self.scan_control, 0, wx.CENTER)
519                 vbox2.Add(buttonbox, 0, wx.CENTER)
520
521         vbox2.Add((4,0), 0, 0)
522
523         if self.setimode == False:
524             myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
525                    label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)
526
527             vbox2.Add((4,0), 0, 0)
528
529         myform['decln'] = form.float_field(
530             parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
531             callback=myform.check_input_and_call(_form_set_decln))
532         vbox2.Add((4,0), 0, 0)
533
534         if self.setimode == False:
535             myform['offset'] = form.slider_field(parent=self.panel, sizer=vbox3,
536                 label="Post-Detector Offset", weight=1, min=-750, max=750, 
537                 callback=self.set_pd_offset)
538             vbox3.Add((2,0), 0, 0)
539             myform['dcgain'] = form.slider_field(parent=self.panel, sizer=vbox3,
540                 label="Post-Detector Gain", weight=1, min=1, max=100, 
541                 callback=self.set_pd_gain)
542             vbox3.Add((2,0), 0, 0)
543         hbox.Add(vbox1, 0, 0)
544         hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
545
546         if self.setimode == False:
547             hbox.Add(vbox3, wx.ALIGN_RIGHT, 0)
548
549         vbox.Add(hbox, 0, wx.EXPAND)
550
551         self._build_subpanel(vbox)
552
553         self.lmst_timer = wx.PyTimer(self.lmst_timeout)
554         #self.lmst_timeout()
555
556
557     def _build_subpanel(self, vbox_arg):
558         # build a secondary information panel (sometimes hidden)
559
560         # FIXME figure out how to have this be a subpanel that is always
561         # created, but has its visibility controlled by foo.Show(True/False)
562         
563         if not(self.show_debug_info):
564             return
565
566         panel = self.panel
567         vbox = vbox_arg
568         myform = self.myform
569
570         #panel = wx.Panel(self.panel, -1)
571         #vbox = wx.BoxSizer(wx.VERTICAL)
572
573         hbox = wx.BoxSizer(wx.HORIZONTAL)
574         hbox.Add((5,0), 0)
575         myform['decim'] = form.static_float_field(
576             parent=panel, sizer=hbox, label="Decim")
577
578         hbox.Add((5,0), 1)
579         myform['fs@usb'] = form.static_float_field(
580             parent=panel, sizer=hbox, label="Fs@USB")
581
582         hbox.Add((5,0), 1)
583         myform['dbname'] = form.static_text_field(
584             parent=panel, sizer=hbox)
585
586         hbox.Add((5,0), 1)
587         myform['baseband'] = form.static_float_field(
588             parent=panel, sizer=hbox, label="Analog BB")
589
590         hbox.Add((5,0), 1)
591         myform['ddc'] = form.static_float_field(
592             parent=panel, sizer=hbox, label="DDC")
593
594         hbox.Add((5,0), 0)
595         vbox.Add(hbox, 0, wx.EXPAND)
596
597         
598         
599     def set_freq(self, target_freq):
600         """
601         Set the center frequency we're interested in.
602
603         @param target_freq: frequency in Hz
604         @rypte: bool
605
606         Tuning is a two step process.  First we ask the front-end to
607         tune as close to the desired frequency as it can.  Then we use
608         the result of that operation and our target_frequency to
609         determine the value for the digital down converter.
610         """
611         #
612         # Everything except BASIC_RX should support usrp.tune()
613         #
614         if not (self.cardtype == usrp_dbid.BASIC_RX):
615             r = usrp.tune(self.u, 0, self.subdev, target_freq)
616         else:
617             r = self.u.set_rx_freq(0, target_freq)
618             f = self.u.rx_freq(0)
619             if abs(f-target_freq) > 2.0e3:
620                 r = 0
621         if r:
622             self.myform['freq'].set_value(target_freq)     # update displayed value
623             #
624             # Make sure calibrator knows our target freq
625             #
626
627             # Remember centerfreq---used for doppler calcs
628             delta = self.centerfreq - target_freq
629             self.centerfreq = target_freq
630             self.observing -= delta
631             self.scope.set_baseband_freq (self.observing)
632
633             self.myform['baseband'].set_value(r.baseband_freq)
634             self.myform['ddc'].set_value(r.dxc_freq)
635
636             if self.use_notches == True:
637                 self.compute_notch_taps(self.notches)
638                 self.notch_filt.set_taps(self.notch_taps)
639
640             return True
641
642         return False
643
644     def set_decln(self, dec):
645         self.decln = dec
646         self.myform['decln'].set_value(dec)     # update displayed value
647
648     def set_gain(self, gain):
649         self.myform['gain'].set_value(gain)     # update displayed value
650         self.subdev.set_gain(gain)
651         self.gain = gain
652
653     def set_averaging(self, avval):
654         self.myform['average'].set_value(avval)
655         self.scope.set_avg_alpha(1.0/(avval))
656         self.scope.set_average(True)
657         self.avg_alpha = avval
658
659     def set_integration(self, integval):
660         if self.setimode == False:
661             self.integrator3.set_taps(1.0/integval)
662         self.myform['integration'].set_value(integval)
663         self.integ = integval
664
665     #
666     # Timeout function
667     # Used to update LMST display, as well as current
668     #  continuum value
669     #
670     # We also write external data-logging files here
671     #
672     def lmst_timeout(self):
673          self.locality.date = ephem.now()
674          if self.setimode == False:
675              x = self.probe.level()
676          sidtime = self.locality.sidereal_time()
677          # LMST
678          s = str(ephem.hours(sidtime)) + " " + self.sunstate
679          # Continuum detector value
680          if self.setimode == False:
681              sx = "%7.4f" % x
682              s = s + "\nDet: " + str(sx)
683          else:
684              sx = "%2d" % self.hitcounter
685              s1 = "%2d" % self.s1hitcounter
686              s2 = "%2d" % self.s2hitcounter
687              sa = "%4.2f" % self.avgdelta
688              sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
689              s = s + "\nHits: " + str(sx) + "\nS1:" + str(s1) + " S2:" + str(s2)
690              s = s + "\nAv D: " + str(sa) + "\nCh lim: " + str(sy)
691
692          self.myform['lmst_high'].set_value(s)
693
694          #
695          # Write data out to recording files
696          #
697          if self.setimode == False:
698              self.write_continuum_data(x,sidtime)
699              self.write_spectral_data(self.fft_outbuf,sidtime)
700
701          else:
702              self.seti_analysis(self.fft_outbuf,sidtime)
703              now = time.time()
704              if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
705                  self.seti_then = now
706                  self.setifreq_current = self.setifreq_current + self.fft_input_rate
707                  if (self.setifreq_current > self.setifreq_upper):
708                      self.setifreq_current = self.setifreq_lower
709                  self.set_freq(self.setifreq_current)
710                  # Make sure we zero-out the hits array when changing
711                  #   frequency.
712                  self.hits_array[:,:] = 0.0
713                  self.hit_intensities[:,:] = 0.0
714
715     def fft_outfunc(self,data,l):
716         self.fft_outbuf=data
717
718     def write_continuum_data(self,data,sidtime):
719     
720         # Create localtime structure for producing filename
721         foo = time.localtime()
722         pfx = self.prefix
723         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
724            foo.tm_mon, foo.tm_mday, foo.tm_hour)
725     
726         # Open the data file, appending
727         continuum_file = open (filenamestr+".tpdat","a")
728       
729         flt = "%6.3f" % data
730         inter = self.decln
731         integ = self.integ
732         fc = self.observing
733         fc = fc / 1000000
734         bw = self.bw
735         bw = bw / 1000000
736         ga = self.gain
737     
738         now = time.time()
739     
740         #
741         # If time to write full header info (saves storage this way)
742         #
743         if (now - self.continuum_then > 20):
744             self.sun.compute(self.locality)
745             enow = ephem.now()
746             sun_insky = "Down"
747             self.sunstate = "Dn"
748             if ((self.sun.rise_time < enow) and (enow < self.sun.set_time)):
749                sun_insky = "Up"
750                self.sunstate = "Up"
751             self.continuum_then = now
752         
753             continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
754             continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
755             continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
756         else:
757             continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
758     
759         continuum_file.close()
760         return(data)
761
762     def write_spectral_data(self,data,sidtime):
763     
764         now = time.time()
765         delta = 10
766                 
767         # If time to write out spectral data
768         # We don't write this out every time, in order to
769         #   save disk space.  Since the spectral data are
770         #   typically heavily averaged, writing this data
771         #   "once in a while" is OK.
772         #
773         if (now - self.spectral_then >= delta):
774             self.spectral_then = now
775
776             # Get localtime structure to make filename from
777             foo = time.localtime()
778         
779             pfx = self.prefix
780             filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
781                foo.tm_mon, foo.tm_mday, foo.tm_hour)
782     
783             # Open the file
784             spectral_file = open (filenamestr+".sdat","a")
785       
786             # Setup data fields to be written
787             r = data
788             inter = self.decln
789             fc = self.observing
790             fc = fc / 1000000
791             bw = self.bw
792             bw = bw / 1000000
793             av = self.avg_alpha
794
795             # Write those fields
796             spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
797             spectral_file.write (" [ ")
798             for r in data:
799                 spectral_file.write(" "+str(r))
800
801             spectral_file.write(" ]\n")
802             spectral_file.close()
803             return(data)
804     
805         return(data)
806
807     def seti_analysis(self,fftbuf,sidtime):
808         l = len(fftbuf)
809         x = 0
810         hits = []
811         hit_intensities = []
812         if self.seticounter < self.setitimer:
813             self.seticounter = self.seticounter + 1
814             return
815         else:
816             self.seticounter = 0
817
818         # Run through FFT output buffer, computing standard deviation (Sigma)
819         avg = 0
820         # First compute average
821         for i in range(0,l):
822             avg = avg + fftbuf[i]
823         avg = avg / l
824
825         sigma = 0.0
826         # Then compute standard deviation (Sigma)
827         for i in range(0,l):
828             d = fftbuf[i] - avg
829             sigma = sigma + (d*d)
830
831         sigma = Numeric.sqrt(sigma/l)
832
833         #
834         # Snarfle through the FFT output buffer again, looking for
835         #    outlying data points
836
837         start_f = self.observing - (self.fft_input_rate/2)
838         current_f = start_f
839         l = len(fftbuf)
840         f_incr = self.fft_input_rate / l
841         hit = -1
842
843         # -nyquist to DC
844         for i in range(l/2,l):
845             #
846             # If current FFT buffer has an item that exceeds the specified
847             #  sigma
848             #
849             if ((fftbuf[i] - avg) > (self.setik * sigma)):
850                 hits.append(current_f)
851                 hit_intensities.append(fftbuf[i])
852             current_f = current_f + f_incr
853
854         # DC to nyquist
855         for i in range(0,l/2):
856             #
857             # If current FFT buffer has an item that exceeds the specified
858             #  sigma
859             #
860             if ((fftbuf[i] - avg) > (self.setik * sigma)):
861                 hits.append(current_f)
862                 hit_intensities.append(fftbuf[i])
863             current_f = current_f + f_incr
864
865         # No hits
866         if (len(hits) <= 0):
867             return
868
869
870         #
871         # OK, so we have some hits in the FFT buffer
872         #   They'll have a rather substantial gauntlet to run before
873         #   being declared a real "hit"
874         #
875
876         # Update stats
877         self.s1hitcounter = self.s1hitcounter + len(hits)
878
879         # Weed out buffers with an excessive number of
880         #   signals above Sigma
881         if (len(hits) > self.nhits):
882             return
883
884
885         # Weed out FFT buffers with apparent multiple narrowband signals
886         #   separated significantly in frequency.  This means that a
887         #   single signal spanning multiple bins is OK, but a buffer that
888         #   has multiple, apparently-separate, signals isn't OK.
889         #
890         last = hits[0]
891         ns2 = 1
892         for i in range(1,len(hits)):
893             if ((hits[i] - last) > (f_incr*3.0)):
894                 return
895             last = hits[i]
896             ns2 = ns2 + 1
897
898         self.s2hitcounter = self.s2hitcounter + ns2
899
900         #
901         # Run through all available hit buffers, computing difference between
902         #   frequencies found there, if they're all within the chirp limits
903         #   declare a good hit
904         #
905         good_hit = False
906         f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
907         avg_delta = 0
908         k = 0
909         for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
910             f_ds[0] = abs(self.hits_array[i,0] - hits[i])
911             for j in range(1,len(f_ds)):
912                f_ds[j] = abs(self.hits_array[i,j] - self.hits_array[i,0])
913                avg_delta = avg_delta + f_ds[j]
914                k = k + 1
915
916             if (self.seti_isahit (f_ds)):
917                 good_hit = True
918                 self.hitcounter = self.hitcounter + 1
919                 break
920
921         if (avg_delta/k < (self.seti_fft_bandwidth/2)):
922             self.avgdelta = avg_delta / k
923
924         # Save 'n shuffle hits
925         #  Old hit buffers percolate through the hit buffers
926         #  (there are self.nhitlines of these buffers)
927         #  and then drop off the end
928         #  A consequence is that while the nhitlines buffers are filling,
929         #  you can get some absurd values for self.avgdelta, because some
930         #  of the buffers are full of zeros
931         for i in range(self.nhitlines,1):
932             self.hits_array[:,i] = self.hits_array[:,i-1]
933             self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
934
935         for i in range(0,len(hits)):
936             self.hits_array[i,0] = hits[i]
937             self.hit_intensities[i,0] = hit_intensities[i]
938
939         # Finally, write the hits/intensities buffer
940         if (good_hit):
941             self.write_hits(sidtime)
942
943         return
944
945     def seti_isahit(self,fdiffs):
946         truecount = 0
947
948         for i in range(0,len(fdiffs)):
949             if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
950                 truecount = truecount + 1
951
952         if truecount == len(fdiffs):
953             return (True)
954         else:
955             return (False)
956
957     def write_hits(self,sidtime):
958         # Create localtime structure for producing filename
959         foo = time.localtime()
960         pfx = self.prefix
961         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
962            foo.tm_mon, foo.tm_mday, foo.tm_hour)
963     
964         # Open the data file, appending
965         hits_file = open (filenamestr+".seti","a")
966
967         # Write sidtime first
968         hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
969
970         #
971         # Then write the hits/hit intensities buffers with enough
972         #   "syntax" to allow parsing by external (not yet written!)
973         #   "stuff".
974         #
975         for i in range(0,self.nhitlines):
976             hits_file.write(" ")
977             for j in range(0,self.nhits):
978                 hits_file.write(str(self.hits_array[j,i])+":")
979                 hits_file.write(str(self.hit_intensities[j,i])+",")
980         hits_file.write("\n")
981         hits_file.close()
982         return
983
984     def xydfunc(self,xyv):
985         if self.setimode == True:
986             return
987         magn = int(Numeric.log10(self.observing))
988         if (magn == 6 or magn == 7 or magn == 8):
989             magn = 6
990         dfreq = xyv[0] * pow(10.0,magn)
991         ratio = self.observing / dfreq
992         vs = 1.0 - ratio
993         vs *= 299792.0
994         if magn >= 9:
995            xhz = "Ghz"
996         elif magn >= 6:
997            xhz = "Mhz"
998         elif magn <= 5:
999            xhz =  "Khz"
1000         s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
1001         s2 = "\n%.3fkm/s" % vs
1002         self.myform['spec_data'].set_value(s+s2)
1003
1004     def xydfunc_waterfall(self,pos):
1005         lower = self.observing - (self.seti_fft_bandwidth / 2)
1006         upper = self.observing + (self.seti_fft_bandwidth / 2)
1007         binwidth = self.seti_fft_bandwidth / 1024
1008         s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
1009         self.myform['spec_data'].set_value(s)
1010
1011     def toggle_cal(self):
1012         if (self.calstate == True):
1013           self.calstate = False
1014           self.u.write_io(0,0,(1<<15))
1015           self.calibrator.SetLabel("Calibration Source: Off")
1016         else:
1017           self.calstate = True
1018           self.u.write_io(0,(1<<15),(1<<15))
1019           self.calibrator.SetLabel("Calibration Source: On")
1020
1021     def toggle_annotation(self):
1022         if (self.annotate_state == True):
1023           self.annotate_state = False
1024           self.annotation.SetLabel("Annotation: Off")
1025         else:
1026           self.annotate_state = True
1027           self.annotation.SetLabel("Annotation: On")
1028     #
1029     # Turn scanning on/off
1030     # Called-back by "Recording" button
1031     #
1032     def toggle_scanning(self):
1033         # Current scanning?  Flip state
1034         if (self.scanning == True):
1035           self.scanning = False
1036           self.scan_control.SetLabel("Scan: Off")
1037         # Not scanning
1038         else:
1039           self.scanning = True
1040           self.scan_control.SetLabel("Scan: On ")
1041
1042     def set_pd_offset(self,offs):
1043          self.myform['offset'].set_value(offs)
1044          self.calib_offset=offs
1045          x = self.calib_coeff / 100.0
1046          self.cal_offs.set_k(offs*(x*8000))
1047
1048     def set_pd_gain(self,gain):
1049          self.myform['dcgain'].set_value(gain)
1050          self.cal_mult.set_k(gain*0.01)
1051          self.calib_coeff = gain
1052          x = gain/100.0
1053          self.cal_offs.set_k(self.calib_offset*(x*8000))
1054
1055     def compute_notch_taps(self,notchlist):
1056          NOTCH_TAPS = 256
1057          tmptaps = Numeric.zeros(NOTCH_TAPS,Numeric.Complex64)
1058          binwidth = self.bw / NOTCH_TAPS
1059  
1060          for i in range(0,NOTCH_TAPS):
1061              tmptaps[i] = complex(1.0,0.0)
1062  
1063          for i in notchlist:
1064              diff = i - self.observing
1065              if i == 0:
1066                  break
1067              if (diff > 0):
1068                  idx = diff / binwidth
1069                  idx = int(idx)
1070                  if (idx < 0 or idx > (NOTCH_TAPS/2)):
1071                      break
1072                  tmptaps[idx] = complex(0.0, 0.0)
1073
1074              if (diff < 0):
1075                  idx = -diff / binwidth
1076                  idx = (NOTCH_TAPS/2) - idx
1077                  idx = int(idx+(NOTCH_TAPS/2))
1078                  if (idx < 0 or idx > (NOTCH_TAPS)):
1079                      break
1080                  tmptaps[idx] = complex(0.0, 0.0)
1081
1082          self.notch_taps = FFT.inverse_fft(tmptaps)
1083
1084 def main ():
1085     app = stdgui.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1086     app.MainLoop()
1087
1088 if __name__ == '__main__':
1089     main ()