コード例 #1
0
    def __init__(self):
        QObject.__init__(self)
        self._name = ''
        self._scope = []
        self._settings = {}

        self._daq = None

        self._sigin = 0
        self._sigout = 0
        self._scope_time = 1

        self._tc = 0
        self._freq = 0
        self._rate = 0

        try:
            port, apilevel = self._discover()
            self.server = ziPython.ziDAQServer('localhost', port, apilevel)
            self.server.connect()

            msg = self._load_settings()
            self.server.set(self._settings['server'])
            self.server.sync()

            self._get_config()

            self._daq = self.server.dataAcquisitionModule()

            self.last_action = 'Lockin found, %s' % (msg)
        except Exception as e:
            self.last_action = str(e)
コード例 #2
0
ファイル: connection.py プロジェクト: katetsu/zhinst-toolkit
    def connect(self):
        """Established a connection to the data server. 
        
        Uses the connection details (host, port, api level) specified in the 
        'connection_details' to open a `zi.ziDAQServer` data server object that
        is used for all communication to the data server.

        Raises:
            ToolkitConnectionError: if connection to the Data Server could not 
                be established

        """
        try:
            self._daq = zi.ziDAQServer(
                self._connection_details.host,
                self._connection_details.port,
                self._connection_details.api,
            )
        except RuntimeError:
            raise ToolkitConnectionError(
                f"No connection could be established with the connection details:"
                f"{self._connection_details}")
        if self._daq is not None:
            print(f"Successfully connected to data server at "
                  f"{self._connection_details.host}:"
                  f"{self._connection_details.port} "
                  f"api version: {self._connection_details.api}")
            self._awg_module = AWGModuleConnection(self._daq)
            self._daq_module = DAQModuleConnection(self._daq)
            self._sweeper_module = SweeperModuleConnection(self._daq)
        else:
            raise ToolkitConnectionError(
                f"No connection could be established with the connection details:"
                f"{self._connection_details}")
コード例 #3
0
ファイル: session.py プロジェクト: zhinst/zhinst-toolkit
    def create_shfqa_sweeper(self) -> tk_modules.SHFQASweeper:
        """Create an instance of the SHFQASweeper.

        For now the general sweeper module does not support the SHFQA. However a
        python based implementation called ``SHFSweeper`` does already provide
        this functionality. The ``SHFSweeper`` is part of the ``zhinst`` module
        and can be found in the utils.

        Toolkit wraps around the ``SHFSweeper`` and exposes a interface that is
        similar to the LabOne modules, meaning the parameters are exposed in a
        node tree like structure.

        In addition a new session is created. This has the benefit that the
        sweeper implementation does not interfere with the the commands and
        setups from the user.

        Returns:
            Created object
        """
        return tk_modules.SHFQASweeper(
            ziPython.ziDAQServer(
                self._server_host,
                self._server_port,
                6,
            ),
            self._session,
        )
コード例 #4
0
ファイル: zishell_NH.py プロジェクト: weiyangliu/PycQED_py3
    def reconnect(self):
        if not self.server:
            raise(ziShellServerError())

        host, port, api_level = self.server
        print("Connecting to server on host {0}:{1} using API level {2}".format(
            host, port, api_level))
        self.daq = zi.ziDAQServer(host, port, api_level)
コード例 #5
0
ファイル: mfli_driver.py プロジェクト: HasanDoha/place
    def __init__(self, device_name, ip_address, port=8004):
        api_level = 6
        self.device_name = device_name
        print(ip_address, port)
        self.daq_server = zi.ziDAQServer(ip_address, port, api_level)
        self.data_acq = self.daq_server.dataAcquisitionModule()
        self.channel_paths = []

        # Create a clean configuration
        zhinst.utils.disable_everything(self.daq_server, self.device_name)
コード例 #6
0
ファイル: zishell_NH.py プロジェクト: weiyangliu/PycQED_py3
    def connect_server(self, host, port=8004, api_level=5):
        self.server = (host, port, api_level)
        print("Connecting to server on host {0}:{1} using API level {2}".format(
            host, port, api_level))
        self.daq = zi.ziDAQServer(host, port, api_level)
        if not self.daq:
            raise(ziShellDAQError())

        # self.daq.setDebugLevel(5)
        self.connected = False

        if self.device and self.interface:
            self.connect_device(self.device, self.interface)
コード例 #7
0
    def __init__(self,
                 ip='127.0.0.1',
                 port=8004,
                 api_level=6,
                 device='dev2192',
                 iface='1GbE',
                 settings='PumpUnpumpBoxCar.xml',
                 repRate=1500,
                 timeOut=30):
        # Create a connection to a Zurich Instruments Data Server

        self.daq = zh.ziDAQServer(ip, port, api_level)
        self.device = device
        self.iface = iface
        # one could also use utils.autoConnect() instead
        self.daq.connectDevice(self.device, self.iface)
        self.daq.connect()
        # load settings
        settings_path = path.join(utils.get_default_settings_path(self.daq),
                                  settings)
        utils.load_settings(self.daq, self.device, settings_path)

        self.timeOut = timeOut
        self.acqStartTime = None
        self.acqEndTime = None
        self.isAcquiring = False

        # Detect a device
        #self.device = utils.autoDetect(self.daq)
        # Find out whether the device is an HF2 or a UHF
        self.devtype = self.daq.getByte('/%s/features/devtype' % self.device)
        self.options = self.daq.getByte('/%s/features/options' % self.device)
        self.clock = self.daq.getDouble('/%s/clockbase' % self.device)

        if not re.search('BOX', self.options):
            raise Exception(
                "This example can only be ran on a UHF with the BOX option enabled."
            )

        if self.daq.getConnectionAPILevel() != 6:
            warnings.warn("ziDAQServer is using API Level 1, it is strongly recommended " * \
                "to use API Level 6 in order to obtain boxcar data with timestamps.")

        self.daq.sync()

        self.daq.subscribe('/%s/boxcars/%d/sample' % (self.device, 0))
        self.daq.subscribe('/%s/boxcars/%d/sample' % (self.device, 1))
