Example #1
0
  def __init__(self, name, set_heater_current, get_heater_current, get_temperature=None, update_interval=15., reset=False):
    '''
    Initializes the heater_controller.

    Input:
        name (string)                : name of the instrument
        set_heater_current(function) : function that sets the heating current, in Amps
        get_heater_current(function) : function that gets the heating current, in Amps
        get_temperature (function)   : function that gets the current temperature
        update_interval (float)      : time scale for feedback operations, in seconds
        reset (bool)                 : resets to default values, default=false

    Output:
        None
    '''
    logging.info(__name__ + ' : Initializing instrument heater_controller: %s' % name)
    Instrument.__init__(self, name, tags=['physical'])
    
    self._set_heater_current = set_heater_current
    self._get_heater_current = get_heater_current
    self._get_temperature = get_temperature
    self._update_interval = update_interval

    self.add_parameter('heater_current', type=types.FloatType, flags=Instrument.FLAG_GETSET, units='A')
    self.add_parameter('last_value_set', type=types.FloatType, flags=Instrument.FLAG_GET|Instrument.FLAG_PERSIST, units='A')
    self.add_parameter('last_change_time', type=types.FloatType, flags=Instrument.FLAG_GET|Instrument.FLAG_PERSIST, units='s')
    self.add_parameter('thermalization_time', type=types.FloatType, flags=Instrument.FLAG_GETSET|Instrument.FLAG_PERSIST, units='s')
    self.add_parameter('time_until_steady_state', type=types.FloatType, flags=Instrument.FLAG_GET, units='s')
    self.add_parameter('steady_state_reached', type=types.BooleanType, flags=Instrument.FLAG_GET)
    
    # Get/set some initial values
    self.get_heater_current()
    if self.get_last_change_time() == None: self.update_value('last_change_time', time.time())
    if self.get_thermalization_time() == None: self.update_value('thermalization_time', 3000.)
    self.get_all()
Example #2
0
    def __init__(self, name, address, reset=False):
        '''
        Input:
          name (string)    : name of the instrument
          address (string) : GPIB address
        '''
        logging.info(__name__ + ' : Initializing instrument JDSU_SWS15101')
        Instrument.__init__(self, name, tags=['physical'])

        # Add some global constants
        self._address = address
        self._visainstrument = visa.instrument(self._address)

        self.add_parameter('power',
            flags=Instrument.FLAG_GETSET, units='mW', minval=0, maxval=10, type=types.FloatType)
        self.add_parameter('diode_current',
            flags=Instrument.FLAG_GETSET, units='mA', minval=0, maxval=150, type=types.FloatType)
        self.add_parameter('wavelength',
            flags=Instrument.FLAG_GETSET, units='nm', minval=1460, maxval=1600, type=types.FloatType)
        self.add_parameter('output_status',
            flags=Instrument.FLAG_GETSET, type=types.BooleanType)
        self.add_parameter('FSCWaveL',
            flags=Instrument.FLAG_SET, units='pm', minval=-22.4, maxval=+22.4, type=types.FloatType)
        
        self.add_function ('get_all')
Example #3
0
    def __init__(self, name, id=0):
        Instrument.__init__(self, name, tags=['physical'])

        self._h = 0
        self._id = id

        self.add_parameter('wavelength',
            flags=Instrument.FLAG_SET|Instrument.FLAG_SOFTGET,
            type=types.IntType,
            units='nm')

        self.add_parameter('power',
            flags=Instrument.FLAG_SET|Instrument.FLAG_SOFTGET,
            type=types.IntType,
            units='%',
            help='Set crystal power')

        self.add_parameter('wlenopt',
            flags=Instrument.FLAG_SET,
            type=types.IntType,
            units='nm',
            help='Set wavelength and optimal power')
            
        self.add_function('enable')
        self._open()
        self.enable()
        
        # Close AOTF before exiting QTlab
        qt.flow.register_exit_handler(self._close)
Example #4
0
    def __init__(self, name, use_adwin='adwin'):

        Instrument.__init__(self, name)
       
        self.add_parameter('channel', 
                           type = types.IntType, 
                           flags = Instrument.FLAG_GETSET)
               
        self.add_parameter('state',
                            type = types.StringType,
                            flags = Instrument.FLAG_GETSET,
                            option_list = ('Open', 'Closed')) #Naar voorbeeld van eerder, Werkt dit? 

        self._ins_adwin=qt.instruments[use_adwin]

        # set defaults
        self._channel = 7 # THis is the channel on the second breakout box, does this corespond? 
        self._state = 'Closed'
        self.get_all()
       
        # override from config       
        cfg_fn = os.path.join(qt.config['ins_cfg_path'], name+'.cfg')

        if not os.path.exists(cfg_fn):
            _f = open(cfg_fn, 'w')
            _f.write('')
            _f.close()

        self._ins_cfg = config.Config(cfg_fn)     
        self.load_cfg()
        self.save_cfg()
    def __init__(self, name, address, number=5):
        """
        Initializes the Oxford Instruments Kelvinox IGH Dilution Refrigerator.

        Input:
            name (string)    : name of the instrument
            address (string) : instrument address
            number (int)     : ISOBUS instrument number

        Output:
            None
        """
        logging.debug(__name__ + " : Initializing instrument")
        Instrument.__init__(self, name, tags=["physical"])

        self._address = address
        self._number = number
        self._visainstrument = visa.SerialInstrument(self._address)
        self._values = {}
        self._visainstrument.stop_bits = 2

        # Add parameters
        self.add_parameter("1K_pot_temp", type=types.FloatType, flags=Instrument.FLAG_GET)
        self.add_parameter("mix_chamber_temp", type=types.FloatType, flags=Instrument.FLAG_GET)

        # Add functions
        self.add_function("get_all")
        self.get_all()
Example #6
0
 def __init__(self, name, dacs = DAC_ROUT, dacranges = None):
     """
     init virtual instrument object
     Inputs:
         - name: qt instrument name
         - dacs: list of routes of channels in use, e.g. [5] or [5,9,2]
         - dacranges: list of length len(dacs) indicating the dac ranges set at the device, list entries one of 'bi' for -2000,2000, 'pos' for 0,4000, 'neg' for -4000,0
     """
     Instrument.__init__(self, name, tags=['virtual'])
     
     self.dacs = dacs
     try:
         self.channels = len(self.dacs)
     except TypeError:
         logging.error('Error reading dac ports to be used. Import as list.')
     if dacranges == None:
         dacranges = ['bi']*self.channels
     else:
         if len(dacranges) != self.channels:
             logging.errors('dacranges not specified properly')
     limits_dict = {'bi':[-2000,2000],'pos':[0,4000],'neg':[-4000,0]}
     self.range_limits = [limits_dict[dacranges[i]] for i in range(self.channels)]
     #print self.range_limits
     if self.channels == 1:
         self.add_parameter('current', type=types.FloatType, flags=Instrument.FLAG_GETSET, units='mA')
         self.add_parameter('range', type=types.StringType, flags=Instrument.FLAG_GETSET)
     elif self.channels > 1 and self.channels <= 16:
         self.add_parameter('current', type=types.FloatType, flags=Instrument.FLAG_GETSET, units='mA', channels=(1, self.channels), channel_prefix='ch%d_')
         self.add_parameter('range', type=types.StringType, flags=Instrument.FLAG_GETSET, channels=(1, self.channels), channel_prefix='ch%d_')
     else:
         logging.error('incorrect number of channels specified')
     
     self.c_ranges = ['1m']*self.channels
Example #7
0
 def __init__(self, name):
     Instrument.__init__(self, name)
     self.name = name
     # Set up a few instruments as private subobjects
     self._snspd = qt.instruments['snspd']
     self._ls211 = qt.instruments['ls211']
     # Define time = 0 to be when the instrument is created
     self._t0 = 0
     # Set a parameter called is_running to be used to control the logic
     # of the update routine
     self.add_parameter('is_running',
         type=types.BooleanType,
         flags=Instrument.FLAG_GETSET)
     # Set the update interval here; can be changed
     self.add_parameter('update_interval',
         type=types.FloatType,
         unit='s',
         flags=Instrument.FLAG_GETSET)
     # Expose these functions to the user to start/stop/show the monitors
     self.add_function('start')
     self.add_function('stop')
     self.add_function('show_monitors')
     # Set default values of parameters
     self.set_is_running(False)
     self.set_update_interval(5)
    def __init__(self, name, address, number=1):
        '''
        Initializes the Oxford Instruments ILM 200 Helium Level Meter.

        Input:
            name (string)    : name of the instrument
            address (string) : instrument address
            number (int)     : ISOBUS instrument number

        Output:
            None
        '''
        logging.debug(__name__ + ' : Initializing instrument')
        Instrument.__init__(self, name, tags=['physical'])


        self._address = address
        self._number = number
        self._visainstrument = visa.SerialInstrument(self._address)
        self._values = {}
        self._visainstrument.stop_bits = 2

        #Add parameters
        self.add_parameter('level', type=types.FloatType,
            flags=Instrument.FLAG_GET)
        self.add_parameter('status', type=types.StringType,
            flags=Instrument.FLAG_GET)

        # Add functions
        self.add_function('get_all')
        self.get_all()
    def __init__(self, name, pulser):
        '''
            Initialize the virtual instruments
                
                Input:
                    name            : Name of the virtual instruments
                    pulser          : Name given to the pulser
                
                Output:
                    None
        '''
        
        Instrument.__init__(self, name, tags=['virtual'])
        
        self.add_parameter('period', units='ns',  flags=Instrument.FLAG_GETSET | Instrument.FLAG_GET_AFTER_SET, type=types.FloatType)
        self.add_parameter('cooling_time', units='ns', flags=Instrument.FLAG_GETSET, type=types.FloatType)
        self.add_parameter('origin', units='ns', flags=Instrument.FLAG_GETSET, type=types.FloatType)

        
        # Defining some stuff
        self._instruments = instruments.get_instruments()
        self._pulser = self._instruments.get(pulser)
        
        self._cooling_time = 1e3 #in [ns]
        self._origin = 0. #in [ns]
        
        
        self.get_all()
