예제 #1
0
class RoachInterface(object):
    """
    Base class for readout systems.

    These methods define an abstract interface that can be relied on to be consistent between the baseband and
    heterodyne readout systems.
    """

    BYTES_PER_SAMPLE = 4
    MEMORY_SIZE_BYTES = None  # Subclasses should give the appropriate value

    def __init__(self,
                 roach=None,
                 roachip='roach',
                 adc_valon=None,
                 host_ip=None,
                 nfs_root='/srv/roach_boot/etch',
                 lo_valon=None):
        """
        Abstract class to represent readout system

        roach: an FpgaClient instance for communicating with the ROACH.
                If not specified, will try to instantiate one connected to *roachip*
        roachip: (optional). Network address of the ROACH if you don't want to provide an FpgaClient
        adc_valon: a Valon class, a string, or None
                Provide access to the Valon class which controls the Valon synthesizer which provides
                the ADC and DAC sampling clock.
                The default None value will use the valon.find_valon function to locate a synthesizer
                and create a Valon class for you.
                You can alternatively pass a string such as '/dev/ttyUSB0' to specify the port for the
                synthesizer, which will then be used for creating a Valon class.
                Finally, for test suites, you can directly pass a Valon class or a class with the same
                interface.
        host_ip: Override IP address to which the ROACH should send it's data. If left as None,
                the host_ip will be set appropriately based on the HOSTNAME.
        """
        self.is_roach2 = False
        self._using_mock_roach = False
        if roach:
            self.r = roach
            # Check if we're using a fake ROACH for testing. If so, disable additional externalities
            # This logic could be made more general if desired (i.e. has attribute mock
            #  or type name matches regex including 'mock'
            if type(roach) is MockRoach:
                self._using_mock_roach = True
        else:  # pragma: no cover
            from corr.katcp_wrapper import FpgaClient
            logger.debug("Creating FpgaClient")
            self.r = FpgaClient(roachip)
            t1 = time.time()
            timeout = 10
            logger.debug("Waiting for connection to ROACH")
            while not self.r.is_connected():
                if (time.time() - t1) > timeout:
                    raise Exception("Connection timeout to roach")
                time.sleep(0.1)
            logger.debug("ROACH is connected")

        if adc_valon is None:  # pragma: no cover
            from kid_readout.roach import valon
            ports = valon.find_valons()
            if len(ports) == 0:
                self.adc_valon_port = None
                self.adc_valon = None
                logger.warn(
                    "Warning: No valon found! You will not be able to change or verify the sampling frequency"
                )
            else:
                for port in ports:
                    try:
                        self.adc_valon_port = port
                        self.adc_valon = valon.Synthesizer(port)
                        f = self.adc_valon.get_frequency_a()
                        break
                    except:
                        pass
        elif type(adc_valon) is str:  # pragma: no cover
            from kid_readout.roach import valon
            self.adc_valon_port = adc_valon
            self.adc_valon = valon.Synthesizer(self.adc_valon_port)
        else:
            self.adc_valon = adc_valon

        if type(lo_valon) is str:  # pragma: no cover
            from kid_readout.roach import valon
            self.lo_valon_port = lo_valon
            self.lo_valon = valon.Synthesizer(self.lo_valon_port)
        else:
            self.lo_valon = lo_valon

        if host_ip is None:  # pragma: no cover
            hostname = socket.gethostname()
            if hostname == 'detectors':
                host_ip = '192.168.1.1'
            else:
                host_ip = '192.168.1.1'
        self.host_ip = host_ip
        self.roachip = roachip
        self.nfs_root = nfs_root
        self._config_file_name = CONFIG_FILE_NAME_TEMPLATE % self.roachip

        self.adc_atten = 31.5
        self.dac_atten = -1
        self.fft_gain = 0
        self.fft_bins = None
        self.tone_nsamp = None
        self.tone_bins = None
        self.phases = None
        self.amps = None
        self.readout_selection = None
        self.modulation_output = 0
        self.modulation_rate = 0
        self.wavenorm = None
        self.phase0 = None

        self.loopback = None
        self.debug_register = None

        # Things to be configured by subclasses
        self.lo_frequency = 0.0
        self.iq_delay = 0
        self.heterodyne = False
        self.bof_pid = None
        self.boffile = None
        self.wafer = None
        self.raw_adc_ns = 2**12  # number of samples in the raw ADC buffer
        self.nfft = None
        # Boffile specific register names
        self._fpga_output_buffer = None

    def _general_setup(self):
        """
        Intended to be called after or at the end of subclass __init__
        """
        self._window_mag = tools.compute_window(npfb=2 * self.nfft,
                                                taps=2,
                                                wfunc=scipy.signal.flattop)
        try:
            self.hardware_delay_estimate = tools.boffile_delay_estimates[
                self.boffile]
        except KeyError:
            self.hardware_delay_estimate = tools.get_delay_estimate_for_nfft(
                self.nfft, self.heterodyne)

        try:
            self.fs = self.adc_valon.get_frequency_a()
        except:
            logger.warn("Couldn't get valon frequency, assuming 512 MHz")
            self.fs = 512.0
        self.bank = self.get_current_bank()

    # FPGA Functions
    def _update_bof_pid(self):
        if self.is_roach2:
            return
        if self.bof_pid:
            return
        if not self._using_mock_roach:
            try:
                self.bof_pid = borph_utils.get_bof_pid(self.roachip)
            except Exception, e:
                self.bof_pid = None