コード例 #8
0
 def __init__(self, dev_id=None, port=8005, api_level=1):
     object.__init__(self)
     #self.server=ziutils.autoConnect(port,api_level)
     for _ in range(5):
         try:
             self.server=zp.ziDAQServer('localhost',port,api_level)
             if self._get_server_devices():
                 break
         finally:
             time.sleep(5.) 
     if dev_id is None:
         devs=self._get_server_devices()
         if not devs:
             raise RuntimeError("No devices were detected")
         dev_id=devs[0]
     self.dev_id=dev_id
     self.ref_timestamp=0
コード例 #9
0
    def __init__(self,
                 ip='127.0.0.1',
                 port=8004,
                 api_level=6,
                 repRate=1500,
                 timeOut=30):
        # Create a connection to a Zurich Instruments Data Server

        print 'connecting ...'

        self.daq = zh.ziDAQServer(ip, port, api_level)
        self.daq.connect()
        self.timeOut = timeOut
        self.acqStartTime = None
        self.acqEndTime = None
        self.isAcquiring = False

        # Detect a device
        self.device = utils.autoDetect(self.daq)
        # Find out whether the device is an HF2 or a UHF
        self.devtype = self.daq.getByte('/%s/features/devtype' % self.device)
        self.options = self.daq.getByte('/%s/features/options' % self.device)
        self.clock = self.daq.getDouble('/%s/clockbase' % self.device)

        if not re.search('BOX', self.options):
            raise Exception(
                "This example can only be ran on a UHF with the BOX option enabled."
            )

        if self.daq.getConnectionAPILevel() != 6:
            warnings.warn("ziDAQServer is using API Level 1, it is strongly recommended " * \
                "to use API Level 6 in order to obtain boxcar data with timestamps.")

        self.daq.sync()

        self.daq.subscribe('/%s/boxcars/%d/sample' % (self.device, 0))
        self.daq.subscribe('/%s/boxcars/%d/sample' % (self.device, 1))

        print 'connected'
コード例 #10
0
ファイル: zurich.py プロジェクト: samueljamesbader/Nowack_Lab
    def __init__(self, server_address = 'localhost', server_port = 8005 ,
                    device_serial = '', in_channel = None, meas_type='V'):
            '''
            Creates the HF2LI object. By choosing server address, can connection
            to HF2LI on remote (local network) computer.
            Arguments:
            server_address (str,optional) = Private IPV4 address of the computer
                                hosting the zurich. Defults to 'localhost',
                                the computer the python kernel is running on.
            server_port (int, optional) = Port of Zurich HF2LI. For local is
                                always 8005 (default), usually 8006 for remote.
            device_serial (str, optional) = Serial number of prefered zurich
                                hf2li. If empty string or does not exist,
                                uses first avaliable ZI.
            in_channel: if None, will use both inputs (TODO). Else, choose input 1
                                or 2.
            meas_type: 'I' or 'V'. Choose whether this channel measures current
                                (via transimpedance amplifier) or voltage.
            '''

            super().__init__()

            self.daq = ziP.ziDAQServer(server_address, server_port)
            deviceList = utils.devices(self.daq)

            # Find device
            if device_serial in deviceList:
                self.device_id = device_serial
            elif device_serial != '':
                print('Requested device not found.')
            if self.device_id is None:
                self.device_id = utils.autoDetect(self.daq)  # first available
            print('Using Zurich HF2LI with serial %s' % self.device_id)

            if in_channel is None:
                raise Exception()
            self.in_channel = in_channel
            self.meas_type = meas_type
