summaryrefslogtreecommitdiff
path: root/gr-radio-astronomy/src/python/usrp_ra_receiver.py
blob: 5e63933c2860ac9cb81c51580af64e530abc8f27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
#!/usr/bin/env python
#
# Copyright 2004,2005 Free Software Foundation, Inc.
# 
# This file is part of GNU Radio
# 
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# 
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
# 

from gnuradio import gr, gru
from gnuradio import usrp
import usrp_dbid
from gnuradio import eng_notation
from gnuradio.eng_option import eng_option
from gnuradio.wxgui import stdgui, ra_fftsink, ra_stripchartsink, ra_waterfallsink, form, slider
from optparse import OptionParser
import wx
import sys
import Numeric 
import time
import FFT
import ephem

class continuum_calibration(gr.feval_dd):
    def eval(self, x):
        str = globals()["calibration_codelet"]
        exec(str)
        return(x)

class app_flow_graph(stdgui.gui_flow_graph):
    def __init__(self, frame, panel, vbox, argv):
        stdgui.gui_flow_graph.__init__(self)

        self.frame = frame
        self.panel = panel
        
        parser = OptionParser(option_class=eng_option)
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0, 0),
                          help="select USRP Rx side A or B (default=A)")
        parser.add_option("-d", "--decim", type="int", default=16,
                          help="set fgpa decimation rate to DECIM [default=%default]")
        parser.add_option("-f", "--freq", type="eng_float", default=None,
                          help="set frequency to FREQ", metavar="FREQ")
	parser.add_option("-a", "--avg", type="eng_float", default=1.0,
		help="set spectral averaging alpha")
	parser.add_option("-i", "--integ", type="eng_float", default=1.0,
		help="set integration time")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("-l", "--reflevel", type="eng_float", default=30.0,
                          help="Set Total power reference level")
        parser.add_option("-y", "--division", type="eng_float", default=0.5,
                          help="Set Total power Y division size")
        parser.add_option("-e", "--longitude", type="eng_float", default=-76.02,                          help="Set Observer Longitude")
        parser.add_option("-c", "--latitude", type="eng_float", default=44.85,                          help="Set Observer Latitude")
        parser.add_option("-o", "--observing", type="eng_float", default=0.0,
                        help="Set observing frequency")
        parser.add_option("-x", "--ylabel", default="dB", help="Y axis label") 
        parser.add_option("-z", "--divbase", type="eng_float", default=0.025, help="Y Division increment base") 
        parser.add_option("-v", "--stripsize", type="eng_float", default=2400, help="Size of stripchart, in 2Hz samples") 
        parser.add_option("-F", "--fft_size", type="eng_float", default=1024, help="Size of FFT")

        parser.add_option("-N", "--decln", type="eng_float", default=999.99, help="Observing declination")
        parser.add_option("-X", "--prefix", default="./")
        parser.add_option("-M", "--fft_rate", type="eng_float", default=8.0, help="FFT Rate")
        parser.add_option("-A", "--calib_coeff", type="eng_float", default=1.0, help="Calibration coefficient")
        parser.add_option("-B", "--calib_offset", type="eng_float", default=0.0, help="Calibration coefficient")
        parser.add_option("-W", "--waterfall", action="store_true", default=False, help="Use Waterfall FFT display")
        parser.add_option("-S", "--setimode", action="store_true", default=False, help="Enable SETI processing of spectral data")
        parser.add_option("-K", "--setik", type="eng_float", default=1.5, help="K value for SETI analysis")
        (options, args) = parser.parse_args()
        if len(args) != 0:
            parser.print_help()
            sys.exit(1)

        self.show_debug_info = True

        # Pick up waterfall option
        self.waterfall = options.waterfall

        # SETI mode stuff
        self.setimode = options.setimode
        self.seticounter = 0
        self.setik = options.setik
        # Because we force the input rate to be 250Khz, 12.5Khz is
        #  exactly 1/20th of this, which makes building decimators
        #  easier.
        # This also allows larger FFTs to be used without totally-gobbling
        #  CPU.  With an FFT size of 16384, for example, this bandwidth
        #  yields a binwidth of 0.762Hz, and plenty of CPU left over
        #  for other things, like the SETI analysis code.
        #
        self.seti_fft_bandwidth = 12500

        # Calculate binwidth
        binwidth = self.seti_fft_bandwidth / options.fft_size

        # Use binwidth, and knowledge of likely chirp rates to set reasonable
        #  values for SETI analysis code.   We assume that SETI signals will
        #  chirp at somewhere between 0.10Hz/sec and 0.25Hz/sec.
        #
        # upper_limit is the "worst case"--that is, the case for which we have
        #  wait the longest to actually see any drift, due to the quantizing
        #  on FFT bins.
        upper_limit = binwidth / 0.10
        self.setitimer = int(upper_limit * 2.00)

        # Calculate the CHIRP values based on Hz/sec
        self.CHIRP_LOWER = 0.10 * self.setitimer
        self.CHIRP_UPPER = 0.25 * self.setitimer

        # Reset hit counter to 0
        self.hitcounter = 0
        # We scan through 1Mhz of bandwidth around the chosen center freq
        self.seti_freq_range = 1.0e6
        # Calculate lower edge
        self.setifreq_lower = options.freq - (self.seti_freq_range/2)
        self.setifreq_current = options.freq
        # Calculate upper edge
        self.setifreq_upper = options.freq + (self.seti_freq_range/2)

        # We change center frequencies every 10 self.setitimer intervals
        self.setifreq_timer = self.setitimer * 10

        # Create actual timer
        self.seti_then = time.time()

        # The hits recording array
        self.nhits = 10
        self.hits_array = Numeric.zeros((self.nhits,3), Numeric.Float64)

        # Calibration coefficient and offset
        self.calib_coeff = options.calib_coeff
        self.calib_offset = options.calib_offset

        self.integ = options.integ
        self.avg_alpha = options.avg
        self.gain = options.gain
        self.decln = options.decln

        # Set initial values for datalogging timed-output
        self.continuum_then = time.time()
        self.spectral_then = time.time()
      
        # build the graph

        #
        # If SETI mode, we always run at maximum USRP decimation
        #
        if (self.setimode):
            options.decim = 256

        self.u = usrp.source_c(decim_rate=options.decim)
        self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
        self.cardtype = self.u.daughterboard_id(0)
        # Set initial declination
        self.decln = options.decln

        # determine the daughterboard subdevice we're using
        self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)

        input_rate = self.u.adc_freq() / self.u.decim_rate()

        #
        # Set prefix for data files
        #
        self.prefix = options.prefix

        #
        # The lower this number, the fewer sample frames are dropped
        #  in computing the FFT.  A sampled approach is taken to
        #  computing the FFT of the incoming data, which reduces
        #  sensitivity.  Increasing sensitivity inreases CPU loading.
        #
        self.fft_rate = options.fft_rate

        self.fft_size = options.fft_size

        # This buffer is used to remember the most-recent FFT display
        #   values.  Used later by self.write_spectral_data() to write
        #   spectral data to datalogging files, and by the SETI analysis
        #   function.
        #
        self.fft_outbuf = Numeric.zeros(options.fft_size, Numeric.Float64)

        #
        # If SETI mode, only look at seti_fft_bandwidth (currently 12.5Khz)
        #   at a time.
        #
        if (self.setimode):
            self.fft_input_rate = self.seti_fft_bandwidth

            #
            # Build a decimating bandpass filter
            #
            self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
               input_rate,
               -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
               gr.firdes.WIN_HAMMING, 0)

            #
            # Compute required decimation factor
            #
            decimation = int(input_rate/self.fft_input_rate)
            self.fft_bandpass = gr.fir_filter_ccc (decimation, 
                self.fft_input_taps)
        else:
            self.fft_input_rate = input_rate

        # Set up FFT display
        if self.waterfall == False:
           self.scope = ra_fftsink.ra_fft_sink_c (self, panel, 
               fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
               fft_rate=int(self.fft_rate), title="Spectral",  
               ofunc=self.fft_outfunc, xydfunc=self.xydfunc)
        else:
            self.scope = ra_waterfallsink.ra_waterfallsink_c (self, panel,
                fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
                fft_rate=int(self.fft_rate), title="Spectral", ofunc=self.fft_outfunc, xydfunc=self.xydfunc)

        # Set up ephemeris data
        self.locality = ephem.Observer()
        self.locality.long = str(options.longitude)
        self.locality.lat = str(options.latitude)

        # Set up stripchart display
        self.stripsize = int(options.stripsize)
        self.chart = ra_stripchartsink.stripchart_sink_f (self, panel,
            stripsize=self.stripsize,
            title="Continuum",
            xlabel="LMST Offset (Seconds)",
            scaling=1.0, ylabel=options.ylabel,
            divbase=options.divbase)

        # Set center frequency
        self.centerfreq = options.freq

        # Set observing frequency (might be different from actual programmed
        #    RF frequency)
        if options.observing == 0.0:
            self.observing = options.freq
        else:
            self.observing = options.observing

        self.bw = input_rate

        # We setup the first two integrators to produce a fixed integration
        # Down to 1Hz, with output at 1 samples/sec
        N = input_rate/5000

        # Second stage runs on decimated output of first
        M = (input_rate/N)

        # Create taps for first integrator
        t = range(0,N-1)
        tapsN = []
        for i in t:
             tapsN.append(1.0/N)

        # Create taps for second integrator
        t = range(0,M-1)
        tapsM = []
        for i in t:
            tapsM.append(1.0/M)

        #
        # The 3rd integrator is variable, and user selectable at runtime
        # This integrator doesn't decimate, but is used to set the
        #  final integration time based on the constant 1Hz input samples
        # The strip chart is fed at a constant 1Hz rate as a result
        #

        #
        # Call constructors for receive chains
        #

        # The three integrators--two FIR filters, and an IIR final filter
        self.integrator1 = gr.fir_filter_fff (N, tapsN)
        self.integrator2 = gr.fir_filter_fff (M, tapsM)
        self.integrator3 = gr.single_pole_iir_filter_ff(1.0)

        # Split complex USRP stream into a pair of floats
        self.splitter = gr.complex_to_float (1);

        # I squarer (detector)
        self.multI = gr.multiply_ff();

        # Q squarer (detector)
        self.multQ = gr.multiply_ff();

        # Adding squared I and Q to produce instantaneous signal power
        self.adder = gr.add_ff();

        # Signal probe
        self.probe = gr.probe_signal_f();

        #
        # Continuum calibration stuff
        #
        self.cal_mult = gr.multiply_const_ff(self.calib_coeff);
        self.cal_offs = gr.add_const_ff(self.calib_offset);

        #self.cal_eqn = continuum_calibration();

        #
        # Start connecting configured modules in the receive chain
        #

        # The scope--handle SETI mode
        if (self.setimode == False):
            self.connect(self.u, self.scope)
        else:
            self.connect(self.u, self.fft_bandpass, self.scope)

        #
        # The head of the continuum chain
        #
        self.connect(self.u, self.splitter)

        # Connect splitter outputs to multipliers
        # First do I^2
        self.connect((self.splitter, 0), (self.multI,0))
        self.connect((self.splitter, 0), (self.multI,1))

        # Then do Q^2
        self.connect((self.splitter, 1), (self.multQ,0))
        self.connect((self.splitter, 1), (self.multQ,1))

        # Then sum the squares
        self.connect(self.multI, (self.adder,0))
        self.connect(self.multQ, (self.adder,1))

        # Connect adder output to two-stages of FIR integrator
        #   followed by a single stage IIR integrator, and
        #   the calibrator
        self.connect(self.adder, self.integrator1, 
           self.integrator2, self.integrator3, self.cal_mult, 
           self.cal_offs, self.chart)

        # Connect calibrator to probe
        # SPECIAL NOTE:  I'm setting the ground work here
        #   for completely changing the way local_calibrator
        #   works, including removing some horrible kludges for
        #   recording data.
        # But for now, self.probe() will be used to display the
        #  current instantaneous integrated detector value
        self.connect(self.cal_offs, self.probe)

        self._build_gui(vbox)

        # Make GUI agree with command-line
        self.integ = options.integ
        self.myform['integration'].set_value(int(options.integ))
        self.myform['average'].set_value(int(options.avg))

        # Make integrator agree with command line
        self.set_integration(int(options.integ))

        self.avg_alpha = options.avg

        # Make spectral averager agree with command line
        if options.avg != 1.0:
            self.scope.set_avg_alpha(float(1.0/options.avg))
            self.scope.set_average(True)

        # Set division size
        self.chart.set_y_per_div(options.division)

        # Set reference(MAX) level
        self.chart.set_ref_level(options.reflevel)

        # set initial values

        if options.gain is None:
            # if no gain was specified, use the mid-point in dB
            g = self.subdev.gain_range()
            options.gain = float(g[0]+g[1])/2

        if options.freq is None:
            # if no freq was specified, use the mid-point
            r = self.subdev.freq_range()
            options.freq = float(r[0]+r[1])/2

        # Set the initial gain control
        self.set_gain(options.gain)

        if not(self.set_freq(options.freq)):
            self._set_status_msg("Failed to set initial frequency")

        # Set declination
        self.set_decln (self.decln)


        # RF hardware information
        self.myform['decim'].set_value(self.u.decim_rate())
        self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
        self.myform['dbname'].set_value(self.subdev.name())

        # Set analog baseband filtering, if DBS_RX
        if self.cardtype == usrp_dbid.DBS_RX:
            lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
            if lbw < 1.0e6:
                lbw = 1.0e6
            self.subdev.set_bw(lbw)

        # Start the timer for the LMST display and datalogging
        self.lmst_timer.Start(1000)


    def _set_status_msg(self, msg):
        self.frame.GetStatusBar().SetStatusText(msg, 0)

    def _build_gui(self, vbox):

        def _form_set_freq(kv):
            # Adjust current SETI frequency, and limits
            self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
            self.setifreq_current = kv['freq']
            self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)

            # Reset SETI analysis timer
            self.seti_then = time.time()
            # Zero-out hits array when changing frequency
            self.hits_array[:,:] = 0.0

            return self.set_freq(kv['freq'])

        def _form_set_decln(kv):
            return self.set_decln(kv['decln'])

        # Position the FFT display
        vbox.Add(self.scope.win, 15, wx.EXPAND)

        # Position the Total-power stripchart
        vbox.Add(self.chart.win, 15, wx.EXPAND)
        
        # add control area at the bottom
        self.myform = myform = form.form()
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add((7,0), 0, wx.EXPAND)
        vbox1 = wx.BoxSizer(wx.VERTICAL)
        myform['freq'] = form.float_field(
            parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
            callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))

        vbox1.Add((4,0), 0, 0)

        myform['lmst_high'] = form.static_text_field(
            parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
        vbox1.Add((4,0), 0, 0)

        myform['spec_data'] = form.static_text_field(
            parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
        vbox1.Add((4,0), 0, 0)

        vbox2 = wx.BoxSizer(wx.VERTICAL)
        g = self.subdev.gain_range()
        myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
                                           weight=1,
                                           min=int(g[0]), max=int(g[1]),
                                           callback=self.set_gain)

        vbox2.Add((4,0), 0, 0)
        myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2, 
                    label="Spectral Averaging (FFT frames)", weight=1, min=1, max=2000, callback=self.set_averaging)

        vbox2.Add((4,0), 0, 0)

        myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
               label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)

        vbox2.Add((4,0), 0, 0)
        myform['decln'] = form.float_field(
            parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
            callback=myform.check_input_and_call(_form_set_decln))
        vbox2.Add((4,0), 0, 0)

        buttonbox = wx.BoxSizer(wx.HORIZONTAL)
        vbox.Add(buttonbox, 0, wx.CENTER)
        hbox.Add(vbox1, 0, 0)
	hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
        vbox.Add(hbox, 0, wx.EXPAND)

        self._build_subpanel(vbox)

        self.lmst_timer = wx.PyTimer(self.lmst_timeout)
        #self.lmst_timeout()


    def _build_subpanel(self, vbox_arg):
        # build a secondary information panel (sometimes hidden)

        # FIXME figure out how to have this be a subpanel that is always
        # created, but has its visibility controlled by foo.Show(True/False)
        
        if not(self.show_debug_info):
            return

        panel = self.panel
        vbox = vbox_arg
        myform = self.myform

        #panel = wx.Panel(self.panel, -1)
        #vbox = wx.BoxSizer(wx.VERTICAL)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add((5,0), 0)
        myform['decim'] = form.static_float_field(
            parent=panel, sizer=hbox, label="Decim")

        hbox.Add((5,0), 1)
        myform['fs@usb'] = form.static_float_field(
            parent=panel, sizer=hbox, label="Fs@USB")

        hbox.Add((5,0), 1)
        myform['dbname'] = form.static_text_field(
            parent=panel, sizer=hbox)

        hbox.Add((5,0), 1)
        myform['baseband'] = form.static_float_field(
            parent=panel, sizer=hbox, label="Analog BB")

        hbox.Add((5,0), 1)
        myform['ddc'] = form.static_float_field(
            parent=panel, sizer=hbox, label="DDC")

        hbox.Add((5,0), 0)
        vbox.Add(hbox, 0, wx.EXPAND)

        
        
    def set_freq(self, target_freq):
        """
        Set the center frequency we're interested in.

        @param target_freq: frequency in Hz
        @rypte: bool

        Tuning is a two step process.  First we ask the front-end to
        tune as close to the desired frequency as it can.  Then we use
        the result of that operation and our target_frequency to
        determine the value for the digital down converter.
        """
        #
        # Everything except BASIC_RX should support usrp.tune()
        #
        if not (self.cardtype == usrp_dbid.BASIC_RX):
            r = usrp.tune(self.u, 0, self.subdev, target_freq)
        else:
            r = self.u.set_rx_freq(0, target_freq)
            f = self.u.rx_freq(0)
            if abs(f-target_freq) > 2.0e3:
                r = 0
        if r:
            self.myform['freq'].set_value(target_freq)     # update displayed value
            #
            # Make sure calibrator knows our target freq
            #

            # Remember centerfreq---used for doppler calcs
            delta = self.centerfreq - target_freq
            self.centerfreq = target_freq
            self.observing -= delta
            self.scope.set_baseband_freq (self.observing)

            self.myform['baseband'].set_value(r.baseband_freq)
            self.myform['ddc'].set_value(r.dxc_freq)

            return True

        return False

    def set_decln(self, dec):
        self.decln = dec
        self.myform['decln'].set_value(dec)     # update displayed value

    def set_gain(self, gain):
        self.myform['gain'].set_value(gain)     # update displayed value
        self.subdev.set_gain(gain)
        self.gain = gain

    def set_averaging(self, avval):
        self.myform['average'].set_value(avval)
        self.scope.set_avg_alpha(1.0/(avval))
        self.scope.set_average(True)
        self.avg_alpha = avval

    def set_integration(self, integval):
        self.integrator3.set_taps(1.0/integval)
        self.myform['integration'].set_value(integval)
        self.integ = integval

    #
    # Timeout function
    # Used to update LMST display, as well as current
    #  continuum value
    #
    # We also write external data-logging files here
    #
    def lmst_timeout(self):
         self.locality.date = ephem.now()
         x = self.probe.level()
         sidtime = self.locality.sidereal_time()
         # LMST
         s = str(ephem.hours(sidtime))
         # Continuum detector value
         sx = "%7.4f" % x
         s = s + "\nDet: " + str(sx)
         sx = "%2d" % self.hitcounter
         sy = "%3.1f/%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
         s = s + "\nH: " + str(sx) + " C: " + str(sy)
         self.myform['lmst_high'].set_value(s)

         #
         # Write data out to recording files
         #
         if self.setimode == False:
             self.write_continuum_data(x,sidtime)
             self.write_spectral_data(self.fft_outbuf,sidtime)

         if self.setimode == True:
             self.seti_analysis(self.fft_outbuf,sidtime)
             now = time.time()
             if ((now - self.seti_then) > self.setifreq_timer):
                 self.seti_then = now
                 self.setifreq_current = self.setifreq_current + self.fft_input_rate
                 if (self.setifreq_current > self.setifreq_upper):
                     self.setifreq_current = self.setifreq_lower
                 self.set_freq(self.setifreq_current)
                 # Make sure we zero-out the hits array when changing
                 #   frequency.
                 self.hits_array[:,:] = 0.0

    def fft_outfunc(self,data,l):
        self.fft_outbuf=data

    def write_continuum_data(self,data,sidtime):
    
        # Create localtime structure for producing filename
        foo = time.localtime()
        pfx = self.prefix
        filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
           foo.tm_mon, foo.tm_mday, foo.tm_hour)
    
        # Open the data file, appending
        continuum_file = open (filenamestr+".tpdat","a")
      
        flt = "%6.3f" % data
        inter = self.decln
        integ = self.integ
        fc = self.observing
        fc = fc / 1000000
        bw = self.bw
        bw = bw / 1000000
        ga = self.gain
    
        now = time.time()
    
        #
        # If time to write full header info (saves storage this way)
        #
        if (now - self.continuum_then > 20):
            self.continuum_then = now
        
            continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
            continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
            continuum_file.write(",Ga="+str(ga)+"\n")
        else:
            continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
    
        continuum_file.close()
        return(data)

    def write_spectral_data(self,data,sidtime):
    
        now = time.time()
        delta = 10
    		
        # If time to write out spectral data
        # We don't write this out every time, in order to
        #   save disk space.  Since the spectral data are
        #   typically heavily averaged, writing this data
        #   "once in a while" is OK.
        #
        if (now - self.spectral_then >= delta):
            self.spectral_then = now

            # Get localtime structure to make filename from
            foo = time.localtime()
        
            pfx = self.prefix
            filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
               foo.tm_mon, foo.tm_mday, foo.tm_hour)
    
            # Open the file
            spectral_file = open (filenamestr+".sdat","a")
      
            # Setup data fields to be written
            r = data
            inter = self.decln
            fc = self.observing
            fc = fc / 1000000
            bw = self.bw
            bw = bw / 1000000
            av = self.avg_alpha

            # Write those fields
            spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
            spectral_file.write(" "+str(r)+"\n")
            spectral_file.close()
            return(data)
    
        return(data)

    def seti_analysis(self,fftbuf,sidtime):
        l = len(fftbuf)
        x = 0
        hits = []
        if self.seticounter < self.setitimer:
            self.seticounter = self.seticounter + 1
            return
        else:
            self.seticounter = 0

        # Run through FFT output buffer, computing standard deviation (Sigma)
        avg = 0
        # First compute average
        for i in range(0,l):
            avg = avg + fftbuf[i]
        avg = avg / l

        sigma = 0.0
        # Then compute standard deviation (Sigma)
        for i in range(0,l):
            d = fftbuf[i] - avg
            sigma = sigma + (d*d)

        sigma = Numeric.sqrt(sigma/l)

        #
        # Snarfle through the FFT output buffer again, looking for
        #    outlying data points

        start_f = self.observing - (self.fft_input_rate/2)
        current_f = start_f
        f_incr = self.fft_input_rate / l
        l = len(fftbuf)
        hit = -1

        # -nyquist to DC
        for i in range(l/2,l):
            #
            # If current FFT buffer has an item that exceeds the specified
            #  sigma
            #
            if ((fftbuf[i] - avg) > (self.setik * sigma)):
                hits.append(current_f)
            current_f = current_f + f_incr

        # DC to nyquist
        for i in range(0,l/2):
            #
            # If current FFT buffer has an item that exceeds the specified
            #  sigma
            #
            if ((fftbuf[i] - avg) > (self.setik * sigma)):
                hits.append(current_f)
            current_f = current_f + f_incr

        if (len(hits) <= 0):
            return

        if (len(hits) > self.nhits):
            return


        #
        # Run through all three hit buffers, computing difference between
        #   frequencies found there, if they're all within the chirp limits
        #   declare a good hit
        #
        good_hit = 0
        good_hit = False
        for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
            f_d1 = abs(self.hits_array[i,0] - hits[i])
            f_d2 = abs(self.hits_array[i,1] - self.hits_array[i,0])
            f_d3 = abs(self.hits_array[i,2] - self.hits_array[i,1])
            if (self.seti_isahit ([f_d1, f_d2, f_d3])):
                good_hit = True
                self.hitcounter = self.hitcounter + 1
                break

        if (good_hit):
            self.write_hits(hits,sidtime)

        # Save 'n shuffle hits
        self.hits_array[:,2] = self.hits_array[:,1]
        self.hits_array[:,1] = self.hits_array[:,0]

        for i in range(0,len(hits)):
            self.hits_array[i,0] = hits[i]

        return

    def seti_isahit(self,fdiffs):
        truecount = 0

        for i in range(0,len(fdiffs)):
            if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
                truecount = truecount + 1

        if truecount == len(fdiffs):
            return (True)
        else:
            return (False)

    def write_hits(self,hits,sidtime):
        # Create localtime structure for producing filename
        foo = time.localtime()
        pfx = self.prefix
        filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
           foo.tm_mon, foo.tm_mday, foo.tm_hour)
    
        # Open the data file, appending
        hits_file = open (filenamestr+".seti","a")
        hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" "+str(hits)+"\n")
        hits_file.close()
        return

    def xydfunc(self,xyv):
        magn = int(Numeric.log10(self.observing))
        if (magn == 6 or magn == 7 or magn == 8):
            magn = 6
        dfreq = xyv[0] * pow(10.0,magn)
        ratio = self.observing / dfreq
        vs = 1.0 - ratio
        vs *= 299792.0
        if magn >= 9:
           xhz = "Ghz"
        elif magn >= 6:
           xhz = "Mhz"
        elif magn <= 5:
           xhz =  "Khz"
        s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
        s2 = "\n%.3fkm/s" % vs
        self.myform['spec_data'].set_value(s+s2)

    def toggle_cal(self):
        if (self.calstate == True):
          self.calstate = False
          self.u.write_io(0,0,(1<<15))
          self.calibrator.SetLabel("Calibration Source: Off")
        else:
          self.calstate = True
          self.u.write_io(0,(1<<15),(1<<15))
          self.calibrator.SetLabel("Calibration Source: On")

    def toggle_annotation(self):
        if (self.annotate_state == True):
          self.annotate_state = False
          self.annotation.SetLabel("Annotation: Off")
        else:
          self.annotate_state = True
          self.annotation.SetLabel("Annotation: On")
        

def main ():
    app = stdgui.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
    app.MainLoop()

if __name__ == '__main__':
    main ()