예제 #2
0
class SinglePixelHeterodyne(SinglePixelReadout):
    def __init__(self,roach=None,roachip='roach',adc_valon = None):
        """
        Class to represent the heterodyne readout system (high frequency, 1.5 GHz, with IQ mixers)
        
        roach: an FpgaClient instance for communicating with the ROACH. If not specified,
                will try to instantiate one connected to *roachip*
        roachip: (optional). Network address of the ROACH if you don't want to provide an FpgaClient
        """
        if roach:
            self.r = roach
        else:
            from corr.katcp_wrapper import FpgaClient
            self.r = FpgaClient(roachip)
            t1 = time.time()
            timeout = 10
            while not self.r.is_connected():
                if (time.time()-t1) > timeout:
                    raise Exception("Connection timeout to roach")
                time.sleep(0.1)
        
        if adc_valon is None:
            import valon
            ports = valon.find_valons()
            if len(ports) == 0:
                raise Exception("No Valon found!")
            self.adc_valon_port = ports[0]
            self.adc_valon = valon.Synthesizer(ports[0]) #use latest port
        elif type(adc_valon) is str:
            import valon
            self.adc_valon_port = adc_valon
            self.adc_valon = valon.Synthesizer(self.adc_valon_port)
        else:
            self.adc_valon = adc_valon
            
        self.fs = self.adc_valon.get_frequency_a()        
        self.dac_ns = 2**16 # number of samples in the dac buffer
        self.raw_adc_ns = 2**11 # number of samples in the raw ADC buffer
        self.nfft = 2**14
        self.boffile = 'iqx2fft14dac14r1_2013_Jun_24_1921.bof'
        
    def set_channel(self,ch,dphi=-0.25,amp=-3):
        """
        ch: channel number (-dac_ns/2 to dac_ns/2-1)
        dphi: phase offset between I and Q components in turns (nominally -1/4 = pi/2 radians)
        amp: amplitude relative to full scale in dB
        nfft: size of the fft
        """
        self.set_tone(ch/(1.0*self.dac_ns), dphi=dphi, amp=amp)
        absch = np.abs(ch)
        chan_per_bin = self.dac_ns/self.nfft
        ibin = absch // chan_per_bin
        if ch < 0:
            ibin = self.nfft-ibin       
        self.select_bin(int(ibin))
        
    def get_data(self,nread=10):
        """
        Get a stream of data from a single FFT bin
        
        nread: number of 4096 sample frames to read
        
        returns  dout,addrs

        dout: complex data stream. Real and imaginary parts are each 16 bit signed 
                integers (but cast to numpy complex)

        addrs: counter values when each frame was read. Can be used to check that 
                frames are contiguous
        """
        bufname = 'ppout'
        return self._read_data(nread, bufname)
        
    def load_waveform(self,iwave,qwave):
        if len(iwave) != self.dac_ns or len(qwave) != self.dac_ns:
            raise Exception("Waveforms should be %d samples long" % self.dac_ns)
        iw2 = iwave.astype('>i2').tostring()
        qw2 = qwave.astype('>i2').tostring()
    
        self.r.blindwrite('iout',iw2)
        self.r.blindwrite('qout',qw2)
            
        self.r.write_int('dacctrl',0)
        self.r.write_int('dacctrl',1)
        
    def set_tone(self,f0,dphi=0.25,amp=-3):
        a = 10**(amp/20.0)
        if a > 0.9999:
            print "warning: clipping amplitude to 0.9999"
            a = 0.9999
        swr = (2**15)*a*np.cos(2*np.pi*(f0*np.arange(self.dac_ns)))
        swi = (2**15)*a*np.cos(2*np.pi*(dphi+f0*np.arange(self.dac_ns)))
        self.load_waveform(swr,swi)
        
    def select_bin(self,ibin):
        """
        Set the register which selects the FFT bin we get data from
        
        ibin: 0 to nfft -1
        """
        self.r.write_int('chansel',ibin)
    
    def _set_fs(self,fs,chan_spacing=2.0):
        """
        Set sampling frequency in MHz
        Note, this should generally not be called without also reprogramming the ROACH
        Use initialize() instead
        """
        self.adc_valon.set_frequency_a(fs,chan_spacing=chan_spacing)
        self.fs = fs