コード例 #11
0
    def __init__(self,
                 name,
                 device='auto',
                 interface='USB',
                 address='127.0.0.1',
                 port=8004,
                 DIO=True,
                 nr_integration_channels=9,
                 **kw):
        '''
        Input arguments:
            name:           (str) name of the instrument
            server_name:    (str) qcodes instrument server
            address:        (int) the address of the data server e.g. 8006
        '''
        # self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        # #suggestion W vlothuizen
        t0 = time.time()
        super().__init__(name, **kw)
        self.nr_integration_channels = nr_integration_channels
        self.DIO = DIO
        self._daq = zi.ziDAQServer(address, int(port), 5)
        # self._daq.setDebugLevel(5)
        if device.lower() == 'auto':
            self._device = zi_utils.autoDetect(self._daq)
        else:
            self._device = device
            self._daq.connectDevice(self._device, interface)
        #self._device = zi_utils.autoDetect(self._daq)
        self._awgModule = self._daq.awgModule()
        self._awgModule.set('awgModule/device', self._device)
        self._awgModule.execute()

        self.acquisition_paths = []

        s_node_pars = []
        d_node_pars = []

        path = os.path.abspath(__file__)
        dir_path = os.path.dirname(path)
        self._s_file_name = os.path.join(dir_path, 'zi_parameter_files',
                                         's_node_pars.txt')
        self._d_file_name = os.path.join(dir_path, 'zi_parameter_files',
                                         'd_node_pars.txt')

        init = True
        try:
            f = open(self._s_file_name).read()
            s_node_pars = json.loads(f)
        except:
            print("parameter file for gettable parameters {} not found".format(
                self._s_file_name))
            init = False
        try:
            f = open(self._d_file_name).read()
            d_node_pars = json.loads(f)
        except:
            print("parameter file for settable parameters {} not found".format(
                self._d_file_name))
            init = False

        self.add_parameter('timeout',
                           unit='s',
                           initial_value=30,
                           parameter_class=ManualParameter)
        for parameter in s_node_pars:
            parname = parameter[0].replace("/", "_")
            parfunc = "/" + self._device + "/" + parameter[0]
            if parameter[1] == 'float':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.setd, parfunc),
                    get_cmd=self._gen_get_func(self.getd, parfunc),
                    vals=vals.Numbers(parameter[2], parameter[3]))
            elif parameter[1] == 'float_small':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.setd, parfunc),
                    get_cmd=self._gen_get_func(self.getd, parfunc),
                    vals=vals.Numbers(parameter[2], parameter[3]))
            elif parameter[1] == 'int_8bit':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.seti, parfunc),
                    get_cmd=self._gen_get_func(self.geti, parfunc),
                    vals=vals.Ints(int(parameter[2]), int(parameter[3])))
            elif parameter[1] == 'int':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.seti, parfunc),
                    get_cmd=self._gen_get_func(self.geti, parfunc),
                    vals=vals.Ints(int(parameter[2]), int(parameter[3])))
            elif parameter[1] == 'int_64':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.seti, parfunc),
                    get_cmd=self._gen_get_func(self.geti, parfunc),
                    vals=vals.Ints(int(parameter[2]), int(parameter[3])))
            elif parameter[1] == 'bool':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.seti, parfunc),
                    get_cmd=self._gen_get_func(self.geti, parfunc),
                    vals=vals.Ints(int(parameter[2]), int(parameter[3])))
            else:
                print(
                    "parameter {} type {} from from s_node_pars not recognized"
                    .format(parname, parameter[1]))

        for parameter in d_node_pars:
            parname = parameter[0].replace("/", "_")
            parfunc = "/" + self._device + "/" + parameter[0]
            if parameter[1] == 'float':
                self.add_parameter(parname,
                                   get_cmd=self._gen_get_func(
                                       self.getd, parfunc))
            elif parameter[1] == 'vector_g':
                self.add_parameter(parname,
                                   get_cmd=self._gen_get_func(
                                       self.getv, parfunc))
            elif parameter[1] == 'vector_s':
                self.add_parameter(parname,
                                   set_cmd=self._gen_set_func(
                                       self.setv, parfunc),
                                   vals=vals.Anything())
            elif parameter[1] == 'vector_gs':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.setv, parfunc),
                    get_cmd=self._gen_get_func(self.getv, parfunc),
                    vals=vals.Anything())
            else:
                print("parameter {} type {} from d_node_pars not recognized".
                      format(parname, parameter[1]))

        self.add_parameter('AWG_file',
                           set_cmd=self._do_set_AWG_file,
                           vals=vals.Anything())
        # storing an offset correction parameter for all weight functions,
        # this allows normalized calibration when performing cross-talk suppressed
        # readout
        for i in range(self.nr_integration_channels):
            self.add_parameter(
                "quex_trans_offset_weightfunction_{}".format(i),
                unit='',  # unit is adc value
                label='RO normalization offset',
                initial_value=0.0,
                parameter_class=ManualParameter)
        if init:
            self.load_default_settings()
        t1 = time.time()

        print('Initialized UHFQC', self._device, 'in %.2fs' % (t1 - t0))
コード例 #12
0
#print "inside subprocess"

import sys, os
sys.path.append(os.path.dirname("/dls_sw/i10/scripts/"))

from zhinst import ziPython

print "after load zipython"

daq = ziPython.ziDAQServer('172.23.110.84', 8004)
sample = daq.getSample('/dev4206/demods/0/sample')
print sample

