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