4290b0b03c72f606d855a979ce9b059fa083368a
[debian/gnuradio] / gr-radio-astronomy / src / python / usrp_ra_receiver.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2004,2005,2007 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 stdgui2, 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 numpy.fft
35 import ephem
36
37 class app_flow_graph(stdgui2.std_top_block):
38         def __init__(self, frame, panel, vbox, argv):
39                 stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)
40
41                 self.frame = frame
42                 self.panel = panel
43                 
44                 parser = OptionParser(option_class=eng_option)
45                 parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0, 0),
46                         help="select USRP Rx side A or B (default=A)")
47                 parser.add_option("-d", "--decim", type="int", default=16,
48                         help="set fgpa decimation rate to DECIM [default=%default]")
49                 parser.add_option("-f", "--freq", type="eng_float", default=None,
50                         help="set frequency to FREQ", metavar="FREQ")
51                 parser.add_option("-a", "--avg", type="eng_float", default=1.0,
52                         help="set spectral averaging alpha")
53                 parser.add_option("-i", "--integ", type="eng_float", default=1.0,
54                         help="set integration time")
55                 parser.add_option("-g", "--gain", type="eng_float", default=None,
56                         help="set gain in dB (default is midpoint)")
57                 parser.add_option("-l", "--reflevel", type="eng_float", default=30.0,
58                         help="Set Total power reference level")
59                 parser.add_option("-y", "--division", type="eng_float", default=0.5,
60                         help="Set Total power Y division size")
61                 parser.add_option("-e", "--longitude", type="eng_float", default=-76.02,help="Set Observer Longitude")
62                 parser.add_option("-c", "--latitude", type="eng_float", default=44.85,help="Set Observer Latitude")
63                 parser.add_option("-o", "--observing", type="eng_float", default=0.0,
64                         help="Set observing frequency")
65                 parser.add_option("-x", "--ylabel", default="dB", help="Y axis label") 
66                 parser.add_option("-z", "--divbase", type="eng_float", default=0.025, help="Y Division increment base") 
67                 parser.add_option("-v", "--stripsize", type="eng_float", default=2400, help="Size of stripchart, in 2Hz samples") 
68                 parser.add_option("-F", "--fft_size", type="eng_float", default=1024, help="Size of FFT")
69                 parser.add_option("-N", "--decln", type="eng_float", default=999.99, help="Observing declination")
70                 parser.add_option("-X", "--prefix", default="./")
71                 parser.add_option("-M", "--fft_rate", type="eng_float", default=8.0, help="FFT Rate")
72                 parser.add_option("-A", "--calib_coeff", type="eng_float", default=1.0, help="Calibration coefficient")
73                 parser.add_option("-B", "--calib_offset", type="eng_float", default=0.0, help="Calibration coefficient")
74                 parser.add_option("-W", "--waterfall", action="store_true", default=False, help="Use Waterfall FFT display")
75                 parser.add_option("-S", "--setimode", action="store_true", default=False, help="Enable SETI processing of spectral data")
76                 parser.add_option("-K", "--setik", type="eng_float", default=1.5, help="K value for SETI analysis")
77                 parser.add_option("-T", "--setibandwidth", type="eng_float", default=12500, help="Instantaneous SETI observing bandwidth--must be divisor of 250Khz")
78                 parser.add_option("-Q", "--seti_range", type="eng_float", default=1.0e6, help="Total scan width, in Hz for SETI scans")
79                 parser.add_option("-Z", "--dual_mode", action="store_true",
80                         default=False, help="Dual-polarization mode")
81                 parser.add_option("-I", "--interferometer", action="store_true", default=False, help="Interferometer mode")
82                 (options, args) = parser.parse_args()
83
84                 self.setimode = options.setimode
85                 self.dual_mode = options.dual_mode
86                 self.interferometer = options.interferometer
87                 self.normal_mode = False
88                 modecount = 0
89                 for modes in (self.dual_mode, self.interferometer):
90                         if (modes == True):
91                                 modecount = modecount + 1
92                                 
93                 if (modecount > 1):
94                         print "must select only 1 of --dual_mode, or --interferometer"
95                         sys.exit(1)
96                         
97                 self.chartneeded = True
98                 
99                 if (self.setimode == True):
100                         self.chartneeded = False
101                         
102                 if (self.setimode == True and self.interferometer == True):
103                         print "can't pick both --setimode and --interferometer"
104                         sys.exit(1)
105                 
106                 if (modecount == 0):
107                         self.normal_mode = True
108
109                 self.show_debug_info = True
110
111                 # Pick up waterfall option
112                 self.waterfall = options.waterfall
113
114                 # SETI mode stuff
115                 self.setimode = options.setimode
116                 self.seticounter = 0
117                 self.setik = options.setik
118                 self.seti_fft_bandwidth = int(options.setibandwidth)
119
120                 # Calculate binwidth
121                 binwidth = self.seti_fft_bandwidth / options.fft_size
122
123                 # Use binwidth, and knowledge of likely chirp rates to set reasonable
124                 #  values for SETI analysis code.       We assume that SETI signals will
125                 #  chirp at somewhere between 0.10Hz/sec and 0.25Hz/sec.
126                 #
127                 # upper_limit is the "worst case"--that is, the case for which we have
128                 #  to wait the longest to actually see any drift, due to the quantizing
129                 #  on FFT bins.
130                 upper_limit = binwidth / 0.10
131                 self.setitimer = int(upper_limit * 2.00)
132                 self.scanning = True
133
134                 # Calculate the CHIRP values based on Hz/sec
135                 self.CHIRP_LOWER = 0.10 * self.setitimer
136                 self.CHIRP_UPPER = 0.25 * self.setitimer
137
138                 # Reset hit counters to 0
139                 self.hitcounter = 0
140                 self.s1hitcounter = 0
141                 self.s2hitcounter = 0
142                 self.avgdelta = 0
143                 # We scan through 2Mhz of bandwidth around the chosen center freq
144                 self.seti_freq_range = options.seti_range
145                 # Calculate lower edge
146                 self.setifreq_lower = options.freq - (self.seti_freq_range/2)
147                 self.setifreq_current = options.freq
148                 # Calculate upper edge
149                 self.setifreq_upper = options.freq + (self.seti_freq_range/2)
150
151                 # Maximum "hits" in a line
152                 self.nhits = 20
153
154                 # Number of lines for analysis
155                 self.nhitlines = 4
156
157                 # We change center frequencies based on nhitlines and setitimer
158                 self.setifreq_timer = self.setitimer * (self.nhitlines * 5)
159
160                 # Create actual timer
161                 self.seti_then = time.time()
162
163                 # The hits recording array
164                 self.hits_array = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
165                 self.hit_intensities = Numeric.zeros((self.nhits,self.nhitlines), Numeric.Float64)
166                 # Calibration coefficient and offset
167                 self.calib_coeff = options.calib_coeff
168                 self.calib_offset = options.calib_offset
169                 if self.calib_offset < -750:
170                         self.calib_offset = -750
171                 if self.calib_offset > 750:
172                         self.calib_offset = 750
173
174                 if self.calib_coeff < 1:
175                         self.calib_coeff = 1
176                 if self.calib_coeff > 100:
177                         self.calib_coeff = 100
178
179                 self.integ = options.integ
180                 self.avg_alpha = options.avg
181                 self.gain = options.gain
182                 self.decln = options.decln
183
184                 # Set initial values for datalogging timed-output
185                 self.continuum_then = time.time()
186                 self.spectral_then = time.time()
187                 
188           
189                 # build the graph
190
191                 self.subdev = [(0, 0), (0,0)]
192                 
193                 #
194                 # If SETI mode, we always run at maximum USRP decimation
195                 #
196                 if (self.setimode):
197                         options.decim = 256
198
199                 if (self.dual_mode == False and self.interferometer == False):
200                         self.u = usrp.source_c(decim_rate=options.decim)
201                         self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
202                         # determine the daughterboard subdevice we're using
203                         self.subdev[0] = usrp.selected_subdev(self.u, options.rx_subdev_spec)
204                         self.subdev[1] = self.subdev[0]
205                         self.cardtype = self.subdev[0].dbid()
206                 else:
207                         self.u=usrp.source_c(decim_rate=options.decim, nchan=2)
208                         self.subdev[0] = usrp.selected_subdev(self.u, (0, 0))
209                         self.subdev[1] = usrp.selected_subdev(self.u, (1, 0))
210                         self.cardtype = self.subdev[0].dbid()
211                         self.u.set_mux(0x32103210)
212                         c1 = self.subdev[0].name()
213                         c2 = self.subdev[1].name()
214                         if (c1 != c2):
215                                 print "Must have identical cardtypes for --dual_mode or --interferometer"
216                                 sys.exit(1)
217                 #
218                 # Set 8-bit mode
219                 #
220                 width = 8
221                 shift = 8
222                 format = self.u.make_format(width, shift)
223                 r = self.u.set_format(format)
224                 
225                 # Set initial declination
226                 self.decln = options.decln
227
228                 input_rate = self.u.adc_freq() / self.u.decim_rate()
229
230                 #
231                 # Set prefix for data files
232                 #
233                 self.prefix = options.prefix
234
235                 #
236                 # The lower this number, the fewer sample frames are dropped
237                 #  in computing the FFT.  A sampled approach is taken to
238                 #  computing the FFT of the incoming data, which reduces
239                 #  sensitivity.  Increasing sensitivity inreases CPU loading.
240                 #
241                 self.fft_rate = options.fft_rate
242
243                 self.fft_size = int(options.fft_size)
244
245                 # This buffer is used to remember the most-recent FFT display
246                 #       values.  Used later by self.write_spectral_data() to write
247                 #       spectral data to datalogging files, and by the SETI analysis
248                 #       function.
249                 #
250                 self.fft_outbuf = Numeric.zeros(self.fft_size, Numeric.Float64)
251
252                 #
253                 # If SETI mode, only look at seti_fft_bandwidth
254                 #       at a time.
255                 #
256                 if (self.setimode):
257                         self.fft_input_rate = self.seti_fft_bandwidth
258
259                         #
260                         # Build a decimating bandpass filter
261                         #
262                         self.fft_input_taps = gr.firdes.complex_band_pass (1.0,
263                            input_rate,
264                            -(int(self.fft_input_rate/2)), int(self.fft_input_rate/2), 200,
265                            gr.firdes.WIN_HAMMING, 0)
266
267                         #
268                         # Compute required decimation factor
269                         #
270                         decimation = int(input_rate/self.fft_input_rate)
271                         self.fft_bandpass = gr.fir_filter_ccc (decimation, 
272                                 self.fft_input_taps)
273                 else:
274                         self.fft_input_rate = input_rate
275
276                 # Set up FFT display
277                 if self.waterfall == False:
278                    self.scope = ra_fftsink.ra_fft_sink_c (panel, 
279                            fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
280                            fft_rate=int(self.fft_rate), title="Spectral",  
281                            ofunc=self.fft_outfunc, xydfunc=self.xydfunc)
282                 else:
283                         self.scope = ra_waterfallsink.waterfall_sink_c (panel,
284                                 fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
285                                 fft_rate=int(self.fft_rate), title="Spectral", ofunc=self.fft_outfunc, size=(1100, 600), xydfunc=self.xydfunc, ref_level=0, span=10)
286
287                 # Set up ephemeris data
288                 self.locality = ephem.Observer()
289                 self.locality.long = str(options.longitude)
290                 self.locality.lat = str(options.latitude)
291                 
292                 # We make notes about Sunset/Sunrise in Continuum log files
293                 self.sun = ephem.Sun()
294                 self.sunstate = "??"
295
296                 # Set up stripchart display
297                 tit = "Continuum"
298                 if (self.dual_mode != False):
299                         tit = "H+V Continuum"
300                 if (self.interferometer != False):
301                         tit = "East x West Correlation"
302                 self.stripsize = int(options.stripsize)
303                 if self.chartneeded == True:
304                         self.chart = ra_stripchartsink.stripchart_sink_f (panel,
305                                 stripsize=self.stripsize,
306                                 title=tit,
307                                 xlabel="LMST Offset (Seconds)",
308                                 scaling=1.0, ylabel=options.ylabel,
309                                 divbase=options.divbase)
310
311                 # Set center frequency
312                 self.centerfreq = options.freq
313
314                 # Set observing frequency (might be different from actual programmed
315                 #        RF frequency)
316                 if options.observing == 0.0:
317                         self.observing = options.freq
318                 else:
319                         self.observing = options.observing
320
321                 # Remember our input bandwidth
322                 self.bw = input_rate
323
324                 #
325                 # 
326                 # The strip chart is fed at a constant 1Hz rate
327                 #
328
329                 #
330                 # Call constructors for receive chains
331                 #
332                 
333                 if (self.dual_mode == True):
334                         self.setup_dual (self.setimode)
335                         
336                 if (self.interferometer == True):
337                         self.setup_interferometer(self.setimode)
338                                 
339                 if (self.normal_mode == True):
340                         self.setup_normal(self.setimode)
341                         
342                 if (self.setimode == True):
343                         self.setup_seti()
344
345                 self._build_gui(vbox)
346
347                 # Make GUI agree with command-line
348                 self.integ = options.integ
349                 if self.setimode == False:
350                         self.myform['integration'].set_value(int(options.integ))
351                         self.myform['offset'].set_value(self.calib_offset)
352                         self.myform['dcgain'].set_value(self.calib_coeff)
353                 self.myform['average'].set_value(int(options.avg))
354
355
356                 if self.setimode == False:
357                         # Make integrator agree with command line
358                         self.set_integration(int(options.integ))
359
360                 self.avg_alpha = options.avg
361
362                 # Make spectral averager agree with command line
363                 if options.avg != 1.0:
364                         self.scope.set_avg_alpha(float(1.0/options.avg))
365                         self.scope.set_average(True)
366
367                 if self.setimode == False:
368                         # Set division size
369                         self.chart.set_y_per_div(options.division)
370                         # Set reference(MAX) level
371                         self.chart.set_ref_level(options.reflevel)
372
373                 # set initial values
374
375                 if options.gain is None:
376                         # if no gain was specified, use the mid-point in dB
377                         g = self.subdev[0].gain_range()
378                         options.gain = float(g[0]+g[1])/2
379
380                 if options.freq is None:
381                         # if no freq was specified, use the mid-point
382                         r = self.subdev[0].freq_range()
383                         options.freq = float(r[0]+r[1])/2
384
385                 # Set the initial gain control
386                 self.set_gain(options.gain)
387
388                 if not(self.set_freq(options.freq)):
389                         self._set_status_msg("Failed to set initial frequency")
390
391                 # Set declination
392                 self.set_decln (self.decln)
393
394
395                 # RF hardware information
396                 self.myform['decim'].set_value(self.u.decim_rate())
397                 self.myform['USB BW'].set_value(self.u.adc_freq() / self.u.decim_rate())
398                 if (self.dual_mode == True):
399                         self.myform['dbname'].set_value(self.subdev[0].name()+'/'+self.subdev[1].name())
400                 else:
401                         self.myform['dbname'].set_value(self.subdev[0].name())
402
403                 # Set analog baseband filtering, if DBS_RX
404                 if self.cardtype in (usrp_dbid.DBS_RX, usrp_dbid.DBS_RX_REV_2_1):
405                         lbw = (self.u.adc_freq() / self.u.decim_rate()) / 2
406                         if lbw < 1.0e6:
407                                 lbw = 1.0e6
408                         self.subdev[0].set_bw(lbw)
409                         self.subdev[1].set_bw(lbw)
410                         
411                 # Start the timer for the LMST display and datalogging
412                 self.lmst_timer.Start(1000)
413
414
415         def _set_status_msg(self, msg):
416                 self.frame.GetStatusBar().SetStatusText(msg, 0)
417
418         def _build_gui(self, vbox):
419
420                 def _form_set_freq(kv):
421                         # Adjust current SETI frequency, and limits
422                         self.setifreq_lower = kv['freq'] - (self.seti_freq_range/2)
423                         self.setifreq_current = kv['freq']
424                         self.setifreq_upper = kv['freq'] + (self.seti_freq_range/2)
425
426                         # Reset SETI analysis timer
427                         self.seti_then = time.time()
428                         # Zero-out hits array when changing frequency
429                         self.hits_array[:,:] = 0.0
430                         self.hit_intensities[:,:] = -60.0
431
432                         return self.set_freq(kv['freq'])
433
434                 def _form_set_decln(kv):
435                         return self.set_decln(kv['decln'])
436
437                 # Position the FFT display
438                 vbox.Add(self.scope.win, 15, wx.EXPAND)
439
440                 if self.setimode == False:
441                         # Position the Total-power stripchart
442                         vbox.Add(self.chart.win, 15, wx.EXPAND)
443                 
444                 # add control area at the bottom
445                 self.myform = myform = form.form()
446                 hbox = wx.BoxSizer(wx.HORIZONTAL)
447                 hbox.Add((7,0), 0, wx.EXPAND)
448                 vbox1 = wx.BoxSizer(wx.VERTICAL)
449                 myform['freq'] = form.float_field(
450                         parent=self.panel, sizer=vbox1, label="Center freq", weight=1,
451                         callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
452
453                 vbox1.Add((4,0), 0, 0)
454
455                 myform['lmst_high'] = form.static_text_field(
456                         parent=self.panel, sizer=vbox1, label="Current LMST", weight=1)
457                 vbox1.Add((4,0), 0, 0)
458
459                 if self.setimode == False:
460                         myform['spec_data'] = form.static_text_field(
461                                 parent=self.panel, sizer=vbox1, label="Spectral Cursor", weight=1)
462                         vbox1.Add((4,0), 0, 0)
463
464                 vbox2 = wx.BoxSizer(wx.VERTICAL)
465                 if self.setimode == False:
466                         vbox3 = wx.BoxSizer(wx.VERTICAL)
467                 g = self.subdev[0].gain_range()
468                 myform['gain'] = form.slider_field(parent=self.panel, sizer=vbox2, label="RF Gain",
469                                                                                    weight=1,
470                                                                                    min=int(g[0]), max=int(g[1]),
471                                                                                    callback=self.set_gain)
472
473                 vbox2.Add((4,0), 0, 0)
474                 if self.setimode == True:
475                         max_savg = 100
476                 else:
477                         max_savg = 3000
478                 myform['average'] = form.slider_field(parent=self.panel, sizer=vbox2, 
479                                         label="Spectral Averaging (FFT frames)", weight=1, min=1, max=max_savg, callback=self.set_averaging)
480
481                 # Set up scan control button when in SETI mode
482                 if (self.setimode == True):
483                         # SETI scanning control
484                         buttonbox = wx.BoxSizer(wx.HORIZONTAL)
485                         self.scan_control = form.button_with_callback(self.panel,
486                                   label="Scan: On ",
487                                   callback=self.toggle_scanning)
488         
489                         buttonbox.Add(self.scan_control, 0, wx.CENTER)
490                         vbox2.Add(buttonbox, 0, wx.CENTER)
491
492                 vbox2.Add((4,0), 0, 0)
493
494                 if self.setimode == False:
495                         myform['integration'] = form.slider_field(parent=self.panel, sizer=vbox2,
496                                    label="Continuum Integration Time (sec)", weight=1, min=1, max=180, callback=self.set_integration)
497
498                         vbox2.Add((4,0), 0, 0)
499
500                 myform['decln'] = form.float_field(
501                         parent=self.panel, sizer=vbox2, label="Current Declination", weight=1,
502                         callback=myform.check_input_and_call(_form_set_decln))
503                 vbox2.Add((4,0), 0, 0)
504
505                 if self.setimode == False:
506                         myform['offset'] = form.slider_field(parent=self.panel, sizer=vbox3,
507                                 label="Post-Detector Offset", weight=1, min=-750, max=750, 
508                                 callback=self.set_pd_offset)
509                         vbox3.Add((2,0), 0, 0)
510                         myform['dcgain'] = form.slider_field(parent=self.panel, sizer=vbox3,
511                                 label="Post-Detector Gain", weight=1, min=1, max=100, 
512                                 callback=self.set_pd_gain)
513                         vbox3.Add((2,0), 0, 0)
514                 hbox.Add(vbox1, 0, 0)
515                 hbox.Add(vbox2, wx.ALIGN_RIGHT, 0)
516
517                 if self.setimode == False:
518                         hbox.Add(vbox3, wx.ALIGN_RIGHT, 0)
519
520                 vbox.Add(hbox, 0, wx.EXPAND)
521
522                 self._build_subpanel(vbox)
523
524                 self.lmst_timer = wx.PyTimer(self.lmst_timeout)
525                 #self.lmst_timeout()
526
527
528         def _build_subpanel(self, vbox_arg):
529                 # build a secondary information panel (sometimes hidden)
530
531                 # FIXME figure out how to have this be a subpanel that is always
532                 # created, but has its visibility controlled by foo.Show(True/False)
533                 
534                 if not(self.show_debug_info):
535                         return
536
537                 panel = self.panel
538                 vbox = vbox_arg
539                 myform = self.myform
540
541                 #panel = wx.Panel(self.panel, -1)
542                 #vbox = wx.BoxSizer(wx.VERTICAL)
543
544                 hbox = wx.BoxSizer(wx.HORIZONTAL)
545                 hbox.Add((5,0), 0)
546                 myform['decim'] = form.static_float_field(
547                         parent=panel, sizer=hbox, label="Decim")
548
549                 hbox.Add((5,0), 1)
550                 myform['USB BW'] = form.static_float_field(
551                         parent=panel, sizer=hbox, label="USB BW")
552
553                 hbox.Add((5,0), 1)
554                 myform['dbname'] = form.static_text_field(
555                         parent=panel, sizer=hbox)
556
557                 hbox.Add((5,0), 1)
558                 myform['baseband'] = form.static_float_field(
559                         parent=panel, sizer=hbox, label="Analog BB")
560
561                 hbox.Add((5,0), 1)
562                 myform['ddc'] = form.static_float_field(
563                         parent=panel, sizer=hbox, label="DDC")
564
565                 hbox.Add((5,0), 0)
566                 vbox.Add(hbox, 0, wx.EXPAND)
567
568                 
569                 
570         def set_freq(self, target_freq):
571                 """
572                 Set the center frequency we're interested in.
573
574                 @param target_freq: frequency in Hz
575                 @rypte: bool
576
577                 Tuning is a two step process.  First we ask the front-end to
578                 tune as close to the desired frequency as it can.  Then we use
579                 the result of that operation and our target_frequency to
580                 determine the value for the digital down converter.
581                 """
582                 #
583                 # Everything except BASIC_RX should support usrp.tune()
584                 #
585                 if not (self.cardtype == usrp_dbid.BASIC_RX):
586                         r = usrp.tune(self.u, self.subdev[0]._which, self.subdev[0], target_freq)
587                         r = usrp.tune(self.u, self.subdev[1]._which, self.subdev[1], target_freq)
588                 else:
589                         r = self.u.set_rx_freq(0, target_freq)
590                         f = self.u.rx_freq(0)
591                         if abs(f-target_freq) > 2.0e3:
592                                 r = 0
593                 if r:
594                         self.myform['freq'].set_value(target_freq)         # update displayed value
595                         #
596                         # Make sure calibrator knows our target freq
597                         #
598
599                         # Remember centerfreq---used for doppler calcs
600                         delta = self.centerfreq - target_freq
601                         self.centerfreq = target_freq
602                         self.observing -= delta
603                         self.scope.set_baseband_freq (self.observing)
604
605                         self.myform['baseband'].set_value(r.baseband_freq)
606                         self.myform['ddc'].set_value(r.dxc_freq)
607
608                         return True
609
610                 return False
611
612         def set_decln(self, dec):
613                 self.decln = dec
614                 self.myform['decln'].set_value(dec)             # update displayed value
615
616         def set_gain(self, gain):
617                 self.myform['gain'].set_value(gain)             # update displayed value
618                 self.subdev[0].set_gain(gain)
619                 self.subdev[1].set_gain(gain)
620                 self.gain = gain
621
622         def set_averaging(self, avval):
623                 self.myform['average'].set_value(avval)
624                 self.scope.set_avg_alpha(1.0/(avval))
625                 self.scope.set_average(True)
626                 self.avg_alpha = avval
627
628         def set_integration(self, integval):
629                 if self.setimode == False:
630                         self.integrator.set_taps(1.0/((integval)*(self.bw/2)))
631                 self.myform['integration'].set_value(integval)
632                 self.integ = integval
633
634         #
635         # Timeout function
636         # Used to update LMST display, as well as current
637         #  continuum value
638         #
639         # We also write external data-logging files here
640         #
641         def lmst_timeout(self):
642                 self.locality.date = ephem.now()
643                 if self.setimode == False:
644                  x = self.probe.level()
645                 sidtime = self.locality.sidereal_time()
646                 # LMST
647                 s = str(ephem.hours(sidtime)) + " " + self.sunstate
648                 # Continuum detector value
649                 if self.setimode == False:
650                  sx = "%7.4f" % x
651                  s = s + "\nDet: " + str(sx)
652                 else:
653                  sx = "%2d" % self.hitcounter
654                  s1 = "%2d" % self.s1hitcounter
655                  s2 = "%2d" % self.s2hitcounter
656                  sa = "%4.2f" % self.avgdelta
657                  sy = "%3.1f-%3.1f" % (self.CHIRP_LOWER, self.CHIRP_UPPER)
658                  s = s + "\nHits: " + str(sx) + "\nS1:" + str(s1) + " S2:" + str(s2)
659                  s = s + "\nAv D: " + str(sa) + "\nCh lim: " + str(sy)
660
661                 self.myform['lmst_high'].set_value(s)
662
663                 #
664                 # Write data out to recording files
665                 #
666                 if self.setimode == False:
667                  self.write_continuum_data(x,sidtime)
668                  self.write_spectral_data(self.fft_outbuf,sidtime)
669
670                 else:
671                  self.seti_analysis(self.fft_outbuf,sidtime)
672                  now = time.time()
673                  if ((self.scanning == True) and ((now - self.seti_then) > self.setifreq_timer)):
674                          self.seti_then = now
675                          self.setifreq_current = self.setifreq_current + self.fft_input_rate
676                          if (self.setifreq_current > self.setifreq_upper):
677                                  self.setifreq_current = self.setifreq_lower
678                          self.set_freq(self.setifreq_current)
679                          # Make sure we zero-out the hits array when changing
680                          #       frequency.
681                          self.hits_array[:,:] = 0.0
682                          self.hit_intensities[:,:] = 0.0
683
684         def fft_outfunc(self,data,l):
685                 self.fft_outbuf=data
686
687         def write_continuum_data(self,data,sidtime):
688         
689                 # Create localtime structure for producing filename
690                 foo = time.localtime()
691                 pfx = self.prefix
692                 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
693                    foo.tm_mon, foo.tm_mday, foo.tm_hour)
694         
695                 # Open the data file, appending
696                 continuum_file = open (filenamestr+".tpdat","a")
697           
698                 flt = "%6.3f" % data
699                 inter = self.decln
700                 integ = self.integ
701                 fc = self.observing
702                 fc = fc / 1000000
703                 bw = self.bw
704                 bw = bw / 1000000
705                 ga = self.gain
706         
707                 now = time.time()
708         
709                 #
710                 # If time to write full header info (saves storage this way)
711                 #
712                 if (now - self.continuum_then > 20):
713                         self.sun.compute(self.locality)
714                         enow = ephem.now()
715                         sun_insky = "Down"
716                         self.sunstate = "Dn"
717                         if ((self.sun.rise_time < enow) and (enow < self.sun.set_time)):
718                            sun_insky = "Up"
719                            self.sunstate = "Up"
720                         self.continuum_then = now
721                 
722                         continuum_file.write(str(ephem.hours(sidtime))+" "+flt+" Dn="+str(inter)+",")
723                         continuum_file.write("Ti="+str(integ)+",Fc="+str(fc)+",Bw="+str(bw))
724                         continuum_file.write(",Ga="+str(ga)+",Sun="+str(sun_insky)+"\n")
725                 else:
726                         continuum_file.write(str(ephem.hours(sidtime))+" "+flt+"\n")
727         
728                 continuum_file.close()
729                 return(data)
730
731         def write_spectral_data(self,data,sidtime):
732         
733                 now = time.time()
734                 delta = 10
735                         
736                 # If time to write out spectral data
737                 # We don't write this out every time, in order to
738                 #       save disk space.  Since the spectral data are
739                 #       typically heavily averaged, writing this data
740                 #       "once in a while" is OK.
741                 #
742                 if (now - self.spectral_then >= delta):
743                         self.spectral_then = now
744
745                         # Get localtime structure to make filename from
746                         foo = time.localtime()
747                 
748                         pfx = self.prefix
749                         filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
750                            foo.tm_mon, foo.tm_mday, foo.tm_hour)
751         
752                         # Open the file
753                         spectral_file = open (filenamestr+".sdat","a")
754           
755                         # Setup data fields to be written
756                         r = data
757                         inter = self.decln
758                         fc = self.observing
759                         fc = fc / 1000000
760                         bw = self.bw
761                         bw = bw / 1000000
762                         av = self.avg_alpha
763
764                         # Write those fields
765                         spectral_file.write("data:"+str(ephem.hours(sidtime))+" Dn="+str(inter)+",Fc="+str(fc)+",Bw="+str(bw)+",Av="+str(av))
766                         spectral_file.write (" [ ")
767                         for r in data:
768                                 spectral_file.write(" "+str(r))
769
770                         spectral_file.write(" ]\n")
771                         spectral_file.close()
772                         return(data)
773         
774                 return(data)
775
776         def seti_analysis(self,fftbuf,sidtime):
777                 l = len(fftbuf)
778                 x = 0
779                 hits = []
780                 hit_intensities = []
781                 if self.seticounter < self.setitimer:
782                         self.seticounter = self.seticounter + 1
783                         return
784                 else:
785                         self.seticounter = 0
786
787                 # Run through FFT output buffer, computing standard deviation (Sigma)
788                 avg = 0
789                 # First compute average
790                 for i in range(0,l):
791                         avg = avg + fftbuf[i]
792                 avg = avg / l
793
794                 sigma = 0.0
795                 # Then compute standard deviation (Sigma)
796                 for i in range(0,l):
797                         d = fftbuf[i] - avg
798                         sigma = sigma + (d*d)
799
800                 sigma = Numeric.sqrt(sigma/l)
801
802                 #
803                 # Snarfle through the FFT output buffer again, looking for
804                 #        outlying data points
805
806                 start_f = self.observing - (self.fft_input_rate/2)
807                 current_f = start_f
808                 l = len(fftbuf)
809                 f_incr = self.fft_input_rate / l
810                 hit = -1
811
812                 # -nyquist to DC
813                 for i in range(l/2,l):
814                         #
815                         # If current FFT buffer has an item that exceeds the specified
816                         #  sigma
817                         #
818                         if ((fftbuf[i] - avg) > (self.setik * sigma)):
819                                 hits.append(current_f)
820                                 hit_intensities.append(fftbuf[i])
821                         current_f = current_f + f_incr
822
823                 # DC to nyquist
824                 for i in range(0,l/2):
825                         #
826                         # If current FFT buffer has an item that exceeds the specified
827                         #  sigma
828                         #
829                         if ((fftbuf[i] - avg) > (self.setik * sigma)):
830                                 hits.append(current_f)
831                                 hit_intensities.append(fftbuf[i])
832                         current_f = current_f + f_incr
833
834                 # No hits
835                 if (len(hits) <= 0):
836                         return
837
838
839                 #
840                 # OK, so we have some hits in the FFT buffer
841                 #       They'll have a rather substantial gauntlet to run before
842                 #       being declared a real "hit"
843                 #
844
845                 # Update stats
846                 self.s1hitcounter = self.s1hitcounter + len(hits)
847
848                 # Weed out buffers with an excessive number of
849                 #       signals above Sigma
850                 if (len(hits) > self.nhits):
851                         return
852
853
854                 # Weed out FFT buffers with apparent multiple narrowband signals
855                 #       separated significantly in frequency.  This means that a
856                 #       single signal spanning multiple bins is OK, but a buffer that
857                 #       has multiple, apparently-separate, signals isn't OK.
858                 #
859                 last = hits[0]
860                 ns2 = 1
861                 for i in range(1,len(hits)):
862                         if ((hits[i] - last) > (f_incr*3.0)):
863                                 return
864                         last = hits[i]
865                         ns2 = ns2 + 1
866
867                 self.s2hitcounter = self.s2hitcounter + ns2
868
869                 #
870                 # Run through all available hit buffers, computing difference between
871                 #       frequencies found there, if they're all within the chirp limits
872                 #       declare a good hit
873                 #
874                 good_hit = False
875                 f_ds = Numeric.zeros(self.nhitlines, Numeric.Float64)
876                 avg_delta = 0
877                 k = 0
878                 for i in range(0,min(len(hits),len(self.hits_array[:,0]))):
879                         f_ds[0] = abs(self.hits_array[i,0] - hits[i])
880                         for j in range(1,len(f_ds)):
881                            f_ds[j] = abs(self.hits_array[i,j] - self.hits_array[i,0])
882                            avg_delta = avg_delta + f_ds[j]
883                            k = k + 1
884
885                         if (self.seti_isahit (f_ds)):
886                                 good_hit = True
887                                 self.hitcounter = self.hitcounter + 1
888                                 break
889
890                 if (avg_delta/k < (self.seti_fft_bandwidth/2)):
891                         self.avgdelta = avg_delta / k
892
893                 # Save 'n shuffle hits
894                 #  Old hit buffers percolate through the hit buffers
895                 #  (there are self.nhitlines of these buffers)
896                 #  and then drop off the end
897                 #  A consequence is that while the nhitlines buffers are filling,
898                 #  you can get some absurd values for self.avgdelta, because some
899                 #  of the buffers are full of zeros
900                 for i in range(self.nhitlines,1):
901                         self.hits_array[:,i] = self.hits_array[:,i-1]
902                         self.hit_intensities[:,i] = self.hit_intensities[:,i-1]
903
904                 for i in range(0,len(hits)):
905                         self.hits_array[i,0] = hits[i]
906                         self.hit_intensities[i,0] = hit_intensities[i]
907
908                 # Finally, write the hits/intensities buffer
909                 if (good_hit):
910                         self.write_hits(sidtime)
911
912                 return
913
914         def seti_isahit(self,fdiffs):
915                 truecount = 0
916
917                 for i in range(0,len(fdiffs)):
918                         if (fdiffs[i] >= self.CHIRP_LOWER and fdiffs[i] <= self.CHIRP_UPPER):
919                                 truecount = truecount + 1
920
921                 if truecount == len(fdiffs):
922                         return (True)
923                 else:
924                         return (False)
925
926         def write_hits(self,sidtime):
927                 # Create localtime structure for producing filename
928                 foo = time.localtime()
929                 pfx = self.prefix
930                 filenamestr = "%s/%04d%02d%02d%02d" % (pfx, foo.tm_year, 
931                    foo.tm_mon, foo.tm_mday, foo.tm_hour)
932         
933                 # Open the data file, appending
934                 hits_file = open (filenamestr+".seti","a")
935
936                 # Write sidtime first
937                 hits_file.write(str(ephem.hours(sidtime))+" "+str(self.decln)+" ")
938
939                 #
940                 # Then write the hits/hit intensities buffers with enough
941                 #       "syntax" to allow parsing by external (not yet written!)
942                 #       "stuff".
943                 #
944                 for i in range(0,self.nhitlines):
945                         hits_file.write(" ")
946                         for j in range(0,self.nhits):
947                                 hits_file.write(str(self.hits_array[j,i])+":")
948                                 hits_file.write(str(self.hit_intensities[j,i])+",")
949                 hits_file.write("\n")
950                 hits_file.close()
951                 return
952
953         def xydfunc(self,xyv):
954                 if self.setimode == True:
955                         return
956                 magn = int(Numeric.log10(self.observing))
957                 if (magn == 6 or magn == 7 or magn == 8):
958                         magn = 6
959                 dfreq = xyv[0] * pow(10.0,magn)
960                 ratio = self.observing / dfreq
961                 vs = 1.0 - ratio
962                 vs *= 299792.0
963                 if magn >= 9:
964                    xhz = "Ghz"
965                 elif magn >= 6:
966                    xhz = "Mhz"
967                 elif magn <= 5:
968                    xhz =  "Khz"
969                 s = "%.6f%s\n%.3fdB" % (xyv[0], xhz, xyv[1])
970                 s2 = "\n%.3fkm/s" % vs
971                 self.myform['spec_data'].set_value(s+s2)
972
973         def xydfunc_waterfall(self,pos):
974                 lower = self.observing - (self.seti_fft_bandwidth / 2)
975                 upper = self.observing + (self.seti_fft_bandwidth / 2)
976                 binwidth = self.seti_fft_bandwidth / 1024
977                 s = "%.6fMHz" % ((lower + (pos.x*binwidth)) / 1.0e6)
978                 self.myform['spec_data'].set_value(s)
979
980         def toggle_cal(self):
981                 if (self.calstate == True):
982                   self.calstate = False
983                   self.u.write_io(0,0,(1<<15))
984                   self.calibrator.SetLabel("Calibration Source: Off")
985                 else:
986                   self.calstate = True
987                   self.u.write_io(0,(1<<15),(1<<15))
988                   self.calibrator.SetLabel("Calibration Source: On")
989
990         def toggle_annotation(self):
991                 if (self.annotate_state == True):
992                   self.annotate_state = False
993                   self.annotation.SetLabel("Annotation: Off")
994                 else:
995                   self.annotate_state = True
996                   self.annotation.SetLabel("Annotation: On")
997         #
998         # Turn scanning on/off
999         # Called-back by "Recording" button
1000         #
1001         def toggle_scanning(self):
1002                 # Current scanning?      Flip state
1003                 if (self.scanning == True):
1004                   self.scanning = False
1005                   self.scan_control.SetLabel("Scan: Off")
1006                 # Not scanning
1007                 else:
1008                   self.scanning = True
1009                   self.scan_control.SetLabel("Scan: On ")
1010
1011         def set_pd_offset(self,offs):
1012                  self.myform['offset'].set_value(offs)
1013                  self.calib_offset=offs
1014                  x = self.calib_coeff / 100.0
1015                  self.cal_offs.set_k(offs*(x*8000))
1016
1017         def set_pd_gain(self,gain):
1018                  self.myform['dcgain'].set_value(gain)
1019                  self.cal_mult.set_k(gain*0.01)
1020                  self.calib_coeff = gain
1021                  x = gain/100.0
1022                  self.cal_offs.set_k(self.calib_offset*(x*8000))
1023
1024         def compute_notch_taps(self,notchlist):
1025                  NOTCH_TAPS = 256
1026                  tmptaps = Numeric.zeros(NOTCH_TAPS,Numeric.Complex64)
1027                  binwidth = self.bw / NOTCH_TAPS
1028  
1029                  for i in range(0,NOTCH_TAPS):
1030                          tmptaps[i] = complex(1.0,0.0)
1031  
1032                  for i in notchlist:
1033                          diff = i - self.observing
1034                          if i == 0:
1035                                  break
1036                          if (diff > 0):
1037                                  idx = diff / binwidth
1038                                  idx = int(idx)
1039                                  if (idx < 0 or idx > (NOTCH_TAPS/2)):
1040                                          break
1041                                  tmptaps[idx] = complex(0.0, 0.0)
1042
1043                          if (diff < 0):
1044                                  idx = -diff / binwidth
1045                                  idx = (NOTCH_TAPS/2) - idx
1046                                  idx = int(idx+(NOTCH_TAPS/2))
1047                                  if (idx < 0 or idx > (NOTCH_TAPS)):
1048                                          break
1049                                  tmptaps[idx] = complex(0.0, 0.0)
1050
1051                  self.notch_taps = numpy.fft.ifft(tmptaps)
1052         
1053         #
1054         # Setup common pieces of radiometer mode
1055         #
1056         def setup_radiometer_common(self):
1057                 # The IIR integration filter for post-detection
1058                         self.integrator = gr.single_pole_iir_filter_ff(1.0)
1059                         self.integrator.set_taps (1.0/self.bw)
1060         
1061                         # Signal probe
1062                         self.probe = gr.probe_signal_f()
1063         
1064                         #
1065                         # Continuum calibration stuff
1066                         #
1067                         x = self.calib_coeff/100.0
1068                         self.cal_mult = gr.multiply_const_ff(self.calib_coeff/100.0)
1069                         self.cal_offs = gr.add_const_ff(self.calib_offset*(x*8000))
1070                         
1071                         #
1072                         # Mega decimator after IIR filter
1073                         #
1074                         self.keepn = gr.keep_one_in_n(gr.sizeof_float, self.bw)
1075                 
1076         
1077         #
1078         # Setup ordinary single-channel radiometer mode
1079         #        
1080         def setup_normal(self, setimode):
1081                 
1082                 self.head = self.u
1083                 self.shead = self.u
1084                 
1085                 if setimode == False:
1086                         self.detector = gr.complex_to_mag_squared()
1087                         self.setup_radiometer_common()          
1088                         
1089                         self.connect(self.shead, self.scope)
1090
1091                         self.connect(self.head, self.detector, 
1092                                 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1093                                 
1094                         self.connect(self.cal_offs, self.probe)
1095                         
1096                 return
1097         
1098         #
1099         # Setup dual-channel (two antenna, usual orthogonal polarity probes in the same waveguide)
1100         #
1101         def setup_dual(self, setimode):
1102                 
1103                 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1104                 self.addchans = gr.add_cc ()
1105                 self.detector = gr.add_ff ()
1106                 self.h_power = gr.complex_to_mag_squared()
1107                 self.v_power = gr.complex_to_mag_squared()
1108                 self.connect (self.u, self.di)
1109                 
1110                 #
1111                 # For spectral, adding the two channels works, assuming no gross
1112                 #       phase or amplitude error
1113                 self.connect ((self.di, 0), (self.addchans, 0))
1114                 self.connect ((self.di, 1), (self.addchans, 1))
1115                 
1116                 #
1117                 # Connect heads of spectral and total-power chains
1118                 #
1119                 self.head = self.di
1120                 self.shead = self.addchans
1121                 
1122                 if (setimode == False):
1123                         
1124                         self.setup_radiometer_common()
1125                 
1126                         #
1127                         # For dual-polarization mode, we compute the sum of the
1128                         #       powers on each channel, after they've been detected
1129                         #
1130                         self.detector = gr.add_ff()
1131                         #
1132                         # In dual-polarization mode, we compute things a little differently
1133                         # In effect, we have two radiometer chains, terminating in an adder
1134                         #
1135                         self.connect((self.di, 0), self.h_power)
1136                         self.connect((self.di, 1), self.v_power)
1137                         self.connect(self.h_power, (self.detector, 0))
1138                         self.connect(self.v_power, (self.detector, 1))
1139                         self.connect(self.detector,
1140                                 self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1141                         self.connect(self.cal_offs, self.probe)
1142                         self.connect(self.shead, self.scope)
1143                 return
1144         
1145         #
1146         # Setup correlating interferometer mode
1147         #
1148         def setup_interferometer(self, setimode):
1149                 self.setup_radiometer_common()
1150                 
1151                 self.di = gr.deinterleave(gr.sizeof_gr_complex)
1152                 self.connect (self.u, self.di)
1153                 self.corr = gr.multiply_cc()
1154                 self.c2f = gr.complex_to_float()
1155                 
1156                 self.shead = (self.di, 0)
1157                 
1158                 # Channel 0 to multiply port 0
1159                 # Channel 1 to multiply port 1
1160                 self.connect((self.di, 0), (self.corr, 0))
1161                 self.connect((self.di, 1), (self.corr, 1))
1162                 
1163                 #
1164                 # Multiplier (correlator) to complex-to-float, followed by integrator, etc
1165                 #
1166                 self.connect(self.corr, self.c2f, self.integrator, self.keepn, self.cal_mult, self.cal_offs, self.chart)
1167                 
1168                 #
1169                 # FFT scope gets only 1 channel
1170                 #  FIX THIS, by cross-correlating the *outputs* of two different FFTs, then display
1171                 #  Funky!
1172                 #
1173                 self.connect(self.shead, self.scope)
1174                 
1175                 #
1176                 # Output of correlator/integrator chain to probe
1177                 #
1178                 self.connect(self.cal_offs, self.probe)
1179                 
1180                 return
1181         
1182         #
1183         # Setup SETI mode
1184         #
1185         def setup_seti(self):
1186                 self.connect (self.shead, self.fft_bandpass, self.scope)
1187                 return
1188
1189                 
1190
1191 def main ():
1192         app = stdgui2.stdapp(app_flow_graph, "RADIO ASTRONOMY SPECTRAL/CONTINUUM RECEIVER: $Revision$", nstatus=1)
1193         app.MainLoop()
1194
1195 if __name__ == '__main__':
1196         main ()