#print "end of subprocess"
コード例 #13
0
ファイル: session.py プロジェクト: zhinst/zhinst-toolkit
    def __init__(
        self,
        server_host: str,
        server_port: int = None,
        *,
        hf2: bool = None,
        connection: ziPython.ziDAQServer = None,
    ):
        self._is_hf2_server = bool(hf2)
        self._server_host = server_host
        self._server_port = server_port if server_port else 8004
        if connection is not None:
            self._is_hf2_server = "HF2" in connection.getString("/zi/about/dataserver")
            if hf2 and not self._is_hf2_server:
                raise RuntimeError(
                    "hf2_server Flag was set but the passed "
                    "DAQServer instance is no HF2 data server."
                )
            if hf2 is False and self._is_hf2_server:
                raise RuntimeError(
                    "hf2_server Flag was reset but the passed "
                    "DAQServer instance is a HF2 data server."
                )
            self._daq_server = connection
        else:
            if self._is_hf2_server and self._server_port == 8004:
                self._server_port = 8005
            try:
                self._daq_server = ziPython.ziDAQServer(
                    self._server_host,
                    self._server_port,
                    1 if self._is_hf2_server else 6,
                )
            except RuntimeError as error:
                if "Unsupported API level" not in error.args[0]:
                    raise
                if hf2 is None:
                    self._is_hf2_server = True
                    self._daq_server = ziPython.ziDAQServer(
                        self._server_host,
                        self._server_port,
                        1,
                    )
                elif not hf2:
                    raise RuntimeError(
                        "hf2_server Flag was reset but the specified "
                        f"server at {self._server_host}:{self._server_port} is a "
                        "HF2 data server."
                    ) from error

        if self._is_hf2_server and "HF2" not in self._daq_server.getString(
            "/zi/about/dataserver"
        ):
            raise RuntimeError(
                "hf2_server Flag was set but the specified "
                f"server at {self._server_host}:{self._server_port} is not a "
                "HF2 data server."
            )
        self._devices = HF2Devices(self) if self._is_hf2_server else Devices(self)
        self._modules = ModuleHandler(self, self._server_host, self._server_port)

        hf2_node_doc = Path(__file__).parent / "resources/nodedoc_hf2_data_server.json"
        nodetree = NodeTree(
            self.daq_server,
            prefix_hide="zi",
            list_nodes=["/zi/*"],
            preloaded_json=json.loads(hf2_node_doc.open("r").read())
            if self._is_hf2_server
            else None,
        )
        super().__init__(nodetree, tuple())
コード例 #14
0
ファイル: UHFLI_lib.py プロジェクト: sandeshkalantre/qtlab
def UHF_init_demod(device_id = 'dev2148', demod_c = 0, out_c = 0):
    
    """
    Connecting to the device specified by device_id and setting initial parameters through LabOne GUI
    


    Arguments:
        

      device_id (str): The ID of the device to run the example with. For
					   example, 'dev2148'.
      demod_c (int): One of {0 - 7} demodulators of UHF LI 
      out_c (int): One of {0,1} output channels of UHF LI


    Raises:

      RuntimeError: If the device is not connected to the Data Server.
    """

    global daq  # Creating global variable for accesing the UHFLI from other functions
    global device # Creating global variable for accesing the UHFLI from other functions 

    # Create an instance of the ziDiscovery class.
    d = ziPython.ziDiscovery()

    # Determine the device identifier from it's ID.
    device = d.find(device_id).lower()

    # Get the device's default connectivity properties.
    props = d.get(device)

    # The maximum API level supported by this example.
    apilevel_example = 5
    # The maximum API level supported by the device class, e.g., MF.
    apilevel_device = props['apilevel']
    # Ensure we run the example using a supported API level.
    apilevel = min(apilevel_device, apilevel_example)
    # See the LabOne Programming Manual for an explanation of API levels.

    # Create a connection to a Zurich Instruments Data Server (an API session)
    # using the device's default connectivity properties.
    daq = ziPython.ziDAQServer(props['serveraddress'], props['serverport'], apilevel)

    # Check that the device is visible to the Data Server
    if device not in utils.devices(daq):
        raise RuntimeError("The specified device `%s` is not visible to the Data Server, " % device_id +
                           "please ensure the device is connected by using the LabOne User Interface " +
                           "or ziControl (HF2 Instruments).")

    # find out whether the device is an HF2 or a UHF
    devtype = daq.getByte('/%s/features/devtype' % device)
    options = daq.getByte('/%s/features/options' % device)

    
 

    # Create a base configuration: disable all outputs, demods and scopes
    general_setting = [
        ['/%s/demods/*/rate' % device, 0],
        ['/%s/demods/*/trigger' % device, 0],
        ['/%s/sigouts/*/enables/*' % device, 0]]
    if re.match('HF2', devtype):
        general_setting.append(['/%s/scopes/*/trigchannel' % device, -1])
    else:  # UHFLI
        pass
        #general_setting.append(['/%s/demods/*/enable' % device, 0])
        #general_setting.append(['/%s/scopes/*/enable' % device, 0])
    daq.set(general_setting)
    
    
    raw_input("Set the UHF LI parameters in user interface dialog!  Press enter to continue...")  # Wait for user to set the device parametrs from user interface

   
    daq.setInt('/%s/demods/%s/enable' % (device, demod_c) , 1)  # Enable demodulator 

    daq.setInt('/%s/demods/%s/rate' % (device, demod_c), 100000) # Set the demodulator sampling rate
    
    
    # Unsubscribe any streaming data
    daq.unsubscribe('*')



    # Path to UHF LI readout node made globally for using in other functions
    global path_demod
    path_demod = '/%s/demods/%d/sample' % (device, demod_c)

    global path_demod_enable
    path_demod_enable = '/%s/demods/%d/enable' % (device, demod_c) 

    # Path to UHF LI demodulator trigger node made globally for using in other functions
    global path_demod_trig
    path_demod_trig = '/%s/demods/%d/trigger' % (device, demod_c) 


    # Perform a global synchronisation between the device and the data server:
    # Ensure that 1. the settings have taken effect on the device before issuing
    # the poll() command and 2. clear the API's data buffers. Note: the sync()
    # must be issued after waiting for the demodulator filter to settle above.
    daq.sync()

    # Subscribe to the demodulator's sample
    path = path_demod
    daq.subscribe(path)

    # Get output amplitude 
    # made globally for using in other functions
    global out_ampl 
    out_ampl = daq.getDouble('/%s/sigouts/%s/amplitudes/3' % (device, out_c))/np.sqrt(2)

    # Get sampling rate
    # made globally for using in other functions
    global sampling_rate
    sampling_rate = daq.getDouble('/%s/demods/%s/rate' % (device, demod_c))

    # Get time constant in seconds 
    # made globally for using in other functions
    global TC
    TC = daq.getDouble('/%s/demods/%s/timeconstant' % (device, demod_c))