Example #10
0
 def __init__(self):
     """
     Object constructor
     """
     Instrument.__init__(self)
     self.set_primary((15.0, 0.1))
     self.set_secondary((1.0, 0.05))
Example #11
0
    def __init__(self, name, dimension_set='default'):
        Instrument.__init__(self, name)
        self.dimension_sets = {
            'default' : {
                'x' : {
                    'scan_length' : 2.0,
                    'nr_of_points' : 60,
                    'qt_ins' : 'fsm',
                    'channel' : 'X',
                    'sigma' : 0.5

                    },
                'y' : {
                    'scan_length' : 2.0,
                    'nr_of_points' : 60,
                    'qt_ins' : 'fsm',
                    'channel' : 'Y',
                    'sigma' : 0.5
                    },
                'z' : {
                    'scan_length' : 5.0,
                    'nr_of_points' : 60,
                    'qt_ins' : 'xps',
                    'channel' : 'Z',
                    'sigma' : 2.0/1000.0
                    },
                'xxps' : {
                    'scan_length' : 2.4,
                    'nr_of_points' : 44,
                    'qt_ins' : 'xps',
                    'ins_attr_set' : 'set_abs_positionX',
                    'ins_attr_get' : 'get_abs_positionX'
                    },
                'yxps' : {
                    'scan_length' : 2.4,
                    'nr_of_points' : 44,
                    'qt_ins' : 'xps',
                    'ins_attr_set' : 'set_abs_positionY',
                    'ins_attr_get' : 'get_abs_positionY'
                    },
                'xyz' : ['x','y','z'],
                'xy': ['y','x'],
                'fullxyz' : ['z','y','x','yxps','xxps']
                },
            }
        # Get the instruments we're going to use -- could remove this from
        # hardcode in the future
        self._fsm = qt.instruments['fsm']
        self._xps = qt.instruments['xps']
        self._ni63 = qt.instruments['NIDAQ6363']
        self._opt_pos_prev = {
                                'x' : 0.0,
                                'y' : 0.0,
                                'z' : 3.0
                                }
        self._opt_pos = {'x' : self._fsm.get_abs_positionX(),
                         'y' : self._fsm.get_abs_positionY(),
                         'z' : self._xps.get_abs_positionZ()}
        self.add_function('optimize')
        self.dimensions = self.dimension_sets[dimension_set]
 def __init__(self, name):
     Instrument.__init__(self, name, tags=['virtual'])
     
     self.add_parameter('temperature', type=types.FloatType,
         flags=Instrument.FLAG_GET, units='mK')
     
     self.t = tip_client('tip',address='pi-us74')   #tip raspberry instance
    def __init__(self, name, address, reset=False):
        '''
        address = COM port
        '''
        logging.info(__name__ + ' : Initializing Spectra Physics Millenia')
        Instrument.__init__(self, name, tags=['physical'])

        # Set parameters
        self._address = address

        self.add_parameter('id',
            flags=Instrument.FLAG_GET,
            type=types.StringType)

        self.add_parameter('power',
            flags=Instrument.FLAG_GETSET,
            format='%.02f',
            type=types.FloatType)

        # Add functions
        self.add_function('reset')
        self.add_function('on')
        self.add_function('off')
        self.add_function('get_all')

        self._open_serial_connection()

        if reset:
            self.reset()
        else:
            self.get_all()
Example #14
0
    def __init__(self, name, ai_in = 'ai1', trig_chan = 'PFI8'):
        #Instrument.__init__(self, name, tags=['positioner'])
        Instrument.__init__(self, name)
        # Import the DAQ as an instrument object to write to.
        self._ni63 = qt.instruments['NIDAQ6363']

        # Store related constants for the interferometer here.

        self.FP_params = {
                'period' : 50.0, # ms
                'FSR' : 10.0, # GHz
                'sample_rate' : 10000.0, # Hz
                'aiport' : 'ai1',
                'trigger' : 'PFI8',
                'thresholdV' : 0.25,
                'thresholdsep' : 0.006

                }
        self.FP_params['aiport'] = ai_in
        self.FP_params['trigger'] = trig_chan
        # Instrument parameters
##        self.add_parameter('abs_position',
##            type=types.FloatType,
##            channels=('X', 'Y'),
##            flags=Instrument.FLAG_SET|Instrument.FLAG_SOFTGET,
##            units='um',
##            format='%.04f')


        # Instrument functions
        self.add_function('read_sweep')
        self.add_function('read_sweep_plot')
        self.add_function('read_sweep_centroids')

        self.add_function('threshold')
Example #15
0
    def __init__(self, name, address, reset=False):
        Instrument.__init__(self, name)

        self._address = address
        self._visa = visa.instrument(self._address)

        self.add_parameter('identification',
            flags=Instrument.FLAG_GET)

        self.add_parameter('internal_temperature',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            units='deg C')

        self.add_parameter('probe1_temperature',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            units='deg C')

        self.add_parameter('probe2_temperature',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            units='deg C')     
        
        self.add_parameter('humidity',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            units='percent')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #16
0
    def __init__(self, name, remote_name, inssrv=None, server=None):
        Instrument.__init__(self, name, tags=['remote'])

        self._remote_name = remote_name
        if inssrv is None:
            inssrv = objsh.helper.find_object('%s:instrument_server' % server)
        self._srv = inssrv
        params = self._srv.get_ins_parameters(remote_name)
        for name, info in params.iteritems():
            if info['flags'] & Instrument.FLAG_GET:
                info['get_func'] = self._get
            elif info['flags'] & Instrument.FLAG_SOFTGET:
                info['flags'] ^= (Instrument.FLAG_SOFTGET | Instrument.FLAG_GET)
                info['get_func'] = self._get
            if info['flags'] & Instrument.FLAG_SET:
                info['set_func'] = self._set
            info['channel'] = name
            self.add_parameter(name, **info)

        funcs = self._srv.get_ins_functions(remote_name)
        for name, info in funcs.iteritems():
            try:
                func = self.create_lambda(name, info.get('argspec', None))
                if 'doc' in info:
                    func.__doc__ = info['doc']
                setattr(self, name, func)
                self.add_function(name, **info)
            except Exception, e:
                logging.warning('Failed to create function %s: %s', name, e)
Example #17
0
    def __init__(self, name, address):
        '''

        Input:
            name (string)    : name of the instrument
            address (string) : instrument (serial port) address

        Output:
            None
        '''
        logging.debug(__name__ + ' : Initializing instrument')
        Instrument.__init__(self, name, tags=['physical'])


        self._address = address
        self._visainstrument = visa.SerialInstrument(self._address, delay = 30e-3)
        self._values = {}
        self._visainstrument.stop_bits = 1
        self.reset()

        #Add parameters
        self.add_parameter('b_raw', type=types.IntType,
            flags=Instrument.FLAG_GET)
        self.add_parameter('counts', type=types.IntType,
            flags=Instrument.FLAG_GETSET)

        # Add functions
        self.add_function('get_all')
        self.get_all()
Example #18
0
    def __init__(self, name, address, reset=False,ip="",delay=0):
        '''
        Initializes the AVS_47, and communicates with the wrapper.

        Input:
            name (string)    : name of the instrument
            address (string) : GPIB address
            reset (bool)     : resets to default values, default=false

        Output:
            None
        '''
        
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address
        self._visainstrument = visa.instrument(self._address,ip=ip,delay=delay)

        self.add_parameter('delay', type=types.FloatType,
            flags=Instrument.FLAG_GETSET | Instrument.FLAG_GET_AFTER_SET,
            channels=(1, 2), minval=0.0, maxval=999, units='sec',channel_prefix='ch%d_')

        self.add_function('reset')
        self.add_function('get_all')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #19
0
    def __init__(self, name, address):
        '''
        Initializes the Cryocon62, and comunicates with the wrapper.

        Input:
            name (string)    : name of the instrument
            address (string) : GPIB address

        Output:
            None
        '''
        logging.info(__name__ + ' : Initializing instrument')
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address
        self._visainstrument = visa.instrument(self._address)

        self.add_parameter('temperature', type=types.FloatType,
            channel_prefix='ch%d_',
            flags=Instrument.FLAG_GET, channels=(1,2))
        self.add_parameter('units', type=types.StringType,
            channel_prefix='ch%d_',
            flags=Instrument.FLAG_GET, channels=(1,2))
        self.add_parameter('sensor_index', type=types.IntType,
            channel_prefix='ch%d_',
            flags=Instrument.FLAG_GET, channels=(1,2))
        self.add_parameter('vbias', type=types.StringType,
            channel_prefix='ch%d_',
            flags=Instrument.FLAG_GET, channels=(1,2))
        self.add_parameter('channel_name', type=types.StringType,
            channel_prefix='ch%d_',
            flags=Instrument.FLAG_GET, channels=(1,2))
        self.add_parameter('sensor_name', type=types.StringType,
            channel_prefix='ch%d_',
            flags=Instrument.FLAG_GET, channels=(1,2))
