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