コード例 #15
0
ファイル: UHFLI_lib.py プロジェクト: sandeshkalantre/qtlab
def UHF_init_scope(device_id = 'dev2148'):
    
    """
    Connecting to the device specified by device_id and setting initial parameters through LabOne GUI
    


    Arguments:
        

      device_id (str): The ID of the device to run the example with. For
        example, 'dev2148'.



    Raises:

      RuntimeError: If the device is not connected to the Data Server.
    """

    global daq  # Creating global variable for accesing the UHFLI from other functions
    global device # Creating global variable for accesing the UHFLI from other functions 

    # Create an instance of the ziDiscovery class.
    d = ziPython.ziDiscovery()

    # Determine the device identifier from it's ID.
    device = d.find(device_id).lower()

    # Get the device's default connectivity properties.
    props = d.get(device)

    # The maximum API level supported by this example.
    apilevel_example = 5
    # The maximum API level supported by the device class, e.g., MF.
    apilevel_device = props['apilevel']
    # Ensure we run the example using a supported API level.
    apilevel = min(apilevel_device, apilevel_example)
    # See the LabOne Programming Manual for an explanation of API levels.

    # Create a connection to a Zurich Instruments Data Server (an API session)
    # using the device's default connectivity properties.
    daq = ziPython.ziDAQServer(props['serveraddress'], props['serverport'], apilevel)

    # Check that the device is visible to the Data Server
    if device not in utils.devices(daq):
        raise RuntimeError("The specified device `%s` is not visible to the Data Server, " % device_id +
                           "please ensure the device is connected by using the LabOne User Interface " +
                           "or ziControl (HF2 Instruments).")

    # find out whether the device is an HF2 or a UHF
    devtype = daq.getByte('/%s/features/devtype' % device)
    options = daq.getByte('/%s/features/options' % device)

    
 

    # Create a base configuration: disable all outputs, demods and scopes
    general_setting = [
        ['/%s/demods/*/rate' % device, 0],
        ['/%s/demods/*/trigger' % device, 0],
        ['/%s/sigouts/*/enables/*' % device, 0]]
    if re.match('HF2', devtype):
        general_setting.append(['/%s/scopes/*/trigchannel' % device, -1])
    else:  # UHFLI
        pass
        #general_setting.append(['/%s/demods/*/enable' % device, 0])
        #general_setting.append(['/%s/scopes/*/enable' % device, 0])
    daq.set(general_setting)
    
    
    raw_input("Set the UHF LI parameters in user interface dialog!  Press enter to continue...")  # Wait for user to set the device parametrs from user interface