예제 #3
0
class SinglePixelBaseband(SinglePixelReadout):
    def __init__(self,roach=None,wafer=0,roachip='roach',adc_valon=None):
        """
        Class to represent the baseband readout system (low-frequency (150 MHz), no mixers)
        
        roach: an FpgaClient instance for communicating with the ROACH. 
                If not specified, will try to instantiate one connected to *roachip*
        wafer: 0 or 1. 
                In baseband mode, each of the two DAC and ADC connections can be used independantly to
                readout a single wafer each. This parameter indicates which connection you want to use.
        roachip: (optional). Network address of the ROACH if you don't want to provide an FpgaClient
        adc_valon: a Valon class, a string, or None
                Provide access to the Valon class which controls the Valon synthesizer which provides
                the ADC and DAC sampling clock.
                The default None value will use the valon.find_valon function to locate a synthesizer
                and create a Valon class for you.
                You can alternatively pass a string such as '/dev/ttyUSB0' to specify the port for the
                synthesizer, which will then be used for creating a Valon class.
                Finally, for test suites, you can directly pass a Valon class or a class with the same
                interface.
        """
        if roach:
            self.r = roach
        else:
            from corr.katcp_wrapper import FpgaClient
            self.r = FpgaClient(roachip)
            t1 = time.time()
            timeout = 10
            while not self.r.is_connected():
                if (time.time()-t1) > timeout:
                    raise Exception("Connection timeout to roach")
                time.sleep(0.1)
                
        if adc_valon is None:
            import valon
            ports = valon.find_valons()
            if len(ports) == 0:
                raise Exception("No Valon found!")
            self.adc_valon_port = ports[0]
            self.adc_valon = valon.Synthesizer(ports[0]) #use latest port
        elif type(adc_valon) is str:
            import valon
            self.adc_valon_port = adc_valon
            self.adc_valon = valon.Synthesizer(self.adc_valon_port)
        else:
            self.adc_valon = adc_valon
            
        self.fs = self.adc_valon.get_frequency_a()
        self.wafer = wafer
        self.dac_ns = 2**16 # number of samples in the dac buffer
        self.raw_adc_ns = 2**12 # number of samples in the raw ADC buffer
        self.nfft = 2**14
