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