Example #20
0
    def __init__(self, name, reset=False, upperlim=10000, lowerlim=0):
        '''
        Initializes the metadata thingy.

        Input:
            name (string)    : name of the instance

        Output:
            None
        '''
        logging.info(__name__ + ' : Initializing meta')
        Instrument.__init__(self, name, tags=['virtual'])

        self.add_parameter('time', type=types.FloatType,
            flags=Instrument.FLAG_GETSET | Instrument.FLAG_GET_AFTER_SET ,
            units = 's', tags = ['sweep'], minval=lowerlim, maxval=upperlim)   
            
        self.add_function('do_get_time')
        self.add_function('do_set_time')
        # reset ?
        self._starting_time = time.time()

        if reset:
            self.reset()
        else:
            self.get_all()
        self._dip = ''
        self._exp = ''
        self._notes = ''
        self._user = ''
Example #21
0
    def __init__(self, name, address, reset=False):
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address


        self.add_parameter('wavelength',
            flags=Instrument.FLAG_GETSET,
            type=types.FloatType,
            units='nm')

        self.add_parameter('wavelength_speed',
            flags=Instrument.FLAG_GETSET,
            type=types.FloatType,
            minval=1)

        self.add_parameter('grating',
            flags=Instrument.FLAG_GETSET,
            type=types.IntType,
            minval=1)


        self.add_function('buffer_clear')




        self._open_serial_connection()
        if reset:
            self.reset()
        else:
            self.get_all()
Example #22
0
    def __init__(self, name, address, reset=False):
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address
        # Device identification
        self.add_parameter('identification',
        flags=Instrument.FLAG_GET)
        # Get temperature in Kelvin
        self.add_parameter('temperature',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            units='K')
        # Input type is the type of temperator sensor in the device
        self.add_parameter('intype',
            flags=Instrument.FLAG_GETSET,
            type=types.IntType)
        # Controls whether display is on or off on the module
        self.add_parameter('dispon',
            flags=Instrument.FLAG_GETSET,
            type=types.BooleanType)

        self._open_serial_connection()
        if reset:
            self.reset()
        else:
            self.get_all()
Example #23
0
    def __init__(self, name, address, reset=False):
        Instrument.__init__(self, name)

        self._address = address
        self._visa = visa.instrument(self._address)

        self.add_parameter('identification',
            flags=Instrument.FLAG_GET)

        self.add_parameter('power',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            units='W')

        self.add_parameter('head_info',
            flags=Instrument.FLAG_GET,
            type=types.StringType)

        self.add_parameter('wavelength',
            flags=Instrument.FLAG_GETSET,
            type=types.FloatType,
            units='m')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #24
0
    def __init__(self, name, address=None, reset=False):
        Instrument.__init__(self,name)
        self.devHandle = CLOpenUSBSerialDevice(c_long(address))
        logging.info('Device handle of Bristol wavemeter is %s' % self.devHandle)
        # Set wavelength reading to nm
        CLSetLambdaUnits(c_int(self.devHandle), c_uint(0))

        self.add_parameter('wavelength',
                type=types.FloatType,
                flags=Instrument.FLAG_GET,
                units='nm')
#	self.add_parameter('frequency',
#	        type=types.FloatType,
#		flags=Instrument.FLAG_GET,
#		units='THz')
        self.add_parameter('power',
                type=types.FloatType,
                flags=Instrument.FLAG_GET,
                units='mW')

        self.add_function('close_device')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #25
0
    def __init__(self, name, address, reset=False):
        Instrument.__init__(self, name)

        self._address = address
        self._visa = visa.instrument(self._address,
                        baud_rate=9600, data_bits=8, stop_bits=1,
                        parity=visa.no_parity, term_chars='\r\n')
Example #26
0
    def __init__(self, name, datafile='', dataset='A', datadirectory=''):
        Instrument.__init__(self, name, tags=['physical'])

        logging.info("LCR_logreader: Initializing")

        self._datafile=datafile
        self._dataset=dataset
        self._datadirectory=datadirectory
        
        if self._datafile == '' and self._datadirectory=='' and self._dataset=='':
            logging.error("LCR_logreader: Error: no datadirectory or datafile specified.")
            return False

        self.add_parameter('impedance', type=types.FloatType,
                flags=Instrument.FLAG_GET,
                units='Ohm',
                format='%.3g')

        self.add_parameter('temperature', type=types.FloatType,
                flags=Instrument.FLAG_GET,
                units='mK',
                format='%.4f')

        self.add_parameter('last_update', type=types.StringType,
                           flags=Instrument.FLAG_GET)
        
        self.add_parameter('filename', type=types.StringType,
                           flags=Instrument.FLAG_GET)                

        self.get_all()        
    def __init__(self, name, address, reset=False):
        Instrument.__init__(self, name)

        self._address = address
        self._visa = visa.instrument(self._address)
        self._channels = ('A', 'B', 'C', 'D')
        
        self.add_parameter('identification',
            flags=Instrument.FLAG_GET)

        self.add_parameter('kelvin',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            channels=self._channels,
            units='K')

        self.add_parameter('sensor',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            channels=self._channels,
            units='')

        self.add_parameter('heater_range',
            flags=Instrument.FLAG_GETSET,
            type=types.IntType,
            format_map={
                1: '25 W',
                2: '2.5 W',
                3: '250 mW',
                4: '25 mW',
                5: '2.5 mW',
                })

        self.add_parameter('heater_output',
            flags=Instrument.FLAG_GET,
            type=types.FloatType,
            units='%')

        self.add_parameter('mode',
            flags=Instrument.FLAG_GETSET,
            type=types.IntType,
            format_map={1: 'Local', 2: 'Remote', 3: 'Remote, local lock'})

        self.add_parameter('pid',
            flags=Instrument.FLAG_GETSET,
            type=types.TupleType,
            channels=(1,4))

        self.add_parameter('setpoint',
            flags=Instrument.FLAG_GETSET,
            type=types.FloatType,
            channels=(1,4))

        self.add_function('local')
        self.add_function('remote')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #28
0
    def __init__(self, name, source=None, channel = 0, stepsize = 2e-9, stepdelay=1):
        '''
            virtual magnet built upon yokogawa source
        '''
        Instrument.__init__(self, name, tags=['virtual'])
        self._instruments = instruments.get_instruments()
        self._source= self._instruments.get(source)
        self._channel = channel        
        # Add parameters        
        self.add_parameter('current', type=types.FloatType,
            flags=Instrument.FLAG_GETSET, units='A')
        self.add_parameter('stepsize', type=types.FloatType,
            flags=Instrument.FLAG_GETSET, units='A')        
        self.add_parameter('range', type=types.FloatType,
            flags=Instrument.FLAG_GETSET, units='A')        
        self.add_parameter('stepdelay', type=types.FloatType,
            flags=Instrument.FLAG_GETSET, units='ms')

        self._stepsize = stepsize
        self._stepdelay = stepdelay
        getattr(self._source, 'set_ch%d_sweep_mode'%channel)('fix')
        getattr(self._source, 'set_ch%d_source_mode'%channel)('curr')
        getattr(self._source, 'set_ch%d_sense_mode'%channel)('curr')

        self.get_all()
Example #29
0
    def __init__(self, name, address, reset=False):
        '''
        Initializes the Agilent_E8257D, and communicates with the wrapper.

        Input:
          name (string)    : name of the instrument
          address (string) : GPIB address
          reset (bool)     : resets to default values, default=False
        '''
        logging.info(__name__ + ' : Initializing instrument Agilent_E8257D')
        Instrument.__init__(self, name, tags=['physical'])

        # Add some global constants
        self._address = address
        self._visainstrument = visa.instrument(self._address)

        self.add_parameter('power',
            flags=Instrument.FLAG_GETSET, units='dBm', minval=-135, maxval=16, type=types.FloatType)
        self.add_parameter('phase',
            flags=Instrument.FLAG_GETSET, units='rad', minval=-numpy.pi, maxval=numpy.pi, type=types.FloatType)
        self.add_parameter('frequency',
            flags=Instrument.FLAG_GETSET, units='Hz', minval=1e5, maxval=20e9, type=types.FloatType)
        self.add_parameter('status',
            flags=Instrument.FLAG_GETSET, type=types.StringType)
        self.add_parameter('ALC',
            flags=Instrument.FLAG_GETSET, type=types.StringType)

        self.add_function('reset')
        self.add_function ('get_all')


        if (reset):
            self.reset()
        else:
            self.get_all()
Example #30
0
  def __init__(self, name, address, reset=False):
    logging.info(__name__ + ' : Initializing instrument Newport ESP100')
    Instrument.__init__(self, name, tags=['physical'])

    self._address = address
    self._visainstrument = visa.instrument(self._address)
    
    # Add functions
    self.add_function('init_default')
    self.add_function('define_home')
    self.add_function('move_1000mu_p')
    self.add_function('move_0100mu_p')
    self.add_function('move_0010mu_p')
    self.add_function('move_0001mu_p')
    self.add_function('move_1000mu_n')
    self.add_function('move_0100mu_n')
    self.add_function('move_0010mu_n')
    self.add_function('move_0001mu_n')
    
    # Add parameters
    self.add_parameter('position',tags=['sweep'],
      flags=Instrument.FLAG_GETSET, units='mm', minval=-300, maxval=300, type=types.FloatType)
    self.add_parameter('ismoving',
      flags=Instrument.FLAG_GET, type=types.StringType)    

    #self.init_default()
	  
    if reset:
      self.init_default()