コード例 #16
0
    def __init__(self, name, device='auto', interface='USB', address='127.0.0.1', port=8004, **kw):
        '''
        Input arguments:
            name:           (str) name of the instrument
            server_name:    (str) qcodes instrument server
            address:        (int) the address of the data server e.g. 8006
        '''
        #self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) #suggestion W vlothuizen
        t0 = time.time()
        super().__init__(name, **kw)

        self._daq = zi.ziDAQServer(address, int(port), 5)
        if device.lower() == 'auto':
            self._device = zi_utils.autoDetect(self._daq)
        else:
            self._device = device
            self._daq.connectDevice(self._device, interface)
        self._device = zi_utils.autoDetect(self._daq)
        s_node_pars=[]
        d_node_pars=[]

        path = os.path.abspath(__file__)
        dir_path = os.path.dirname(path)
        self._s_file_name = os.path.join(dir_path, 'zi_parameter_files', 's_node_pars.txt')
        self._d_file_name = os.path.join(dir_path, 'zi_parameter_files', 'd_node_pars.txt')

        init = True
        try:
            f = open(self._s_file_name).read()
            s_node_pars = json.loads(f)
        except:
            print("parameter file for gettable parameters {} not found".format(self._s_file_name))
            init=False
        try:
            f = open(self._d_file_name).read()
            d_node_pars = json.loads(f)
        except:
            print("parameter file for settable parameters {} not found".format(self._d_file_name))
            init = False

        for parameter in s_node_pars:
            parname=parameter[0].replace("/","_")
            parfunc="/"+device+"/"+parameter[0]
            if parameter[1] == 'float':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.setd, parfunc),
                    get_cmd=self._gen_get_func(self.getd, parfunc),
                    vals=vals.Numbers(parameter[2], parameter[3]))
            elif parameter[1] == 'float_small':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.setd, parfunc),
                    get_cmd=self._gen_get_func(self.getd, parfunc),
                    vals=vals.Numbers(parameter[2], parameter[3]))
            elif parameter[1] == 'int_8bit':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.seti, parfunc),
                    get_cmd=self._gen_get_func(self.geti, parfunc),
                    vals=vals.Ints(int(parameter[2]), int(parameter[3])))
            elif parameter[1]=='int':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.seti, parfunc),
                    get_cmd=self._gen_get_func(self.geti, parfunc),
                    vals=vals.Ints(int(parameter[2]), int(parameter[3])))
            elif parameter[1]=='int_64':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.seti, parfunc),
                    get_cmd=self._gen_get_func(self.geti, parfunc),
                    vals=vals.Ints(int(parameter[2]), int(parameter[3])))
            elif parameter[1]=='bool':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.seti, parfunc),
                    get_cmd=self._gen_get_func(self.geti, parfunc),
                    vals=vals.Ints(int(parameter[2]), int(parameter[3])))
            else:
                print("parameter {} type {} from from s_node_pars not recognized".format(parname,parameter[1]))

        for parameter in d_node_pars:
            parname=parameter[0].replace("/","_")
            parfunc="/"+device+"/"+parameter[0]
            if parameter[1]=='float':
                self.add_parameter(
                    parname,
                    get_cmd=self._gen_get_func(self.getd, parfunc))
            elif parameter[1]=='vector_g':
                self.add_parameter(
                    parname,
                    get_cmd=self._gen_get_func(self.getv, parfunc))
            elif parameter[1]=='vector_s':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.setv, parfunc),
                    vals=vals.Anything())
            elif parameter[1]=='vector_gs':
                self.add_parameter(
                    parname,
                    set_cmd=self._gen_set_func(self.setv, parfunc),
                    get_cmd=self._gen_get_func(self.getv, parfunc),
                    vals=vals.Anything())
            else:
                print("parameter {} type {} from d_node_pars not recognized".format(parname,parameter[1]))


        self.add_parameter('AWG_file',
                           set_cmd=self._do_set_AWG_file,
                           vals=vals.Anything())
        if init:
            self.load_default_settings()
        t1 = time.time()

        print('Initialized UHFQC', self._device,
              'in %.2fs' % (t1-t0))
