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