#        self.boffile = 'adcdac2xfft14r4_2013_Jun_13_1717.bof'
        self.boffile = 'adcdac2xfft14r5_2013_Jun_18_1542.bof'
        self.bufname = 'ppout%d' % wafer
    def set_channel(self,ch,dphi=None,amp=-3):
        """
        ch: channel number (0 to dac_ns-1)

        dphi: phase offset between I and Q components in turns (nominally 1/4 = pi/2 radians)
                not used for Baseband readout

        amp: amplitude relative to full scale in dB

        nfft: size of the fft
        """
        self.set_tone(ch/(1.0*self.dac_ns), dphi=dphi, amp=amp)
        absch = np.abs(ch)
        chan_per_bin = (self.dac_ns/self.nfft)/2 # divide by 2 because it's a real signal
        ibin = absch // chan_per_bin
#        if ch < 0:
#            ibin = nfft-ibin       
        self.select_bin(int(ibin))
        
    def get_data(self,nread=10):
        """
        Get a stream of data from a single FFT bin
        
        nread: number of 4096 sample frames to read
        
        returns  dout,addrs

        dout: complex data stream. Real and imaginary parts are each 16 bit signed 
                integers (but cast to numpy complex)

        addrs: counter values when each frame was read. Can be used to check that 
                frames are contiguous
        """
        bufname = 'ppout%d' % self.wafer
        return self._read_data(nread, bufname)
        
    def load_waveform(self,wave):
        if len(wave) != self.dac_ns:
            raise Exception("Waveform should be %d samples long" % self.dac_ns)
        w2 = wave.astype('>i2').tostring()
        if self.wafer == 0:
            self.r.blindwrite('iout',w2)
        else:
            self.r.blindwrite('qout',w2)
            
        self.r.write_int('dacctrl',0)
        self.r.write_int('dacctrl',1)
        
    def set_tone(self,f0,dphi=None,amp=-3):
        if dphi:
            print "warning: got dphi parameter in set_tone; ignoring for baseband readout"
        a = 10**(amp/20.0)
        if a > 0.9999:
            print "warning: clipping amplitude to 0.9999"
            a = 0.9999
        swr = (2**15)*a*np.cos(2*np.pi*(f0*np.arange(self.dac_ns)))
        self.load_waveform(swr)
        
    def select_bin(self,ibin):
        """
        Set the register which selects the FFT bin we get data from
        
        ibin: 0 to nfft -1
        """
        offset = 2 # bins are shifted by 2
        ibin = np.mod(ibin-offset,self.nfft)
        self.r.write_int('chansel',ibin)
    
    def _set_fs(self,fs,chan_spacing=2.0):
        """
        Set sampling frequency in MHz
        Note, this should generally not be called without also reprogramming the ROACH
        Use initialize() instead        
        """
        self.adc_valon.set_frequency_a(fs,chan_spacing=chan_spacing)
        self.fs = fs
예제 #4
0
class KatcpCatcher():
    def __init__(self, proc_func, bufname, roachip='roach'):
        self.bufname = bufname
        self.data_thread = None
        self.proc_func = proc_func
        from corr.katcp_wrapper import FpgaClient
        self.data_thread_r = FpgaClient(roachip, timeout=0.1)
        t1 = time.time()
        timeout = 10
        while not self.data_thread_r.is_connected():
            if (time.time() - t1) > timeout:
                raise Exception("Connection timeout to roach")
            time.sleep(0.1)
            
        self.last_addr = 0


    def start_data_thread(self):
        if self.data_thread:
            self.quit_data_thread = True
            self.data_thread.join(1.0)
            self.data_thread = None
        self.quit_data_thread = False
        self.data_thread = threading.Thread(target=self._cont_read_data, args=())
        # IMPORTANT - where cont_read_data comes in
        self.data_thread.daemon = True
        self.data_thread.start()
        
    def _proc_raw_data(self, data, addr):
        if addr - self.last_addr > 8192:
            print "skipped:", addr, self.last_addr, (addr - self.last_addr)
        self.last_addr = addr 
        data = np.fromstring(data, dtype='>i2').astype('float32').view('complex64')
        self.pxx = (np.abs(np.fft.fft(data.reshape((-1, 1024)), axis=1)) ** 2).mean(0)
        
    def _cont_read_data(self):
        """
        Low level data reading loop. Reads data continuously and passes it to self.proc_func
        """
        regname = '%s_addr' % self.bufname
        brama = '%s_a' % self.bufname
        bramb = '%s_b' % self.bufname
        r = self.data_thread_r
        a = r.read_uint(regname) & 0x1000
        addr = r.read_uint(regname) 
        b = addr & 0x1000
        while a == b:
            addr = r.read_uint(regname)
            b = addr & 0x1000
        data = []
        addrs = []
        tic = time.time()
        idle = 0
        while not self.quit_data_thread:
            a = b
            if a:
                bram = brama
            else:
                bram = bramb
            data = r.read(bram, 4 * 2 ** 12)
            self.proc_func(data, addr)
            # Where proc_func comes in
            # coord passes self.aggregator.proc_raw_data as the proc_func here.
            
            addr = r.read_uint(regname)
            b = addr & 0x1000
            while (a == b) and not self.quit_data_thread:
                try:
                    addr = r.read_uint(regname)
                    b = addr & 0x1000
                    idle += 1
                except Exception, e:
                    print e
                time.sleep(0.1)
        else:
예제 #5
0
class RoachBaseband(RoachInterface):
    def __init__(self,roach=None,wafer=0,roachip='roach',adc_valon=None):
        """
        Class to represent the baseband readout system (low-frequency (150 MHz), no mixers)
        
        roach: an FpgaClient instance for communicating with the ROACH. 
                If not specified, will try to instantiate one connected to *roachip*
        wafer: 0 or 1. 
                In baseband mode, each of the two DAC and ADC connections can be used independantly to
                readout a single wafer each. This parameter indicates which connection you want to use.
        roachip: (optional). Network address of the ROACH if you don't want to provide an FpgaClient
        adc_valon: a Valon class, a string, or None
                Provide access to the Valon class which controls the Valon synthesizer which provides
                the ADC and DAC sampling clock.
                The default None value will use the valon.find_valon function to locate a synthesizer
                and create a Valon class for you.
                You can alternatively pass a string such as '/dev/ttyUSB0' to specify the port for the
                synthesizer, which will then be used for creating a Valon class.
                Finally, for test suites, you can directly pass a Valon class or a class with the same
                interface.
        """
        if roach:
            self.r = roach
        else:
            from corr.katcp_wrapper import FpgaClient
            self.r = FpgaClient(roachip)
            t1 = time.time()
            timeout = 10
            while not self.r.is_connected():
                if (time.time()-t1) > timeout:
                    raise Exception("Connection timeout to roach")
                time.sleep(0.1)
                
        if adc_valon is None:
            import valon
            ports = valon.find_valons()
            if len(ports) == 0:
                raise Exception("No Valon found!")
            for port in ports:
                try:
                    self.adc_valon_port = port
                    self.adc_valon = valon.Synthesizer(port)
                    f = self.adc_valon.get_frequency_a()
                    break
                except:
                    pass
        elif type(adc_valon) is str:
            import valon
            self.adc_valon_port = adc_valon
            self.adc_valon = valon.Synthesizer(self.adc_valon_port)
        else:
            self.adc_valon = adc_valon
        
        self.adc_atten = -1
        self.dac_atten = -1
        self.bof_pid = None
        self.roachip = roachip
        self.fs = self.adc_valon.get_frequency_a()
        self.wafer = wafer
        self.dac_ns = 2**16 # number of samples in the dac buffer
        self.raw_adc_ns = 2**12 # number of samples in the raw ADC buffer
        self.nfft = 2**14
        self.boffile = 'bb2xpfb14mcr5_2013_Jul_31_1301.bof'
        self.bufname = 'ppout%d' % wafer

    def load_waveform(self,wave,fast=True):
        """
        Load waveform
        
        wave : array of 16-bit (dtype='i2') integers with waveform
        
        fast : boolean
            decide what method for loading the dram 
        """
        data = np.zeros((2*wave.shape[0],),dtype='>i2')
        offset = self.wafer*2
        data[offset::4] = wave[::2]
        data[offset+1::4] = wave[1::2]
        self.r.write_int('dram_mask', data.shape[0]/4 - 1)
        self._load_dram(data,fast=fast)
        
    def set_tone_freqs(self,freqs,nsamp,amps=None):
        """
        Set the stimulus tones to generate
        
        freqs : array of frequencies in MHz
            For baseband system, these must be positive
        nsamp : int, must be power of 2
            number of samples in the playback buffer. Frequency resolution will be fs/nsamp
        amps : optional array of floats, same length as freqs array
            specify the relative amplitude of each tone. Can set to zero to read out a portion
            of the spectrum with no stimulus tone.
                    
        returns:
        actual_freqs : array of the actual frequencies after quantization based on nsamp
        """        
        bins = np.round((freqs/self.fs)*nsamp).astype('int')
        actual_freqs = self.fs*bins/float(nsamp)
        self.set_tone_bins(bins, nsamp,amps=amps)
        self.fft_bins = self.calc_fft_bins(bins, nsamp)
        if self.fft_bins.shape[0] > 8:
            readout_selection = range(8)
        else:
            readout_selection = range(self.fft_bins.shape[0])   
            
        self.select_fft_bins(readout_selection)
        return actual_freqs

    def set_tone_bins(self,bins,nsamp,amps=None):
        """
        Set the stimulus tones by specific integer bins
        
        bins : array of bins at which tones should be placed
            For Heterodyne system, negative frequencies should be placed in cannonical FFT order
        nsamp : int, must be power of 2
            number of samples in the playback buffer. Frequency resolution will be fs/nsamp
        amps : optional array of floats, same length as bins array
            specify the relative amplitude of each tone. Can set to zero to read out a portion
            of the spectrum with no stimulus tone.
        """
        
        spec = np.zeros((nsamp/2+1,),dtype='complex')
        self.tone_bins = bins.copy()
        self.tone_nsamp = nsamp
        phases = np.random.random(len(bins))*2*np.pi
        self.phases = phases.copy()
        if amps is None:
            amps = 1.0
        self.amps = amps
        spec[bins] = amps*np.exp(1j*phases)
        wave = np.fft.irfft(spec)
        self.wavenorm = np.abs(wave).max()
        qwave = np.round((wave/self.wavenorm)*(2**15-1024)).astype('>i2')
        self.qwave = qwave
        self.load_waveform(qwave)
        
    def calc_fft_bins(self,tone_bins,nsamp):
        """
        Calculate the FFT bins in which the tones will fall
        
        tone_bins : array of integers
            the tone bins (0 to nsamp - 1) which contain tones
        
        nsamp : length of the playback bufffer
        
        returns : fft_bins, array of integers. 
        """
        
        tone_bins_per_fft_bin = nsamp/(2*self.nfft) # factor of 2 because real signal
        fft_bins = np.round(tone_bins/float(tone_bins_per_fft_bin)).astype('int')
        return fft_bins
    
    def fft_bin_to_index(self,bins):
        """
        Convert FFT bins to FPGA indexes
        """
        top_half = bins > self.nfft/2
        idx = bins.copy()
        idx[top_half] = self.nfft - bins[top_half] + self.nfft/2
        return idx
        
    def select_fft_bins(self,readout_selection):
        """
        Select which subset of the available FFT bins to read out
        
        Initially we can only read out from a subset of the FFT bins, so this function selects which bins to read out right now
        This also takes care of writing the selection to the FPGA with the appropriate tweaks
        
        The readout selection is stored to self.readout_selection
        The FPGA readout indexes is stored in self.fpga_fft_readout_indexes
        The bins that we are reading out is stored in self.readout_fft_bins
        
        readout_selection : array of ints
            indexes into the self.fft_bins array to specify the bins to read out
        """
        offset = 2
        idxs = self.fft_bin_to_index(self.fft_bins[readout_selection])
        order = idxs.argsort()
        idxs = idxs[order]
        self.readout_selection = np.array(readout_selection)[order]
        self.fpga_fft_readout_indexes = idxs
        self.readout_fft_bins = self.fft_bins[self.readout_selection]

        binsel = np.zeros((self.fpga_fft_readout_indexes.shape[0]+1,),dtype='>i4')
        binsel[:-1] = np.mod(self.fpga_fft_readout_indexes-offset,self.nfft)
        binsel[-1] = -1
        self.r.write('chans',binsel.tostring())
        
    def demodulate_data(self,data):
        """
        Demodulate the data from the FFT bin
        
        This function assumes that self.select_fft_bins was called to set up the necessary class attributes
        
        data : array of complex data
        
        returns : demodulated data in an array of the same shape and dtype as *data*
        """
        demod = np.zeros_like(data)
        t = np.arange(data.shape[0])
        for n,ich in enumerate(self.readout_selection):
            phi0 = self.phases[ich]
            k = self.tone_bins[ich]
            m = self.fft_bins[ich]
            if m >= self.nfft/2:
                sign = 1.0
            else:
                sign = -1.0
            nfft = self.nfft
            ns = self.tone_nsamp
            foffs = (2*k*nfft - m*ns)/float(ns)
            demod[:,n] = np.exp(sign*1j*(2*np.pi*foffs*t + phi0)) * data[:,n]
            if m >= self.nfft/2:
                demod[:,n] = np.conjugate(demod[:,n])
        return demod
                
    def get_data(self,nread=10,demod=True):
        """
        Get a chunk of data
        
        nread: number of 4096 sample frames to read
        
        demod: should the data be demodulated before returning? Default, yes
        
        returns  dout,addrs

        dout: complex data stream. Real and imaginary parts are each 16 bit signed
            integers (but cast to numpy complex)

        addrs: counter values when each frame was read. Can be used to check that
            frames are contiguous
        """

        bufname = 'ppout%d' % self.wafer
        chan_offset = 1
        draw,addr,ch =  self._read_data(nread, bufname)
        if not np.all(ch == ch[0]):
            print "all channel registers not the same; this case not yet supported"
            return draw,addr,ch
        if not np.all(np.diff(addr)<8192):
            print "address skip!"
        nch = self.readout_selection.shape[0]
        dout = draw.reshape((-1,nch))
        shift = np.flatnonzero(self.fpga_fft_readout_indexes==(ch[0]-chan_offset))[0] - (nch-1)
        print shift
        dout = np.roll(dout,shift,axis=1)
        if demod:
            dout = self.demodulate_data(dout)
        return dout,addr
    
    def _set_fs(self,fs,chan_spacing=2.0):
        """
        Set sampling frequency in MHz
        Note, this should generally not be called without also reprogramming the ROACH
        Use initialize() instead        
        """
        self.adc_valon.set_frequency_a(fs,chan_spacing=chan_spacing)    # for now the baseband readout uses both valon outputs,
        self.adc_valon.set_frequency_b(fs,chan_spacing=chan_spacing)    # one for ADC, one for DAC
        self.fs = fs
