#! /usr/bin/env python
#
# getgpibdata.py
#
# This script will get data from an Agilent 4395A network analyzer
# and spits out the data into standard output.
# The output format is a space delimited list, each row representing a frequency point.
# The meanings of columns are:
#<Network analyzer mode>
# freq  real  imag  
#<Spectrum analyzer mode>
# freq  mag1  [mag2]
# mag2 is present only when the dual channel mode is active. 
#
# Yoichi Aso  Aug 26 2008

import re
import Gpib
device = Gpib.Gpib("ag4395a")  

#Put the analyzer on hold
device.write("HOLD")    

#Get the number of data points
device.write("POIN?")    
numPoints = device.read(30)
numPoints = int(numPoints)

#Set the output format to ASCII
device.write("FORM4")

#Get the frequency points
device.write("OUTPSWPRM?")    
freq = device.read(23*numPoints)

#Break the data into lists
freqList = re.findall(r'[-+.E0-9]+',freq)

#Check for the analyzer mode
device.write("NA?") 
analyzerMode = int(device.read())

if analyzerMode == 1:
    # It is the network analyzer mode    
    # In this mode, the data format is real,imag for each frequency point
    #Get the data
    device.write("OUTPDATA?")
    data=device.read(15*numPoints*2);

    #Break the data into lists
    dataList = re.findall(r'[-+.E0-9]+',data)

    # Print data
    j=0;
    for i in range(len(freqList)):
        print freqList[i], dataList[j], dataList[j+1]
        j=j+2;

else:
    # It is spectrum analyzer mode

    #Check if it is the dual channel mode or not
    device.write('DUAC?')
    numOfChan = int(device.read()) +1

    #Get the data
    dataList=[]
    for i in range(1,numOfChan+1):
        device.write("OUTPDATA?")
        data=device.read(15*numPoints)
        #Break into elements
        data=re.findall(r'[-+.E0-9]+',data)
        #Append to dataList
        dataList.append(data)

    # Print data
    for i in range(len(freqList)):
        print freqList[i],
        for j in range(0, numOfChan):
            print dataList[j][i],
        
        print



#Resume the measurement
device.write("CONT")    