Example #31
0
    def __init__(self, name, address="localhost", port=9999):
        #logging.info(__name__ + ' : Initializing TIP client')
        Instrument.__init__(self, name, tags=['physical'])

        # Add some global constants
        self._address = address
        self._port = port

        self.setup(address, port)
        self.add_function('setup')
        self.add_function('send')
        self.add_function('recv')
        self.add_function('r_set_T')
        self.add_function('r_get_T')
        self.add_function('new_T')
        self.add_function('close')

        self.add_parameter('T',
                           flags=Instrument.FLAG_GETSET,
                           type=types.FloatType,
                           units='K')

        self.T = 0.0
Example #32
0
    def __init__(self, name, address):
        '''
        Initialzes the IVVIDIG, and communicates with the wrapper

        Input:
            name (string)        : name of the instrument
            address (string)     : ASRL address
        Output:
            None
        '''
        logging.info(__name__ + ' : Initializing instrument IVVIDIG')
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address

        #FIXME: numdacs is now variable!?
        self._numdacs = 16

        # Add functions
        #self.add_function('get_dac')
        self.add_function('set_dac')

        self._open_serial_connection()
Example #33
0
    def __init__(self, name, address, reset=False):
        Instrument.__init__(self, name)

        self._address = address


        self.add_parameter('identification',
            flags=Instrument.FLAG_GET)

        self.add_parameter('toggle_enable',
            flags=Instrument.FLAG_GETSET,
            type=types.BooleanType)

        self.add_parameter('mode',
            flags=Instrument.FLAG_GETSET,
            type=types.IntType,
            format_map={
               1: 'Manual',
               2: 'Auto',
               3: 'Single',
               4: 'Repeat',
               5: 'External'
            })




        self.add_parameter('closed',
            flags=Instrument.FLAG_GET,
            type=types.BooleanType)

        self.add_function('buffer_clear')

        self._open_serial_connection()
        self.buffer_clear()

        self.get_all()
Example #34
0
    def __init__(self, name, address, reset=False):
        '''
        Initializes the RS_SMR40, and communicates with the wrapper.

        Input:
            name (string)    : name of the instrument
            address (string) : GPIB address
            reset (bool)     : resets to default values, default=false

        Output:
            None
        '''
        logging.info(__name__ + ' : Initializing instrument')
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address
        self._visainstrument = visa.instrument(self._address)

        self.add_parameter('frequency', type=types.FloatType,
            flags=Instrument.FLAG_GETSET | Instrument.FLAG_GET_AFTER_SET,
            minval=1e9, maxval=40e9,
            units='Hz', format='%.04e',
            tags=['sweep'])
        self.add_parameter('power', type=types.FloatType,
            flags=Instrument.FLAG_GETSET | Instrument.FLAG_GET_AFTER_SET,
            minval=-30, maxval=25, units='dBm',
            tags=['sweep'])
        self.add_parameter('status', type=types.StringType,
            flags=Instrument.FLAG_GETSET | Instrument.FLAG_GET_AFTER_SET)

        self.add_function('reset')
        self.add_function('get_all')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #35
0
    def __init__(self, name, interface, ethertype):
        '''
        Initializes the Oxford Instruments Kelvinox IGH Dilution Refrigerator.

        Input:
            name (string)    : name of the instrument
            interface (string) : label of the network interface used

        Output:
            None
        '''
        logging.debug(__name__ + ' : Initializing instrument')
        Instrument.__init__(self, name, tags=['physical'])

        self._interface = interface
        self._ethertype = int(ethertype)
        self._queues = {}
        self._monitor = None # will receive all packets if set to a Queue object
        self._receiver = self.receiver(name = 'node_rx', args = (self))
        self._receiver.daemon = True
        self._updateLock = threading.Lock()

        #Add parameters
        self.add_parameter('interface', type=types.StringType, flags=Instrument.FLAG_GET)
        self.add_parameter('ethertype', type=types.IntType, flags=Instrument.FLAG_GET)
        self.add_parameter('MACs', type=types.ListType, flags=Instrument.FLAG_GET)
        self.add_parameter('rcvbuf', type=types.IntType, flags=Instrument.FLAG_GETSET)
        self.add_parameter('monitoring', type.types.BooleanType, flags.Instrument.FLAG_GETSET)

        # Add functions
        self.add_function('register')
        self.add_function('unregister')
        self.add_function('monitor')
        self.add_function('send')

        # open socket
        self._init()
    def __init__(self, name, address):
        '''
        Initializes the any_device, and communicates with the wrapper.

        Input:
            name (string)           : name of the instrument
            address (string)        : GPIB address
            reset (bool)            : resets to default values
           
        Output:
            None
        '''
        # Initialize wrapper functions
        logging.info('Initializing instrument')
        Instrument.__init__(self, name, tags=['virtual'])

        # Add some global constants
        self._address = address
        self._visainstrument = visa.instrument(self._address)

        # Add parameters to wrapper

        self.add_parameter('start_frequency', type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           units='Hz', minval=10e6, maxval=13500e6)





         
        # Add functions to wrapper
        self.add_function('set_mode_volt_ac')

        # Connect to measurement flow to detect start and stop of measurement
        qt.flow.connect('measurement-start', self._measurement_start_cb)
        qt.flow.connect('measurement-end', self._measurement_end_cb)
Example #37
0
    def __init__(self, name, reset=False):
        Instrument.__init__(self, name)

        self.add_parameter('frequency',
                type=types.FloatType,
                flags=Instrument.FLAG_GETSET | \
                Instrument.FLAG_GET_AFTER_SET,
                minval=0, maxval=20e9,
                units='Hz')
        self.add_parameter('power',
                type=types.FloatType,
                flags=Instrument.FLAG_GETSET | \
                Instrument.FLAG_GET_AFTER_SET,
                minval=-120, maxval=25,
                units='dBm')
        self.add_parameter('phase',
                type=types.FloatType,
                flags=Instrument.FLAG_GETSET | \
                Instrument.FLAG_GET_AFTER_SET,
                minval=-180, maxval=180)
        self.add_parameter('status',
                type=types.StringType,
                option_list=('on', 'off'),
                flags=Instrument.FLAG_GETSET | \
                Instrument.FLAG_GET_AFTER_SET)

        # these are dummy values for an instrument that
        # is already running
        self._dummy_frequency = -99
        self._dummy_power = -99
        self._dummy_phase = -99
        self._dummy_status = 'on'

        if reset:
            self.reset()
        else:
            self.get_all()
Example #38
0
    def __init__(self, name, serial):
        '''
		Initializes the Labbrick, and communicates with the wrapper.

		Input:
		  name (string)    : name of the instrument
		  serial (int)  : serial number
		'''
        logging.info(__name__ + ' : Initializing instrument Labbrick')
        Instrument.__init__(self, name, tags=['physical'])

        devices = get_labbricks()
        for device_id, device in devices.items():
            if device['serial_number'] == serial:
                self._device_id = device_id
                self._device_name = device['name']

        if not hasattr(self, '_device_id'):
            raise ValueError(
                'Labbrick with serial number {0} not found'.format(serial))

        _labbrick.set_test_mode(False)
        _labbrick.init_device(self._device_id)

        # Add some global constants
        self._serial_number = serial

        self.add_parameter('power',
         flags=Instrument.FLAG_GETSET, units='dBm', minval=4*_labbrick.get_min_pwr(self._device_id), \
         maxval=4*_labbrick.get_max_pwr(self._device_id), type=float)
        self.add_parameter('frequency',
         flags=Instrument.FLAG_GETSET, units='Hz', minval=_labbrick.get_min_freq(self._device_id)*10, \
         maxval=_labbrick.get_max_freq(self._device_id)*10, type=float)
        self.add_parameter('status', flags=Instrument.FLAG_GETSET, type=bool)

        self.add_function('get_all')
        self.get_all()
Example #39
0
class StrategyNeural:
    def __init__(self):
        self.position = Position()
        self.instrument = Instrument()
        self.neural_network = NeuralNetwork()

    def execute(self):
        if not self.position.has_open_position():
            params = self.builder_params()
            candles = self.instrument.get_candles(params)
            open, high, low, close, volume = self.candles2array(candles)

            operation = self.neural_network.predict(open, high, low, close, volume)

            self.execute_trade(operation)

    def builder_params(self):
        return {'instrument': 'EUR_USD', 'granularity': 'M5', 'count': 170}

    def candles2array(self, candles):
        open = []
        high = []
        low = []
        close = []
        volume = []

        for candle in candles:
            mid = candle.mid
            open.append(mid.o)
            high.append(mid.h)
            low.append(mid.l)
            close.append(mid.c)
            volume.append(candle.volume)

        return numpy.array(open, dtype=float), \
               numpy.array(high, dtype=float), \
               numpy.array(low, dtype=float), \
               numpy.array(close, dtype=float), \
               numpy.array(volume, dtype=float)

    def execute_trade(self, operation):
        params = {}
        params['instrument'] = 'EUR_USD'
        params['take_profit'] = 0.002
        params['stop_loss'] = 0.002
        if operation == 1:
            Buy().execute(params)
        elif operation == 2:
            Sell().execute(params)
Example #40
0
    def __init__(self, name, address):
        '''
        Initializes the LeCroy 44Xi.

        Input:
            name (string)    : name of the instrument
            address (string) : VICP address

        Output:
            None
        '''
        logging.debug(__name__ + ' : Initializing instrument')
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address
        self._visainstrument = visa.instrument(self._address)
        self._values = {}

        # Add parameters
        self.add_parameter('timebase',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET)
        self.add_parameter('vertical',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 4),
                           channel_prefix='ch%d_')
        self.add_parameter('msize',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET)

        # Make Load/Delete Waveform functions for each channel
        for ch in range(1, 5):
            self._add_save_data_func(ch)

        self.get_all()