コード例 #17
0
ファイル: MFIAClass.py プロジェクト: nelsongt/mfiaDLTS2
    def reset(self, dlts, mfia):
        self.generate_log("Initializing MFIA...", "blue")
        self.ziDAQ = []

        calcRejectSamples = math.floor(
            16 * mfia.time_constant * mfia.sample_rate
        )  #calculation of hardware recovery, derived from the MFIA user manual sect. 6.4.2 for 99% recovery using 8th order filter
        extraRejectSamples = mfia.sample_reject  #if empirically it is seen that more data points should be rejected beyond the above calculation, add the extra # of points here
        self.rejectSamples = calcRejectSamples + extraRejectSamples  #length of hardware recovery in data points

        ## Open connection to the ziServer (socket for sync interface)
        self.ziDAQ = ziPython.ziDAQServer(
            '127.0.0.1', 8004, 6)  # Use local data server for best performance
        # Get device name automagically (e.g. 'dev234')
        device = self.autoDetect()
        self.device = device  #TODO Fix this later
        # or specify manually
        #device = 'dev3327'

        # Enable IA module
        self.ziDAQ.setInt("/{0}/imps/0/enable".format(device), 1)
        #     ziDAQ('setInt', ['/' device '/imps/0/enable'], 1);

        vrange = 10
        irange = mfia.i_range
        phase_offset = 0

        # Setup IA module
        self.ziDAQ.setInt("/{0}/imps/0/mode".format(device), 1)
        self.ziDAQ.setInt("/{0}/system/impedance/filter".format(device), 1)
        self.ziDAQ.setInt("/{0}/imps/0/model".format(device), 0)
        #     ziDAQ('setInt', ['/' device '/imps/0/mode'], 1);
        #     ziDAQ('setInt', ['/' device '/system/impedance/filter'], 1);
        #     ziDAQ('setInt', ['/' device '/imps/0/model'], 0);
        self.ziDAQ.setInt("/{0}/imps/0/auto/output".format(device), 0)
        self.ziDAQ.setInt("/{0}/system/impedance/precision".format(device), 0)
        self.ziDAQ.setDouble("/{0}/imps/0/maxbandwidth".format(device), 1000)
        self.ziDAQ.setDouble("/{0}/imps/0/omegasuppression".format(device), 60)
        #     ziDAQ('setInt', ['/' device '/imps/0/auto/output'], 0);
        #     ziDAQ('setInt', ['/' device '/system/impedance/precision'], 0);
        #     ziDAQ('setDouble', ['/' device '/imps/0/maxbandwidth'], 1000);
        #     ziDAQ('setDouble', ['/' device '/imps/0/omegasuppression'], 60);
        self.ziDAQ.setDouble(
            "/{0}/imps/0/confidence/lowdut2t/ratio".format(device), 1000)
        #
        # Input settings, set to current and set range
        self.ziDAQ.setInt("/{0}/imps/0/auto/inputrange".format(device), 0)
        self.ziDAQ.setDouble("/{0}/imps/0/current/range".format(device),
                             irange)
        self.ziDAQ.setDouble("/{0}/imps/0/voltage/range".format(device),
                             vrange)
        #     ziDAQ('setInt', ['/' device '/imps/0/auto/inputrange'], 0);
        #     ziDAQ('setDouble', ['/' device '/imps/0/current/range'], irange);
        #     %ziDAQ('setDouble', ['/' device '/imps/0/voltage/range'], vrange);
        #
        # Lock in params & filtering
        self.ziDAQ.setInt("/{0}/imps/0/demod/sinc".format(device), 1)
        self.ziDAQ.setInt("/{0}/imps/0/demod/order".format(device), 8)
        self.ziDAQ.setInt("/{0}/imps/0/auto/bw".format(device), 0)
        self.ziDAQ.setDouble("/{0}/demods/0/phaseshift".format(device),
                             phase_offset)
        self.ziDAQ.setDouble("/{0}/imps/0/demod/timeconstant".format(device),
                             mfia.time_constant)
        self.ziDAQ.setDouble("/{0}/imps/0/demod/harmonic".format(device), 1)
        #     ziDAQ('setInt', ['/' device '/imps/0/demod/sinc'], 1);
        #     ziDAQ('setInt', ['/' device '/imps/0/demod/order'], 8);
        #     ziDAQ('setInt', ['/' device '/imps/0/auto/bw'], 0);
        #     ziDAQ('setDouble', ['/' device '/demods/0/phaseshift'], phase_offset);
        #     ziDAQ('setDouble', ['/' device '/imps/0/demod/timeconstant'], mfia.time_constant);
        #     ziDAQ('setDouble', ['/' device '/imps/0/demod/harmonic'], 1);
        #
        # Oscillator settings
        self.ziDAQ.setDouble("/{0}/imps/0/freq".format(device), mfia.ac_freq)
        self.ziDAQ.setDouble("/{0}/imps/0/output/amplitude".format(device),
                             mfia.ac_ampl)
        #     ziDAQ('setDouble', ['/' device '/imps/0/freq'], mfia.ac_freq);
        #     ziDAQ('setDouble', ['/' device '/imps/0/output/amplitude'], mfia.ac_ampl);
        #
        # Output settings
        self.ziDAQ.setDouble("/{0}/imps/0/output/range".format(device), vrange)
        self.ziDAQ.setInt("/{0}/imps/0/output/on".format(device), 1)
        if dlts.pulse_height:
            self.ziDAQ.setInt("/{0}/sigouts/0/add".format(device), 1)
        else:
            self.ziDAQ.setInt("/{0}/sigouts/0/add".format(device), 0)

    #     ziDAQ('setDouble', ['/' device '/imps/0/output/range'], vrange);
    #     ziDAQ('setInt', ['/' device '/imps/0/output/on'], 1);
    #     if mfia.pulse_height  % Check if a pulse bias is set, if so add to ss bias
    #         ziDAQ('setInt', ['/' device '/sigouts/0/add'], 1);
    #     else
    #         ziDAQ('setInt', ['/' device '/sigouts/0/add'], 0);
    #     end
        self.ziDAQ.setDouble("/{0}/sigouts/0/offset".format(device),
                             dlts.ss_bias)
        self.ziDAQ.setInt("/{0}/tu/thresholds/0/input".format(device), 59)
        self.ziDAQ.setInt("/{0}/tu/thresholds/1/input".format(device), 59)
        self.ziDAQ.setInt("/{0}/tu/thresholds/0/inputchannel".format(device),
                          0)
        self.ziDAQ.setInt("/{0}/tu/thresholds/1/inputchannel".format(device),
                          0)
        self.ziDAQ.setInt("/{0}/tu/logicunits/0/inputs/0/not".format(device),
                          1)
        self.ziDAQ.setInt("/{0}/tu/logicunits/1/inputs/0/not".format(device),
                          1)
        #     ziDAQ('setDouble', ['/' device '/sigouts/0/offset'], dlts.ss_bias);
        #     ziDAQ('setInt', ['/' device '/tu/thresholds/0/input'], 59);
        #     ziDAQ('setInt', ['/' device '/tu/thresholds/1/input'], 59);
        #     ziDAQ('setInt', ['/' device '/tu/thresholds/0/inputchannel'], 0);
        #     ziDAQ('setInt', ['/' device '/tu/thresholds/1/inputchannel'], 0);
        #     ziDAQ('setInt', ['/' device '/tu/logicunits/0/inputs/0/not'], 1);
        #     ziDAQ('setInt', ['/' device '/tu/logicunits/1/inputs/0/not'], 1);
        self.ziDAQ.setDouble(
            "/{0}/tu/thresholds/0/deactivationtime".format(device),
            dlts.trns_length + 0.001)
        self.ziDAQ.setDouble(
            "/{0}/tu/thresholds/0/activationtime".format(device),
            dlts.pulse_width)
        self.ziDAQ.setDouble(
            "/{0}/tu/thresholds/1/deactivationtime".format(device), 0)
        self.ziDAQ.setDouble(
            "/{0}/tu/thresholds/1/activationtime".format(device), 0)
        #     ziDAQ('setDouble', ['/' device '/tu/thresholds/0/deactivationtime'], dlts.trns_length+0.001); #add 1ms buffer time
        #     ziDAQ('setDouble', ['/' device '/tu/thresholds/0/activationtime'], dlts.pulse_width);
        #     ziDAQ('setDouble', ['/' device '/tu/thresholds/1/deactivationtime'], 0);
        #     ziDAQ('setDouble', ['/' device '/tu/thresholds/1/activationtime'], 0);
        self.ziDAQ.setInt("/{0}/auxouts/0/outputselect".format(device), 13)
        self.ziDAQ.setInt("/{0}/auxouts/1/outputselect".format(device), 13)
        self.ziDAQ.setInt("/{0}/auxouts/0/demodselect".format(device), 0)
        self.ziDAQ.setInt("/{0}/auxouts/1/demodselect".format(device), 1)
        #     ziDAQ('setInt', ['/' device '/auxouts/0/outputselect'], 13);
        #     ziDAQ('setInt', ['/' device '/auxouts/1/outputselect'], 13);
        #     ziDAQ('setInt', ['/' device '/auxouts/0/demodselect'], 0);
        #     ziDAQ('setInt', ['/' device '/auxouts/1/demodselect'], 1);
        self.ziDAQ.setDouble("/{0}/auxouts/0/scale".format(device),
                             dlts.pulse_height)
        self.ziDAQ.setDouble("/{0}/auxouts/0/offset".format(device), 0)
        self.ziDAQ.setDouble("/{0}/auxouts/1/scale".format(device), -5.0)
        self.ziDAQ.setDouble("/{0}/auxouts/1/offset".format(device), 5.0)
        #     ziDAQ('setDouble', ['/' device '/auxouts/0/scale'], dlts.pulse_height);
        #     ziDAQ('setDouble', ['/' device '/auxouts/0/offset'], 0);
        #     ziDAQ('setDouble', ['/' device '/auxouts/1/scale'], -5.0);
        #     ziDAQ('setDouble', ['/' device '/auxouts/1/offset'], 5.0);
        #
        # Data stream settings
        self.ziDAQ.setDouble("/{0}/imps/0/demod/rate".format(device),
                             mfia.sample_rate)
        #     ziDAQ('setDouble', ['/' device '/imps/0/demod/rate'], mfia.sample_rate);

        self.generate_log("MFIA configure OK.", "green")
        return True