예제 #6
0
class RoachInterface(object):
    """
    Base class for readout systems.

    These methods define an abstract interface that can be relied on to be consistent between the baseband and
    heterodyne readout systems.
    """

    def __init__(self, roach=None, roachip='roach', adc_valon=None, host_ip=None,
                 nfs_root='/srv/roach_boot/etch', lo_valon=None):
        """
        Abstract class to represent readout system

        roach: an FpgaClient instance for communicating with the ROACH.
                If not specified, will try to instantiate one connected to *roachip*
        roachip: (optional). Network address of the ROACH if you don't want to provide an FpgaClient
        adc_valon: a Valon class, a string, or None
                Provide access to the Valon class which controls the Valon synthesizer which provides
                the ADC and DAC sampling clock.
                The default None value will use the valon.find_valon function to locate a synthesizer
                and create a Valon class for you.
                You can alternatively pass a string such as '/dev/ttyUSB0' to specify the port for the
                synthesizer, which will then be used for creating a Valon class.
                Finally, for test suites, you can directly pass a Valon class or a class with the same
                interface.
        host_ip: Override IP address to which the ROACH should send it's data. If left as None,
                the host_ip will be set appropriately based on the HOSTNAME.
        """
        self.is_roach2 = False
        self._using_mock_roach = False
        if roach:
            self.r = roach
            # Check if we're using a fake ROACH for testing. If so, disable additional externalities
            # This logic could be made more general if desired (i.e. has attribute mock
            #  or type name matches regex including 'mock'
            if type(roach) is MockRoach:
                self._using_mock_roach = True
        else:  # pragma: no cover
            from corr.katcp_wrapper import FpgaClient
            logger.debug("Creating FpgaClient")
            self.r = FpgaClient(roachip)
            t1 = time.time()
            timeout = 10
            logger.debug("Waiting for connection to ROACH")
            while not self.r.is_connected():
                if (time.time() - t1) > timeout:
                    raise Exception("Connection timeout to roach")
                time.sleep(0.1)
            logger.debug("ROACH is connected")

        if adc_valon is None:  # pragma: no cover
            from kid_readout.roach import valon
            ports = valon.find_valons()
            if len(ports) == 0:
                self.adc_valon_port = None
                self.adc_valon = None
                logger.warn("Warning: No valon found! You will not be able to change or verify the sampling frequency")
            else:
                for port in ports:
                    try:
                        self.adc_valon_port = port
                        self.adc_valon = valon.Synthesizer(port)
                        f = self.adc_valon.get_frequency_a()
                        break
                    except:
                        pass
        elif type(adc_valon) is str: # pragma: no cover
            from kid_readout.roach import valon
            self.adc_valon_port = adc_valon
            self.adc_valon = valon.Synthesizer(self.adc_valon_port)
        else:
            self.adc_valon = adc_valon

        if type(lo_valon) is str: # pragma: no cover
            from kid_readout.roach import valon
            self.lo_valon_port = lo_valon
            self.lo_valon = valon.Synthesizer(self.lo_valon_port)
        else:
            self.lo_valon = lo_valon

        if host_ip is None: # pragma: no cover
            hostname = socket.gethostname()
            if hostname == 'detectors':
                host_ip = '192.168.1.1'
            else:
                host_ip = '192.168.1.1'
        self.host_ip = host_ip
        self.roachip = roachip
        self.nfs_root = nfs_root
        self._config_file_name = CONFIG_FILE_NAME_TEMPLATE % self.roachip

        self.adc_atten = 31.5
        self.dac_atten = -1
        self.fft_gain = 0
        self.fft_bins = None
        self.tone_nsamp = None
        self.tone_bins = None
        self.phases = None
        self.amps = None
        self.readout_selection = None
        self.modulation_output = 0
        self.modulation_rate = 0
        self.wavenorm = None
        self.phase0 = None

        self.loopback = None
        self.debug_register = None

        # Things to be configured by subclasses
        self.lo_frequency = 0.0
        self.iq_delay = 0
        self.heterodyne = False
        self.bof_pid = None
        self.boffile = None
        self.wafer = None
        self.raw_adc_ns = 2 ** 12  # number of samples in the raw ADC buffer
        self.nfft = None
        # Boffile specific register names
        self._fpga_output_buffer = None


    def _general_setup(self):
        """
        Intended to be called after or at the end of subclass __init__
        """
        self._window_mag = tools.compute_window(npfb=2 * self.nfft, taps=2, wfunc=scipy.signal.flattop)
        try:
            self.hardware_delay_estimate = tools.boffile_delay_estimates[self.boffile]
        except KeyError:
            self.hardware_delay_estimate = tools.get_delay_estimate_for_nfft(self.nfft,self.heterodyne)

        try:
            self.fs = self.adc_valon.get_frequency_a()
        except:
            logger.warn("Couldn't get valon frequency, assuming 512 MHz")
            self.fs = 512.0
        self.bank = self.get_current_bank()

    # FPGA Functions
    def _update_bof_pid(self):
        if self.is_roach2:
            return
        if self.bof_pid:
            return
        if not self._using_mock_roach:
            try:
                self.bof_pid = borph_utils.get_bof_pid(self.roachip)
            except Exception, e:
                self.bof_pid = None