Example #41
0
    def __init__(self, name, address, reset=False):
        Instrument.__init__(self, name)

        self._address = address
        self._visa = visa.instrument(self._address,
                                     baud_rate=115200,
                                     data_bits=8,
                                     stop_bits=1,
                                     parity=visa.no_parity,
                                     term_chars='\r\n')

        self.add_parameter('identification', flags=Instrument.FLAG_GET)

        self.add_parameter('power',
                           flags=Instrument.FLAG_GET,
                           type=types.FloatType,
                           units='W')

        self.add_parameter('head_info',
                           flags=Instrument.FLAG_GET,
                           type=types.StringType)

        self.add_parameter('wavelength',
                           flags=Instrument.FLAG_GETSET,
                           type=types.FloatType,
                           units='m')

        self.add_parameter('filter_freq',
                           flags=Instrument.FLAG_GETSET,
                           type=types.IntType,
                           units='Hz')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #42
0
    def processFile(self, input, output, open_file=False):
        Instrument.reset()

        self.logger.log(
            'processing file: ' + self.logger.color(input, self.logger.YELLOW),
            True)
        content = Util.openFile(input)

        whistle = WarpWhistle(content, self.logger, self.options)
        whistle.import_directory = os.path.dirname(input)

        while whistle.isPlaying():
            open_file = open_file and whistle.first_run

            song = whistle.play()

            new_output = output
            if song[1] is not None:
                new_output = new_output.replace('.mml', '_' + song[1] + '.mml')

            self.handleProcessedFile(song[0], new_output, open_file)

        if self.options['separate_voices']:
            self.logger.log("")
Example #43
0
    def __init__(self, name, reset=False):
        Instrument.__init__(self, name)

        self.add_parameter('wavelength',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GET,
                           units='nm')
        self.add_parameter('frequency',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GET,
                           units='THz')
        self.add_parameter('linewidth',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GET,
                           units='THz')
        self.add_parameter('power',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GET,
                           units='microW')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #44
0
    def __init__(self, name, anc=None, arc=None, channels=3):
        Instrument.__init__(self, name, tags=['positioner'])

        self._anc = qt.instruments[anc]
        self._arc = qt.instruments[arc]

        # Instrument parameters
        self.add_parameter('position',
                           type=types.TupleType,
                           flags=Instrument.FLAG_GET,
                           format='%.03f, %.03f, %.03f')
        self.add_parameter('speed',
                           type=types.TupleType,
                           flags=Instrument.FLAG_GETSET)
        self.add_parameter('channels',
                           type=types.IntType,
                           flags=Instrument.FLAG_SET | Instrument.FLAG_SOFTGET)

        self.set_channels(channels)

        # Instrument functions
        self.add_function('start')
        self.add_function('stop')
        self.add_function('move_abs')
Example #45
0
    def __init__(self, name, set_eprime_func,get_eprime_func,get_E_func,get_Y_func,set_strain_splitting_func, **kw):
        Instrument.__init__(self, name)
       
        ins_pars  = {'read_interval'   :   {'type':types.FloatType,'flags':Instrument.FLAG_GETSET,'unit':'s', 'val': 1.},
                    'is_running'       :   {'type':types.BooleanType,'flags':Instrument.FLAG_GETSET, 'val': False},
                    'E_y'              :   {'type':types.BooleanType,'flags':Instrument.FLAG_GETSET, 'val': True},
                    'offset'           :   {'type':types.FloatType,  'flags':Instrument.FLAG_GETSET, 'unit':'GHz', 'val': 0.},
                    'precision'        :   {'type':types.FloatType,  'flags':Instrument.FLAG_GETSET, 'unit':'GHz', 'val': 0.05},
                    'yellow_z_factor'  :   {'type':types.FloatType,  'flags':Instrument.FLAG_GETSET, 'unit':'GHz', 'val': 4.2},
                    'yellow_x_factor'  :   {'type':types.FloatType,  'flags':Instrument.FLAG_GETSET, 'unit':'GHz', 'val': 0.2},
                    'strain_splitting' :   {'type':types.FloatType,  'flags':Instrument.FLAG_GET, 'unit':'GHz', 'val': 0.},
                    }           
        instrument_helper.create_get_set(self,ins_pars)
        
        self.add_function('start')        
        self.add_function('stop')
        
        self._get_E_func=get_E_func
        self._get_Y_func=get_Y_func
        self._set_eprime_func = set_eprime_func
        self._get_eprime_func = get_eprime_func
        self._set_strain_splitting_func = set_strain_splitting_func

        self._timer=-1

    # override from config    ----------   
        cfg_fn = os.path.abspath(
                os.path.join(qt.config['ins_cfg_path'], name+'.cfg'))
        if not os.path.exists(cfg_fn):
            _f = open(cfg_fn, 'w')
            _f.write('')
            _f.close()
        self._parlist = ['read_interval', 'E_y', 'offset','yellow_z_factor', 'yellow_x_factor','precision']
        self.ins_cfg = config.Config(cfg_fn)
        self.load_cfg()
        self.save_cfg()
Example #46
0
 def __init__(self,
              name='sample',
              notes=[],
              bpm=120,
              instrument=Instrument("Piano", 1),
              volume=100,
              octave=4,
              actual_time=0):
     self.actual_time = actual_time
     self.instrument = instrument
     self.octave = octave
     self.name = name
     self.notes = notes
     self.bpm = bpm
     self.volume = volume
     self.midi_file = MIDIFile(1)