コード例 #18
0
    def connect_device(self,
                       devicename,
                       required_options=None,
                       required_err_msg='',
                       exp_dependencie=False):
        import zhinst.utils as utils
        import zhinst.ziPython as ziPython

        # This function finds and connect the zurich device with serial number : devicename
        api_level = 6
        # dev_type = 'UHFLI'
        dev_type = 'MFLI'
        # Create an instance of the ziDiscovery class.
        d = ziPython.ziDiscovery()
        # Determine the device identifier from it's ID.
        device_id = d.find(devicename).lower()
        # Get the device's connectivity properties.
        props = d.get(device_id)
        if not props['discoverable']:
            messagebox.showinfo(
                message="The specified device `{}` is not discoverable  ".
                format(devicename) +
                "from the API. Please ensure the device is powered-on and visible using the LabOne User"
                + "Interface or ziControl.",
                title='Information')
        else:
            if not re.search(dev_type, props['devicetype']):
                messagebox.showinfo(
                    message=
                    "Required device type not satisfied. Device type `{}` does not match the"
                    + "required device type:`{}`. {}".format(
                        props['devicetype'], dev_type, required_err_msg))

            if required_options:
                assert isinstance(required_options, list), "The keyword argument must be a list of string each entry" \
                                                           "specifying a device option."

                def regex_option_diff(required_options, device_options):
                    """Return the options in required_options (as regex) that are not found in the
                    device_options list.

                    """
                    missing_options = []
                    for option in required_options:
                        if not re.search(option, '/'.join(device_options)):
                            missing_options += required_options
                    return missing_options

                if props['devicetype'] == 'UHFAWG':
                    # Note(16.12): This maintains backwards compatibility of this function.
                    installed_options = props['options'] + ['AWG']
                else:
                    installed_options = props['options']
                missing_options = regex_option_diff(required_options,
                                                    installed_options)
                if missing_options:
                    raise Exception(
                        "Required option set not satisfied. The specified device `{}` has the `{}` options "
                        "installed but is missing the required options `{}`. {}"
                        .format(device_id, props['options'], missing_options,
                                required_err_msg))
            # The maximum API level supported by the device class, e.g., MF.
            apilevel_device = props['apilevel']

            # Ensure that we connect on an compatible API Level (from where create_api_session() was called).
            apilevel = min(apilevel_device, api_level)
            # Creating a Daq server for the device with the parameters found
            daq = ziPython.ziDAQServer(props['serveraddress'],
                                       props['serverport'], apilevel)
            messagebox.showinfo(
                message='Zurich Instrument device {} is connected'.format(
                    device_id),
                title='Information')
            self.info = {'daq': daq, 'device': device_id, 'prop': props}
            self.default = utils.default_output_mixer_channel(
                self.info['prop'])
            self.node_branch = daq.listNodes('/%s/' % device_id, 0)
            reset_settings = [['/%s/demods/*/enable' % device_id, 0],
                              ['/%s/demods/*/trigger' % device_id, 0],
                              ['/%s/sigout/*/enables/*' % device_id, 0],
                              ['/%s/scopes/*/enable' % device_id, 0]]

            daq.set(reset_settings)
            daq.sync()

            if self.mainf:
                experiments = self.mainf.Frame[4].experiment_dict
                for experiment in experiments:
                    experiments[experiment].update_options('Zurich')