Example #47
0
 def compose(self, mood, index):
     if index < min(self.num_chord, len(self.tonalities)):
         self.tonality = self.tonalities[index]
     else:
         self.tonality = self.tonalities[-1]
     melody_param = self.generate_melody_parameter(mood)
     harmony_param = self.generate_harmony_parameter(mood)
     max_dynamic = 0
     if index >= self.num_chord:
         pattern = MIDI.new_pattern()
         pattern.append(Generator.generate_track([], melody_param['tempo'] * self.tempo_multiplier))
         pattern.append(Generator.generate_track([], melody_param['tempo'] * self.tempo_multiplier))
         pattern.append(Generator.generate_track([], harmony_param['tempo'] * self.tempo_multiplier))
         pattern.append(Generator.generate_track([], harmony_param['tempo'] * self.tempo_multiplier))
     else:
         (melody_annotated_notes, adjustable, max_dynamic) = self.generate_melody(melody_param, index)
         Generator.adjust_mode_for_harmony(adjustable, self.tonality, melody_param, harmony_param)
         self.adjusted_progressions = Composer.adjust_progression(self.progression_notations, self.annotated_important_notes, harmony_param)
         harmony_annotated_notes = self.generate_harmony(harmony_param, index)
         melody_track = Generator.generate_track(melody_annotated_notes, melody_param['tempo'] * self.tempo_multiplier)
         harmony_track = Generator.generate_track(harmony_annotated_notes, melody_param['tempo'] * self.tempo_multiplier)
         harmony_track_split = MIDI.separate_track(harmony_track, num_track = 2)
         
         pattern = MIDI.new_pattern()
         pattern.append(melody_track)
         for track in harmony_track_split:
             pattern.append(track)
     
     # set tonality
     if melody_param['mode'][0] > 0:
         tonality = {'mode': 'Major', 'key': self.tonality['key']}
     elif melody_param['mode'][0] < 0:
         tonality = {'mode': 'Minor', 'key': self.tonality['key']}
     else:
         tonality = {'mode': self.tonality['mode'], 'key': self.tonality['key']}
         
     (instruments, seed_change) = Instrument.get_instruments(mood, Generator.seed)
     Generator.seed_change_tmp = seed_change
     tonality_name_major = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']
     tonality_name_minor = ['C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'G#', 'A', 'Bb', 'B']
     if tonality['mode'] == 'Major':
         print tonality_name_major[tonality['key']], 'Major'
     else:
         print tonality_name_minor[tonality['key']], 'Minor'
     
     dynamic_offset = Generator.gen_dynamic_parameter(mood) + (max_dynamic - 80)
     return (pattern, tonality, instruments, dynamic_offset)
Example #48
0
    def addInstrument(self, name, content):
        if name == 'end':
            raise Exception(
                'end is a reserved word and connt be used for an instrument')

        lines = content.strip().split('\n')
        data = {}

        for line in lines:
            line = line.strip()
            match = re.match(r'^@extends {1,}(\'|\")(.*)(\1)$', line)
            if match:
                data["extends"] = match.group(2)
                continue

            data[line.split(':', 1)[0].strip()] = line.split(':', 1)[1].strip()

        self.instruments[name] = Instrument(data)
Example #49
0
    def compose(self, mood):
        self.tonality = {'key': 0, 'mode': 'Major'}
        melody_param = self.generate_melody_parameter(mood)
        melody_track = Generator.generate_track([], melody_param['tempo'] *
                                                self.tempo_multiplier)

        harmony_param = self.generate_harmony_parameter(mood)
        # self.adjusted_progressions = Composer.adjust_progression(self.progression_notations, self.annotated_important_notes, harmony_param)
        harmony_annotated_notes = self.generate_harmony(harmony_param)
        harmony_track = Generator.generate_track(
            harmony_annotated_notes,
            harmony_param['tempo'] * self.tempo_multiplier)
        harmony_track_split = MIDI.separate_track(harmony_track, num_track=2)
        pattern = MIDI.new_pattern()
        pattern.append(melody_track)
        for track in harmony_track_split:
            pattern.append(track)

        # set tonality
        if melody_param['mode'][0] > 0:
            tonality = {'mode': 'Major', 'key': self.tonality['key']}
        elif melody_param['mode'][0] < 0:
            tonality = {'mode': 'Minor', 'key': self.tonality['key']}
        else:
            tonality = {
                'mode': self.tonality['mode'],
                'key': self.tonality['key']
            }

        (instruments,
         seed_change) = Instrument.get_instruments(mood, Generator.seed)
        Generator.seed_change_tmp = seed_change
        tonality_name_major = [
            'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'
        ]
        tonality_name_minor = [
            'C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'G#', 'A', 'Bb', 'B'
        ]
        if tonality['mode'] == 'Major':
            print tonality_name_major[tonality['key']], 'Major'
        else:
            print tonality_name_minor[tonality['key']], 'Minor'
        return (pattern, tonality, instruments)
Example #50
0
 def _parseRow(self, csvRowDict, basepath):
     '''Parses one row in the manifest file.'''
     description = csvRowDict["description"]
     symbol = csvRowDict["symbol"]
     pointValue = float(csvRowDict["pointValue"])
     currency = csvRowDict["currency"]
     exchange = csvRowDict["exchange"]
     initialMargin = float(csvRowDict["initialMargin"])
     maintMargin = float(csvRowDict["maintMargin"])
     sector = csvRowDict["sector"]
     datafile = basepath + '/' + csvRowDict["datafile"]
     if symbol.find('?') == -1:
         return Instrument(symbol, datafile, pointValue = pointValue, \
                           currency = currency, exchange = exchange, \
                           initialMargin = initialMargin, maintMargin = maintMargin, \
                           sector = sector, description = description)
     else:
         logger.warning('Skipping unknown symbol %s' % symbol)
         return None
Example #51
0
def test_1():
  # This should produce an exception since the
  # de-preprocessed file is empty
  got_exception = False
  try:
    preFileName = PRE_PROCESSED
    sourceFileName = SOURCE
    inst = Instrument(preFileName, sourceFileName)
    inst.deprocess()
    inst.findDeviceDeclarations()
  except EmptyFileException:
    got_exception = True

  assert got_exception
 def get_instrument(self, instmt_id):
     """
     Return the instrument object by instrument id
     :param instmt_id: Instrument ID
     :return Instrument object
     """
     exchange_name = self.config.get(instmt_id, 'exchange')
     instmt_name = self.config.get(instmt_id, 'instmt_name')
     instmt_code = self.config.get(instmt_id, 'instmt_code')
     enabled = int(self.config.get(instmt_id, 'enabled'))
     params = dict(self.config.items(instmt_id))
     del params['exchange']
     del params['instmt_name']
     del params['instmt_code']
     del params['enabled']
     
     if enabled == 1:
         return Instrument(exchange_name, instmt_name, instmt_code, **params)
     else:
         return None
Example #53
0
def decode_instrument(data, name):
    flags, finetune, fixed_note = struct.unpack("<hBB", data[0:4])

    voice1 = decode_voice(data[4:20], name)
    offset1 = voice1["note_offset"]

    # Second voice?

    if (flags & FLAG_TWO_VOICE) != 0:
        voice2 = decode_voice(data[20:], name)
        offset2 = voice2["note_offset"]
    else:
        voice2 = None
        offset2 = 0

    # Null out fixed_note if the fixed pitch flag isn't set:

    if (flags & FLAG_FIXED_PITCH) == 0:
        fixed_note = None

    return Instrument(
        voice1, voice2, off1=offset1, off2=offset2, note=fixed_note
    )
    def get_instrument(self, instmt_id):
        """
        Return the instrument object by instrument id
        :param instmt_id: Instrument ID
        :return Instrument object
        """
        exchange_name = self.config.get(instmt_id, 'exchange')
        candle_table = self.config.get(instmt_id, 'candle_table')
        frequency = self.config.get(instmt_id, 'frequency')
        enabled = int(self.config.get(instmt_id, 'enabled'))
        base = self.config.get(instmt_id, 'base')
        base_table = self.config.get(instmt_id, 'base_table')
        params = dict(self.config.items(instmt_id))
        del params['exchange']
        del params['candle_table']
        del params['frequency']
        del params['enabled']
        del params['base']
        del params['base_table']

        if enabled == 1:
            return Instrument(exchange_name, candle_table, int(frequency), base, base_table, **params)
        else:
            return None
Example #55
0
    def __init__(self, name, address, channel_index = 1):
        '''
        Initializes 

        Input:
            name (string)    : name of the instrument
            address (string) : GPIB address
        '''
        
        logging.info(__name__ + ' : Initializing instrument')
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address
        self._visainstrument = visa.instrument(self._address)
        self._zerospan = False
        self._freqpoints = 0
        self._ci = channel_index 
        self._start = 0
        self._stop = 0
        self._nop = 0

        # Implement parameters
        self.add_parameter('nop', type=types.IntType,
            flags=Instrument.FLAG_GETSET,
            minval=1, maxval=100000,
            tags=['sweep'])

        self.add_parameter('bandwidth', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,
            minval=0, maxval=1e9,
            units='Hz', tags=['sweep']) 

        self.add_parameter('averages', type=types.IntType,
            flags=Instrument.FLAG_GETSET,
            minval=1, maxval=1024, tags=['sweep'])                    

        self.add_parameter('Average', type=types.BooleanType,
            flags=Instrument.FLAG_GETSET)   

        self.add_parameter('centerfreq', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,
            minval=0, maxval=20e9,
            units='Hz', tags=['sweep'])

        self.add_parameter('cwfreq', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,
            minval=0, maxval=20e9,
            units='Hz', tags=['sweep'])

        self.add_parameter('startfreq', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,
            minval=0, maxval=20e9,
            units='Hz', tags=['sweep'])            

        self.add_parameter('stopfreq', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,
            minval=0, maxval=20e9,
            units='Hz', tags=['sweep'])                        

        self.add_parameter('span', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,
            minval=0, maxval=20e9,
            units='Hz', tags=['sweep'])        

        self.add_parameter('power', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,
            minval=-25, maxval=30,
            units='dBm', tags=['sweep'])

        self.add_parameter('cw', type=types.BooleanType,
            flags=Instrument.FLAG_GETSET)

        self.add_parameter('zerospan', type=types.BooleanType,
            flags=Instrument.FLAG_GETSET)

        self.add_parameter('channel_index', type=types.IntType,
            flags=Instrument.FLAG_GETSET)     

        self.add_parameter('source_attenuation', type=types.IntType,
            flags=Instrument.FLAG_GETSET,channels=(1,2),
            minval=0, maxval=60,
            units='dB', tags=['sweep'])
            
        self.add_parameter('source_power_start', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,channels=(1,2),
            minval=-2.9e1, maxval=3e1,
            units='dBm', tags=['sweep'])
            
        self.add_parameter('source_power_stop', type=types.FloatType,
            flags=Instrument.FLAG_GETSET,channels=(1,2),
            minval=-2.9e1, maxval=3e1,
            units='dBm', tags=['sweep'])
            
        self.add_parameter('calibration_state', type=types.BooleanType,
            flags=Instrument.FLAG_GETSET) 
        
        self.add_parameter('sweep_type', type=types.StringType,
            flags=Instrument.FLAG_GETSET,tags=['sweep']) 
            
        self.add_parameter('power_nop', type=types.IntType,
            flags=Instrument.FLAG_GETSET,channels=(1,2),
            minval=0, maxval=60,
            tags=['sweep'])
        
        self.add_parameter('avg_type', type=types.StringType,
            flags=Instrument.FLAG_GETSET,tags=['sweep']) 
        
        self.add_parameter('edel', type=types.FloatType,   #added by MW
            flags=Instrument.FLAG_GETSET,
            minval=0, maxval=1e-3,
            units='s', tags=['sweep'])
        
        self.add_parameter('sweeptime', type=types.FloatType,   #JB
            flags=Instrument.FLAG_GET,
            minval=0, maxval=1e-3,
            units='s', tags=['sweep'])
            
        self.add_parameter('sweeptime_averages', type=types.FloatType,   #JB
            flags=Instrument.FLAG_GET,
            minval=0, maxval=1e-3,
            units='s', tags=['sweep'])
                    
        #Triggering Stuff
        self.add_parameter('trigger_source', type=types.StringType,
            flags=Instrument.FLAG_GETSET)
        
        # Implement functions
        self.add_function('get_freqpoints')
        self.add_function('get_tracedata')
        self.add_function('init')
        self.add_function('returnToLocal')
        self.add_function('pre_measurement')
        self.add_function('start_measurement')
        self.add_function('ready')
        self.add_function('post_measurement')
        self.add_function('avg_clear')
        self.add_function('avg_status')
        
        #self._oldspan = self.get_span()
        #self._oldnop = self.get_nop()
        #if self._oldspan==0.002:
        #  self.set_zerospan(True)
        
        self.get_all()
Example #56
0
    def __init__(self, name, address, reset=False):
        '''
        Initializes the Keysight_33500B, and communicates with the wrapper.

        Input:
            name (string)    : name of the instrument
            address (string) : GPIB, TCPIP or USB address
            reset (bool)     : resets to default values, default=false

        Output:
            None
        '''
        logging.info('Initializing Keysight 33500B series AWG')
        Instrument.__init__(self, name, tags=['physical'])

        self._address = address
        self._visainstrument = visa.instrument(self._address)
        self._visainstrument.term_chars = '\n'
        self._idn = self._visainstrument.ask('*IDN?')
        self._model = self._idn.split(',')[1]
        self._channels = (1, 2)
        self._installed_options = self._visainstrument.ask('*OPT?').split(',')
        logging.info('The connected AWG is a {0}'.format(self._model))
        if 'MEM' in self._installed_options:
            logging.info('The extended memory option is installed')
            self._mem_size = 16e6
        else:
            self._mem_size = 1e6
            logging.debug('Extended memory option not installed')
        self._visainstrument.write('FORM:BORD SWAP')  # correct byte order

        # Output
        self.add_parameter(
            'output',
            type=types.BooleanType,
            flags=Instrument.FLAG_GETSET,
            channels=(1, 2),
            channel_prefix='ch%i_',
        )
        self.add_parameter('sync_source',
                           type=types.StringType,
                           flags=Instrument.FLAG_GETSET,
                           option_list=('CH1', 'CH2'))

        # General parameters
        self.add_parameter('frequency',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=1e-6,
                           maxval=30e6,
                           units='Hz')
        self.add_parameter('amplitude',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=1e-3,
                           maxval=5.0,
                           format='%.3f',
                           units='Vpp')
        self.add_parameter('offset',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=-5.0,
                           maxval=5.0,
                           format='%.3f',
                           units='V')
        self.add_parameter(
            'load',
            type=types.FloatType,
            flags=Instrument.FLAG_GETSET,
            channels=(1, 2),
            channel_prefix='ch%i_',
            minval=1.0,
            maxval=10000,
            units='Ohm',
        )

        # Function parameter
        self.add_parameter(
            'apply',
            type=types.StringType,
            flags=Instrument.FLAG_GETSET,
            channels=(1, 2),
            channel_prefix='ch%i_',
        )
        self.add_parameter('function',
                           type=types.StringType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           option_list=('SIN', 'SQU', 'TRI', 'RAMP', 'PULS',
                                        'PRBS', 'NOIS', 'ARB', 'DC'))

        # Burst mode parameters
        self.add_parameter('burst_cycle',
                           type=types.IntType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=1,
                           maxval=1e8,
                           units='#')
        self.add_parameter('burst_state',
                           type=types.StringType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           option_list=('ON', 'OFF'))
        self.add_parameter('burst_mode',
                           type=types.StringType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           option_list=('TRIG', 'GAT'))
        self.add_parameter('burst_gate_polarity',
                           type=types.StringType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           option_list=('NORM', 'INV'))
        self.add_parameter('burst_phase',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=-360.0,
                           maxval=360.0,
                           units='degree')
        self.add_parameter('burst_period',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=1e-6,
                           maxval=8e3,
                           units='second')

        # Pulse mode parameters
        self.add_parameter('pulse_dutycycle',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=0,
                           maxval=100,
                           units='%')
        self.add_parameter('pulse_trans_leading',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=8.4e-9,
                           maxval=1e-6,
                           units='second')
        self.add_parameter('pulse_trans_trailing',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=8.4e-9,
                           maxval=1e-6,
                           units='second')
        self.add_parameter('pulse_width',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=16e-9,
                           maxval=1e6,
                           units='second')

        # Trigger parameters
        self.add_parameter(
            'continuous',
            type=types.BooleanType,
            flags=Instrument.FLAG_GETSET,
            channels=(1, 2),
            channel_prefix='ch%i_',
        )
        self.add_parameter('trigger_source',
                           type=types.StringType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           option_list=('IMM', 'EXT', 'TIM', 'BUS'))
        self.add_parameter('trigger_delay',
                           type=types.FloatType,
                           flags=Instrument.FLAG_GETSET,
                           channels=(1, 2),
                           channel_prefix='ch%i_',
                           minval=0.0,
                           maxval=1e3,
                           units='second')

        # memory
        self.add_parameter(
            'free_volatile_memory',
            type=types.IntType,
            flags=Instrument.FLAG_GET,
            channels=(1, 2),
            channel_prefix='ch%i_',
        )

        # display
        self.add_parameter(
            'display',
            type=types.BooleanType,
            flags=Instrument.FLAG_GET,
        )
        # arbitrary waveform system
        self.add_parameter(
            'arbitrary_waveform',
            type=types.StringType,
            flags=Instrument.FLAG_GETSET,
            channels=(1, 2),
            channel_prefix='ch%i_',
        )
        self.add_parameter(
            'arbitrary_waveform_frequency',
            type=types.FloatType,
            flags=Instrument.FLAG_GET,
            channels=(1, 2),
            channel_prefix='ch%i_',
            units='Hz',
            format='%.1f',
        )
        self.add_parameter(
            'arbitrary_waveform_period',
            type=types.FloatType,
            flags=Instrument.FLAG_GET,
            channels=(1, 2),
            channel_prefix='ch%i_',
            units='s',
        )
        self.add_parameter(
            'arbitrary_waveform_points',
            type=types.IntType,
            flags=Instrument.FLAG_GET,
            channels=(1, 2),
            channel_prefix='ch%i_',
            units='#',
        )
        self.add_parameter(
            'arbitrary_waveform_samplerate',
            type=types.IntType,
            flags=Instrument.FLAG_GETSET,
            channels=(1, 2),
            channel_prefix='ch%i_',
            maxval=62500000,
        )
        self.add_parameter(
            'arbitrary_waveform_filter',
            type=types.StringType,
            flags=Instrument.FLAG_GETSET,
            channels=(1, 2),
            channel_prefix='ch%i_',
            option_list=('NORMAL', 'STEP', 'OFF'),
        )
        self.add_parameter(
            'arbitrary_waveform_peak_to_peak',
            type=types.FloatType,
            flags=Instrument.FLAG_GET,
            channels=(1, 2),
            channel_prefix='ch%i_',
            units='V',
            format='%.3f',
        )

        self.add_function('imm_trigger')
        self.add_function('ext_trigger')
        self.add_function('bus_trigger')
        self.add_function('send_trigger1')
        self.add_function('send_trigger2')
        self.add_function('send_trigger')
        self.add_function('initiate')
        self.add_function('get_volatile_memory_catalog')
        self.add_function('synchronize_waveforms')

        self.add_function('reset')
        self.add_function('get_all')

        if reset:
            self.reset()
        else:
            self.get_all()
Example #57
0
    def __init__(self, name, address, reset=False):
        '''
        Initializes the HP_4195A, and communicates with the wrapper

        Input:
            name (string)    : name of the instrument
            address (string) : GPIB address
            reset (bool)     : resets to default values, default=false
        '''
        Instrument.__init__(self, name)

        self._address = address
        self._visainstrument = visa.instrument(self._address)

        self._visainstrument.timeout = 30
        # BEWARE! in case of low IFWB, it might be
        # necessary to add additional delay
        # ( ~ numpoints / IFBW ) yourself!

        self.add_parameter('resbw',
                           flags=Instrument.FLAG_GETSET,
                           type=types.IntType)
        self.add_parameter('numpoints',
                           flags=Instrument.FLAG_GETSET,
                           type=types.IntType)
        self.add_parameter('start_freq',
                           flags=Instrument.FLAG_GETSET,
                           type=types.FloatType)
        self.add_parameter('stop_freq',
                           flags=Instrument.FLAG_GETSET,
                           type=types.FloatType)
        self.add_parameter('power',
                           flags=Instrument.FLAG_GETSET,
                           type=types.FloatType)
        self.add_parameter('center_freq',
                           flags=Instrument.FLAG_GETSET,
                           type=types.FloatType)
        self.add_parameter('span_freq',
                           flags=Instrument.FLAG_GETSET,
                           type=types.FloatType)
        self.add_parameter('att_t1',
                           flags=Instrument.FLAG_GETSET,
                           type=types.IntType)
        self.add_parameter('att_r1',
                           flags=Instrument.FLAG_GETSET,
                           type=types.IntType)
        self.add_parameter('sweep_time',
                           flags=Instrument.FLAG_GET,
                           type=types.FloatType)

        #self.add_function('set_measurement_S11')
        #self.add_function('set_measurement_S22')
        #self.add_function('set_measurement_S12')
        #self.add_function('set_measurement_S21')
        #self.add_function('set_format_logm')
        #self.add_function('set_format_phas')
        #self.add_function('set_lin_freq')
        #self.add_function('set_log_freq')

        #self.add_function('set_trigger_continuous')
        #self.add_function('set_trigger_single')
        #self.add_function('set_trigger_manual')
        #self.add_function('send_trigger')
        #self.add_function('reset')

        self.get_all()
Example #58
0
    def __init__(self, name, address, ip=""):

        Instrument.__init__(self, name, tags=['physical'])

        self._address = address
        self._visainstrument = visa.instrument(self._address, ip=ip)

        self.set_default()  # reset everything to:

        #REFERENCE / PHASE
        #Phase                  0.000 deg
        #Reference Source       Internal
        #Harmonic               1
        #Sine Amplitude         1.000 Vrms
        #Internal Frequency     1.000 kHz
        #Ext Reference Trigger  Sine
        #
        #INPUT / FILTERS
        #Source                 A
        #Grounding              Float
        #Coupling               AC
        #Line Notches           Out
        #
        #GAIN / TC
        #Sensitivity            1V
        #Reserve                Low Noise
        #Time Constant          100 ms
        #Filter dB/oct.         12 dB
        #Synchronous            Off
        #
        #DISPLAY
        #CH1                    X
        #CH2                    Y
        #Ratio                  None
        #Reference              Frequency
        #
        #OUTPUT / OFFSET
        #CH1 Output             X
        #CH2 Output             Y
        #All Offsets            0.00%
        #All Expands            1
        #
        #AUX OUTPUTS
        #All Output Voltages    0.000 V
        #
        #SETUP
        #Output To              GPIB
        #GPIB Address           8
        #RS232 Baud Rate        9600
        #Parity                 None
        #Key Click              On
        #Alarms                 On
        #Override Remote        On
        #
        #DATA STORAGE
        #Sample Rate            1 Hz
        #Scan Mode              Loop
        #Trigger Starts         No
        #
        #STATUS ENABLE
        #REGISTERS              Cleared

        self.add_function('set_default')
        self.add_function('set_outx')
        self.add_function('get_reference')
        self.add_function('set_reference')
        self.add_function('get_phase_shift')
        self.add_function('set_phase_shift')
        self.add_function('get_frequency')
        self.add_function('set_frequency')
        self.add_function('get_ref_trigger')
        self.add_function('set_ref_trigger')
        self.add_function('get_harmonic')
        self.add_function('set_harmonic')
        self.add_function('get_sine_ampl')
        self.add_function('set_sine_ampl')
        self.add_function('get_input_source')
        self.add_function('set_input_source')
        self.add_function('get_input_shield_gnd')
        self.add_function('set_input_shield_gnd')
        self.add_function('get_input_coupling')
        self.add_function('set_input_coupling')
        self.add_function('get_notch_filters')
        self.add_function('set_notch_filters')
        self.add_function('get_sensitivity')
        self.add_function('set_sensitivity')
        self.add_function('get_reserve_mode')
        self.add_function('set_reserve_mode')
        self.add_function('get_time_constant')
        self.add_function('set_time_constant')
        self.add_function('get_filter_slope')
        self.add_function('set_filter_slope')
        self.add_function('get_sync_filter')
        self.add_function('set_sync_filter')
        self.add_function('get_display_CH1')
        self.add_function('get_display_CH2')
        self.add_function('get_display_CH')
        self.add_function('set_display_CH')
        self.add_function('get_front_panel_output_source_CH1')
        self.add_function('get_front_panel_output_source_CH2')
        self.add_function('get_front_panel_output_source')
        self.add_function('set_front_panel_output_source')
        self.add_function('get_offsets_and_expands_X')
        self.add_function('get_offsets_and_expands_Y')
        self.add_function('get_offsets_and_expands_R')
        self.add_function('get_offsets_and_expands')
        self.add_function('set_offsets_and_expands')
        self.add_function('set_auto_offset_X')
        self.add_function('set_auto_offset_Y')
        self.add_function('set_auto_offset_R')
        self.add_function('set_auto_offset')
        self.add_function('get_aux_input_AUX1')
        self.add_function('get_aux_input_AUX2')
        self.add_function('get_aux_input_AUX3')
        self.add_function('get_aux_input_AUX4')
        self.add_function('get_aux_input')
        self.add_function('get_aux_output')
        self.add_function('get_aux_output_AUX1')
        self.add_function('get_aux_output_AUX2')
        self.add_function('get_aux_output_AUX3')
        self.add_function('get_aux_output_AUX4')
        self.add_function('set_aux_output')
        self.add_function('set_override_remote')
        self.add_function('save_setup')
        self.add_function('recall_setup')
        self.add_function('get_output')
        self.add_function('get_output_X')
        self.add_function('get_output_Y')
        self.add_function('get_output_Z')
        self.add_function('get_output_theta')
        self.add_function('get_snap')
def maintain_equity(symbol_ticker, desired_portion, tolerance):
    """
	Maintains equity of stocks you own to a certain percentage.

	Args:
		symbol_ticker: str of the symbol
		desired_portion: Decimal value of the fraction you want your portfolio
						 to be of this stock
		tolerance: Decimal value of the tolerance you can respect with your
				   desired portion

	Returns:
		list of Orders that are suggested to maintain the desired_portion
	"""
    my_portfolio = Portfolio()
    available_funds = my_portfolio.excess_margin()
    invested_funds = my_portfolio.value(Portfolio.ValueType.MARKET_VALUE)
    equity_instrument = Instrument(Instrument.Type.STOCK, symbol_ticker)

    current_positions = my_portfolio.positions()

    available_quantity = 0.0
    quantity_equity = 0.0

    weights = []
    symbol_quantity = 0
    symbol_value = 0.0

    for position in current_positions:
        check_instrument = Instrument(Instrument.Type.STOCK,
                                      position['symbol'])

        if position['symbol'] == symbol_ticker:
            symbol_quantity, symbol_value = my_portfolio.share_info(
                check_instrument)
            continue

        quantity, value = my_portfolio.share_info(check_instrument)
        heapq.heappush(weights, [-value, quantity, position['symbol']])

    weight = (symbol_quantity * symbol_value) / invested_funds

    difference = desired_portion - weight
    needed_shares_to_buy = 0
    needed_shares_to_sell = 0
    reallocated_funds = invested_funds * difference

    if difference > 0:
        trade = Order.Type.BUY
        needed_shares_to_buy = (reallocated_funds) // symbol_value
    elif difference < 0:
        trade = Order.Type.SELL
        reallocated_funds = reallocated_funds * -1
        needed_shares_to_sell == (reallocated_funds) // symbol_value
    else:
        return

    return_orders = []

    if trade == Order.Type.SELL:
        sell_order = Order(equity_instrument, trade, needed_shares_to_sell,
                           Order.TimeInForce.GFD)
        return_orders += [sell_order]
        trade = Order.Type.BUY
    else:
        buy_order = Order(equity_instrument, trade, needed_shares_to_buy,
                          Order.TimeInForce.GFD)
        return_orders += [buy_order]
        trade = Order.Type.SELL

    lower_bound = reallocated_funds - (reallocated_funds * tolerance)
    upper_bound = reallocated_funds + (reallocated_funds * tolerance)

    total_spent = 0

    while not (within_bounds(lower_bound, upper_bound, total_spent)):
        try:
            [value, quantity, ticker] = weights.pop()
            shares_needed = int((reallocated_funds - total_spent) / value)
            instrument_trade = Instrument(Instrument.Type.STOCK, ticker)
            if shares_needed >= quantity:
                add_to_order = Order(instrument_trade, trade, quantity,
                                     Order.TimeInForce.GFD)
                total_spent += quantity * value
            else:
                add_to_order = Order(instrument_trade, trade,
                                     quantity - shares_needed,
                                     Order.TimeInForce.GFD)
                total_spent += (quantity - shares_needed) * value
            return_orders += [add_to_order]
        except:
            break

    print("Suggested Order List:")
    for order in return_orders:
        print(str(order))
        print("\n##########################################\n")

    return return_orders
Example #60
0
    def __init__(self, name, address, reset=False):
        '''
        Initializes the Rigol_DS1102E, and communicates with the wrapper.

        Input:
            name (string)           : name of the instrument
            address (string)        : GPIB address
            reset (bool)            : resets to default values
            change_display (bool)   : If True (default), automatically turn off
                                        display during measurements.
            change_autozero (bool)  : If True (default), automatically turn off
                                        autozero during measurements.
        Output:
            None
        '''
        # Initialize wrapper functions
        logging.info('Initializing instrument Rigol DM3058')
        Instrument.__init__(self, name, tags=['physical'])

        # Add some global constants
        self._address = address
        self._visainstrument = visa.instrument(self._address)
        self._visainstrument.timeout = 1
        print 'timeout = %s' % self._visainstrument.timeout
        # Add parameters to wrapper

        self.add_parameter('time_resolution',
                           flags=Instrument.FLAG_GETSET,
                           units='s',
                           minval=1e-15,
                           maxval=0.5,
                           type=types.FloatType)
        self.add_parameter('time_scale',
                           flags=Instrument.FLAG_GETSET,
                           units='s/div',
                           minval=2e-9,
                           maxval=50,
                           type=types.FloatType)
        self.add_parameter('record_length',
                           flags=Instrument.FLAG_GETSET,
                           units='',
                           minval=1000,
                           maxval=1e9,
                           type=types.IntType)
        self.add_parameter('time_position',
                           flags=Instrument.FLAG_GETSET,
                           units='s',
                           minval=-500,
                           maxval=500,
                           type=types.FloatType)
        self.add_parameter('time_offset',
                           flags=Instrument.FLAG_GETSET,
                           units='s',
                           minval=-50,
                           maxval=50,
                           type=types.FloatType)
        self.add_parameter('voltage_scale',
                           flags=Instrument.FLAG_GETSET,
                           units='V/div',
                           channels=(1, 4),
                           minval=2e-3,
                           maxval=10e3,
                           type=types.FloatType)
        self.add_parameter('voltage_position',
                           flags=Instrument.FLAG_GETSET,
                           units='div',
                           channels=(1, 4),
                           minval=-5,
                           maxval=5,
                           type=types.FloatType)
        self.add_parameter('voltage_offset',
                           flags=Instrument.FLAG_GETSET,
                           units='V',
                           channels=(1, 4),
                           minval=-40,
                           maxval=40,
                           type=types.FloatType)
        self.add_parameter('memory_depth',
                           flags=Instrument.FLAG_GETSET,
                           type=types.StringType)
        self.add_parameter('waveform_mode',
                           flags=Instrument.FLAG_GETSET,
                           type=types.StringType)
        self.add_parameter('sampling_rate',
                           flags=Instrument.FLAG_GET,
                           units='Sa/s',
                           channels=(1, 4),
                           type=types.FloatType)

        # Add functions to wrapper
        #self.add_function('set_mode_volt_ac')

        # Connect to measurement flow to detect start and stop of measurement
        qt.flow.connect('measurement-start', self._measurement_start_cb)
        qt.flow.connect('measurement-end', self._measurement_end_cb)

        self._visainstrument.write('FORM REAL,32')
        self._visainstrument.write('EXP:WAV:INCX OFF')

        if reset:
            self._visainstrument.write('*RST')
            self._visainstrument.write('DISP OFF')