コード例 #1
0
ファイル: runner.py プロジェクト: xiaowenlong100/enaml
def main():
    usage = 'usage: %prog [options] enaml_file [script arguments]'
    parser = optparse.OptionParser(usage=usage, description=__doc__)
    parser.allow_interspersed_args = False
    parser.add_option('-c',
                      '--component',
                      default='Main',
                      help='The component to view')
    parser.add_option(
        '-t',
        '--toolkit',
        default='default',
        help='The GUI toolkit to use [default: qt or ETS_TOOLKIT].')

    options, args = parser.parse_args()
    toolkit = prepare_toolkit(options.toolkit)

    if len(args) == 0:
        print 'No .enaml file specified'
        sys.exit()
    else:
        enaml_file = args[0]
        script_argv = args[1:]

    with open(enaml_file, 'rU') as f:
        enaml_code = f.read()

    # Parse and compile the Enaml source into a code object
    ast = parse(enaml_code, filename=enaml_file)
    code = EnamlCompiler.compile(ast, enaml_file)

    # Create a proper module in which to execute the compiled code so
    # that exceptions get reported with better meaning
    module = types.ModuleType('__main__')
    module.__file__ = enaml_file
    ns = module.__dict__

    # Put the directory of the Enaml file first in the path so relative
    # imports can work.
    sys.path.insert(0, os.path.abspath(os.path.dirname(enaml_file)))
    # Bung in the command line arguments.
    sys.argv = [enaml_file] + script_argv
    with imports():
        exec code in ns

    requested = options.component
    if requested in ns:
        component = ns[requested]
        descr = 'Enaml-run "%s" view' % requested
        show_simple_view(component(), toolkit, descr)
    elif 'main' in ns:
        ns['main']()
    else:
        msg = "Could not find component '%s'" % options.component
        print msg
コード例 #2
0
ファイル: runner.py プロジェクト: 5n1p/enaml
def main():
    usage = 'usage: %prog [options] enaml_file [script arguments]'
    parser = optparse.OptionParser(usage=usage, description=__doc__)
    parser.allow_interspersed_args = False
    parser.add_option(
        '-c', '--component', default='Main', help='The component to view'
    )
    parser.add_option(
        '-t', '--toolkit', default='default',
        help='The GUI toolkit to use [default: qt or ETS_TOOLKIT].'
    )

    options, args = parser.parse_args()
    toolkit = prepare_toolkit(options.toolkit)

    if len(args) == 0:
        print 'No .enaml file specified'
        sys.exit()
    else:
        enaml_file = args[0]
        script_argv = args[1:]

    with open(enaml_file, 'rU') as f:
        enaml_code = f.read()

    # Parse and compile the Enaml source into a code object
    ast = parse(enaml_code, filename=enaml_file)
    code = EnamlCompiler.compile(ast, enaml_file)

    # Create a proper module in which to execute the compiled code so
    # that exceptions get reported with better meaning
    module = types.ModuleType('__main__')
    module.__file__ = enaml_file
    ns = module.__dict__

    # Put the directory of the Enaml file first in the path so relative
    # imports can work.
    sys.path.insert(0, os.path.abspath(os.path.dirname(enaml_file)))
    # Bung in the command line arguments.
    sys.argv = [enaml_file] + script_argv
    with imports():
        exec code in ns

    requested = options.component
    if requested in ns:
        component = ns[requested]
        descr = 'Enaml-run "%s" view' % requested
        show_simple_view(component(), toolkit, descr)
    elif 'main' in ns:
        ns['main']()
    else:
        msg = "Could not find component '%s'" % options.component
        print msg
コード例 #3
0
        while self._run:
            send = {}
            if self.io_controller.added_links:
                add = self.io_controller.added_links
                self.io_controller.added_links = []
                send['add_link'] = add
            if self.io_controller.removed_links:
                remove = self.io_controller.removed_links
                self.io_controller.removed_links = []
                send['remove_link'] = remove
            if self.io_controller.outputs:
                outputs = self.io_controller.outputs
                self.io_controller.outputs = {}
                send['out'] = outputs
            socket.send(json.dumps(send))
            message = socket.recv()
            self.io_controller.set(**json.loads(message))
        socket.close()


if __name__ == '__main__':
    from enaml.stdlib.sessions import show_simple_view
    with enaml.imports():
        from sensor_view import SensorViewWindow
    ip, port = sys.argv[1].split(':')
    sensor_app = SensorApp(ip=ip, port=port)
    window = SensorViewWindow(io_controller=sensor_app.io_controller)
    show_simple_view(window)
    sensor_app.stop()
コード例 #4
0
#------------------------------------------------------------------------------
#  Copyright (c) 2011, Enthought, Inc.
#  All rights reserved.
#------------------------------------------------------------------------------
import enaml
from enaml.stdlib.sessions import show_simple_view

if __name__ == '__main__':
    with enaml.imports():
        from hello_world_view import Main

    main_view = Main()
    show_simple_view(main_view)
コード例 #5
0
                with open(self.libFile, 'r') as FID:
                    tmpLib = json.load(FID, cls=JSONHelpers.LibraryDecoder)
                    if isinstance(tmpLib, SweepLibrary):
                        self.sweepDict.update(tmpLib.sweepDict)
                        del self.possibleInstrs[:]
                        for instr in tmpLib.possibleInstrs:
                            self.possibleInstrs.append(instr)
                        del self.sweepOrder[:]
                        for sweepStr in tmpLib.sweepOrder:
                            self.sweepOrder.append(sweepStr)
            except IOError:
                print('No sweep library found.')

if __name__ == "__main__":
    from instruments.MicrowaveSources import AgilentN5183A  
    testSource1 = AgilentN5183A(name='TestSource1')
    testSource2 = AgilentN5183A(name='TestSource2')

    from Sweeps import Frequency, Power, SweepLibrary
    # sweepLib = SweepLibrary(possibleInstrs=[testSource1.name, testSource2.name])
    # sweepLib.sweepDict.update({'TestSweep1':Frequency(name='TestSweep1', start=5, stop=6, step=0.1, instr=testSource1.name)
    # sweepLib.sweepDict.update({'TestSweep2':Power(name='TestSweep2', start=-20, stop=0, step=0.5, instr=testSource2.name)
    sweepLib = SweepLibrary(libFile='SweepLibrary.json')
    sweepLib.load_from_library()

    from enaml.stdlib.sessions import show_simple_view

    with enaml.imports():
        from SweepsViews import SweepManagerWindow
    session = show_simple_view(SweepManagerWindow(sweepLib=sweepLib))
コード例 #6
0
        if self.current_sigma < self.min_sigma:
            self.current_sigma = self.min_sigma
        self.weights = np.hstack([np.array(w) for w in weights[::-1]])
        self.current_weight = self.weights[:, 0]

    def sharpe_ratio(self):
        # TODO: use CLA.evalSR() to return Sharpe ratio
        pass

    def _get_weight_interpolater(self):
        return interp1d(self.sigma, self.weights)

    def set_current_weight(self):
        """ Interpolate the weights on the efficient frontier
        """
        try:
            self.current_weight = self.weight_interpolater(self.current_sigma)
            self.bar_data.set_data('value', self.current_weight)
        except Exception, e:
            pass

    def _current_sigma_changed(self):
        self.set_current_weight()


if __name__ == '__main__':
    filename = 'CLA/CLA_Data.csv'
    portfolio = CLAModel(csvfile=filename)
    view = MainView(model=portfolio)
    show_simple_view(view)
コード例 #7
0
ファイル: AWGs.py プロジェクト: eccstartup/PyQLab

class Tek7000(AWG):
    numChannels = 2
    seqFileExt = Constant('.awg')


AWGList = [APS, Tek5014, Tek7000]

if __name__ == "__main__":

    with enaml.imports():
        from AWGViews import AWGView

    awg = APS(name='BBNAPS1')
    session = show_simple_view(AWGView(awg=awg))


def get_empty_channel_set(AWG):
    """
    Helper function to get the set of empty channels when compiling to hardware.
    """
    if isinstance(AWG, Tek5014):
        return {
            'ch12': {},
            'ch34': {},
            'ch1m1': {},
            'ch1m2': {},
            'ch2m1': {},
            'ch2m2': {},
            'ch3m1': {},
コード例 #8
0
                                filt.filters = filterList
                        self.filterDict.update(tmpLib.filterDict)
            except IOError:
                print("No measurement library found.")


if __name__ == "__main__":

    #Work around annoying problem with multiple class definitions
    from MeasFilters import DigitalHomodyne, MeasFilterLibrary

    testFilter1 = DigitalHomodyne(name='M1',
                                  boxCarStart=100,
                                  boxCarStop=500,
                                  IFfreq=10e6,
                                  samplingRate=250e6,
                                  channel=1)
    testFilter2 = DigitalHomodyne(name='M2',
                                  boxCarStart=150,
                                  boxCarStop=600,
                                  IFfreq=39.2e6,
                                  samplingRate=250e6,
                                  channel=2)

    testLib = MeasFilterLibrary(libFile='MeasFilterLibrary.json')
    testLib.filterDict.update({'M1': testFilter1, 'M2': testFilter2})
    from enaml.stdlib.sessions import show_simple_view
    with enaml.imports():
        from MeasFiltersViews import MeasFilterManagerWindow
    session = show_simple_view(MeasFilterManagerWindow(filterLib=testLib))
コード例 #9
0
ファイル: Channels.py プロジェクト: eccstartup/PyQLab
                    if chName in self.channelDict:
                        for paramName in updateList:
                            if paramName in chParams:
                                #Deal with unicode/string difference
                                if paramName == 'pulseParams':
                                    paramDict = {k.encode('ascii'):v for k,v in chParams['pulseParams'].items()}
                                    shapeFunName = paramDict.pop('shapeFun', None)
                                    if shapeFunName:
                                        paramDict['shapeFun'] = getattr(PulseShapes, shapeFunName)
                                    setattr(self.channelDict[chName], 'pulseParams', paramDict)
                                else:
                                    setattr(self.channelDict[chName], paramName, chParams[paramName])


NewLogicalChannelList = [Qubit, LogicalMarkerChannel, Measurement]
NewPhysicalChannelList = [PhysicalMarkerChannel, PhysicalQuadratureChannel]

if __name__ == '__main__':
    # create a channel params file
    import QGL.Channels
    import enaml
    from enaml.stdlib.sessions import show_simple_view

    with enaml.imports():
        from ChannelsViews import ChannelLibraryWindow
    show_simple_view(ChannelLibraryWindow(channelLib=Compiler.channelLib, instrumentLib=instrumentLib))



    
    
コード例 #10
0
ファイル: AWGs.py プロジェクト: circuitqed/PyQLab
    numChannels = 4
    seqFileExt = Constant('.awg')

class Tek7000(AWG):
    numChannels = 2
    seqFileExt = Constant('.awg')

AWGList = [APS, Tek5014, Tek7000]

if __name__ == "__main__":

    with enaml.imports():
        from AWGViews import AWGView
    
    awg = APS(name='BBNAPS1')
    session = show_simple_view(AWGView(awg=awg))


def get_empty_channel_set(AWG):
    """
    Helper function to get the set of empty channels when compiling to hardware.
    """
    if isinstance(AWG, Tek5014):
        return {'ch12':{}, 'ch34':{}, 'ch1m1':{}, 'ch1m2':{}, 'ch2m1':{}, 'ch2m2':{}, 'ch3m1':{}, 'ch3m2':{} , 'ch4m1':{}, 'ch4m2':{}}
    elif isinstance(AWG, Tek7000):
        return {'ch12':{}, 'ch1m1':{}, 'ch1m2':{}, 'ch2m1':{}, 'ch2m2':{}}
    elif isinstance(AWG, APS):
        return {'ch12':{}, 'ch34':{}, 'ch1m1':{}, 'ch2m1':{}, 'ch3m1':{}, 'ch4m1':{}}
    else:
        raise NameError('Unknown AWG type')             
コード例 #11
0
ファイル: MicrowaveSources.py プロジェクト: eccstartup/PyQLab
    gateMinWidth = Float(100e-9)
    gateDelay = Float(-60e-9)


class Labbrick64(MicrowaveSource):
    gateBuffer = Float(20e-9)
    gateMinWidth = Float(100e-9)
    gateDelay = Float(-60e-9)


class HP8673B(MicrowaveSource):
    pass


class HP8340B(MicrowaveSource):
    pass


#List of possible sources for other views
MicrowaveSourceList = [
    AgilentN5183A, HolzworthHS9000, Labbrick, Labbrick64, HP8673B, HP8340B
]

if __name__ == "__main__":
    from MicrowaveSources import AgilentN5183A
    uwSource = AgilentN5183A(name='Agilent1')
    with enaml.imports():
        from MicrowaveSourcesView import MicrowaveSourceView

    session = show_simple_view(MicrowaveSourceView(uwSource=uwSource))
コード例 #12
0
ファイル: Digitizers.py プロジェクト: circuitqed/PyQLab
	nbrSegments = Int(1, desc='Number of segments in memory')
	nbrWaveforms = Int(1, desc='Number of times each segment is repeated')
	nbrRoundRobins = Int(1, desc='Number of times entire memory is looped')

	def json_encode(self, matlabCompatible=False):
		if matlabCompatible:
			"For the Matlab experiment manager we seperately nest averager, horizontal, vertical settings"
			jsonDict = {}
			jsonDict['address'] = self.address
			jsonDict['deviceName'] = 'AlazarATS9870'
			jsonDict['horizontal'] = {'delayTime':self.delay, 'samplingRate':self.samplingRate}
			jsonDict['vertical'] = {k:getattr(self,k) for k in ['verticalScale', 'verticalOffset', 'verticalCoupling', 'bandwidth']}
			jsonDict['trigger'] = {k:getattr(self,k) for k in ['triggerLevel', 'triggerSource', 'triggerCoupling', 'triggerSlope']}
			jsonDict['averager'] = {k:getattr(self,k) for k in ['recordLength', 'nbrSegments', 'nbrWaveforms', 'nbrRoundRobins']}
			#Add the other necessities
			jsonDict['acquireMode'] = self.acquireMode
			jsonDict['clockType'] = self.clockType
		else:
			jsonDict = super(AlazarATS9870, self).json_encode(matlabCompatible)

		return jsonDict

if __name__ == "__main__":
	from Digitizers import AlazarATS9870
	digitizer = AlazarATS9870(name='scope')
	with enaml.imports():
		from DigitizersViews import TestAlazarWindow

	session = show_simple_view(TestAlazarWindow(instr=digitizer))
	
コード例 #13
0
ファイル: hello_world.py プロジェクト: 5n1p/enaml
#------------------------------------------------------------------------------
#  Copyright (c) 2011, Enthought, Inc.
#  All rights reserved.
#------------------------------------------------------------------------------
import enaml
from enaml.stdlib.sessions import show_simple_view


if __name__ == '__main__':
    with enaml.imports():
        from hello_world_view import Main

    main_view = Main()
    show_simple_view(main_view)

コード例 #14
0
            self.sweeps.sweepOrder = quickPick['sweepOrder']

        #Setup the digitizer number of segments
        if 'nbrSegments' in quickPick:
            self.instruments['scope'].nbrSegments = quickPick['nbrSegments']


if __name__ == '__main__':
    import Libraries

    from ExpSettingsGUI import ExpSettings
    expSettings= ExpSettings(sweeps=Libraries.sweepLib, instruments=Libraries.instrumentLib,
                     measurements=Libraries.measLib,  channels = Libraries.channelLib)

    #If we were passed a scripter file to write to the use it
    parser = argparse.ArgumentParser()
    parser.add_argument('--scripterFile', action='store', dest='scripterFile', default=None)    
    options =  parser.parse_args(sys.argv[1:])
    if options.scripterFile:
        expSettings.curFileName = options.scripterFile

    with enaml.imports():
        from ExpSettingsView import ExpSettingsView

    show_simple_view(ExpSettingsView(expSettings=expSettings))





コード例 #15
0
ファイル: MicrowaveSources.py プロジェクト: circuitqed/PyQLab
    gateDelay = Float(-60e-9)

class Labbrick(MicrowaveSource):
    refSource = Enum('Internal' , 'External', desc='Source of 10MHz ref.')

    gateBuffer = Float(20e-9)
    gateMinWidth = Float(100e-9)
    gateDelay = Float(-60e-9)

class Labbrick64(MicrowaveSource):
    gateBuffer = Float(20e-9)
    gateMinWidth = Float(100e-9)
    gateDelay = Float(-60e-9)

class HP8673B(MicrowaveSource):
    pass

class HP8340B(MicrowaveSource):
    pass

#List of possible sources for other views
MicrowaveSourceList = [AgilentN5183A, HolzworthHS9000, Labbrick, Labbrick64, HP8673B, HP8340B]

if __name__ == "__main__":
    from MicrowaveSources import AgilentN5183A
    uwSource = AgilentN5183A(name='Agilent1')
    with enaml.imports():
        from MicrowaveSourcesView import MicrowaveSourceView

    session = show_simple_view(MicrowaveSourceView(uwSource=uwSource))
コード例 #16
0
ファイル: sensor_client.py プロジェクト: jminardi/pycon-demo
        while self._run:
            self.io_controller.rotate_logo = True
            send = {}
            if self.io_controller.added_links:
                add = self.io_controller.added_links
                self.io_controller.added_links = []
                send['add_link'] = add
            if self.io_controller.removed_links:
                remove = self.io_controller.removed_links
                self.io_controller.removed_links = []
                send['remove_link'] = remove
            if self.io_controller.outputs:
                outputs = self.io_controller.outputs
                self.io_controller.outputs = {}
                send['out'] = outputs
            socket.send(json.dumps(send))
            message = socket.recv()
            self.io_controller.set(**json.loads(message))
        socket.close()


if __name__ == '__main__':
    from enaml.stdlib.sessions import show_simple_view
    with enaml.imports():
        from sensor_view import SensorViewWindow
    sensor_app = SensorApp()
    window = SensorViewWindow(io_controller=sensor_app.io_controller)
    show_simple_view(window)
    sensor_app.stop()
コード例 #17
0
                            for ct in range(self.instrDict[instrName].numChannels):
                                self.instrDict[instrName].channels[ct].offset = instrParams['channels'][ct]['offset']


    #Getter for AWG list
    def _get_AWGs(self):
        return sorted([instr for instr in self.instrDict.values() if isinstance(instr, AWGs.AWG)], key = lambda instr : instr.name)

    #Getter for microwave source list
    def _get_sources(self):
        return sorted([instr for instr in self.instrDict.values() if isinstance(instr, MicrowaveSources.MicrowaveSource)], key = lambda instr : instr.name)

if __name__ == '__main__':
    import enaml
    from enaml.stdlib.sessions import show_simple_view

    from Libraries import instrumentLib
    with enaml.imports():
        from InstrumentManagerView import InstrumentManagerWindow
    show_simple_view(InstrumentManagerWindow(instrLib=instrumentLib))








    
    
コード例 #18
0
                                    self.instrDict[instrName].numChannels):
                                self.instrDict[instrName].channels[
                                    ct].offset = instrParams['channels'][ct][
                                        'offset']

    #Getter for AWG list
    def _get_AWGs(self):
        return sorted([
            instr for instr in self.instrDict.values()
            if isinstance(instr, AWGs.AWG)
        ],
                      key=lambda instr: instr.name)

    #Getter for microwave source list
    def _get_sources(self):
        return sorted([
            instr for instr in self.instrDict.values()
            if isinstance(instr, MicrowaveSources.MicrowaveSource)
        ],
                      key=lambda instr: instr.name)


if __name__ == '__main__':
    import enaml
    from enaml.stdlib.sessions import show_simple_view

    from Libraries import instrumentLib
    with enaml.imports():
        from InstrumentManagerView import InstrumentManagerWindow
    show_simple_view(InstrumentManagerWindow(instrLib=instrumentLib))
コード例 #19
0
""" Basic enaml example

Requires enaml 0.6.x

"""
import enaml
from enaml.stdlib.sessions import show_simple_view

from quandl_example import DataViewer

if __name__ == '__main__':
    with enaml.imports():
        from enaml_viewer import Viewer

    viewer = Viewer(model=DataViewer())
    show_simple_view(viewer)
コード例 #20
0
ファイル: MeasFilters.py プロジェクト: circuitqed/PyQLab
        if self.libFile:
            try:
                with open(self.libFile, 'r') as FID:
                    tmpLib = json.load(FID, cls=JSONHelpers.LibraryDecoder)
                    if isinstance(tmpLib, MeasFilterLibrary):
                        #Update correlator filter lists to filter objects
                        for filt in tmpLib.filterDict.values():
                            if isinstance(filt, Correlator):
                                filterList = []
                                for f in filt.filters:
                                    filterList.append(tmpLib.filterDict[f])
                                filt.filters = filterList
                        self.filterDict.update(tmpLib.filterDict)
            except IOError:
                print("No measurement library found.")

if __name__ == "__main__":

    #Work around annoying problem with multiple class definitions 
    from MeasFilters import DigitalHomodyne, MeasFilterLibrary

    testFilter1 = DigitalHomodyne(name='M1', boxCarStart=100, boxCarStop=500, IFfreq=10e6, samplingRate=250e6, channel=1)
    testFilter2 = DigitalHomodyne(name='M2', boxCarStart=150, boxCarStop=600, IFfreq=39.2e6, samplingRate=250e6, channel=2)

    testLib = MeasFilterLibrary(libFile='MeasFilterLibrary.json')
    testLib.filterDict.update({'M1':testFilter1, 'M2':testFilter2})
    from enaml.stdlib.sessions import show_simple_view
    with enaml.imports():
        from MeasFiltersViews import MeasFilterManagerWindow
    session = show_simple_view(MeasFilterManagerWindow(filterLib=testLib))
コード例 #21
0
ファイル: Digitizers.py プロジェクト: eccstartup/PyQLab
            jsonDict['trigger'] = {
                k: getattr(self, k)
                for k in [
                    'triggerLevel', 'triggerSource', 'triggerCoupling',
                    'triggerSlope'
                ]
            }
            jsonDict['averager'] = {
                k: getattr(self, k)
                for k in [
                    'recordLength', 'nbrSegments', 'nbrWaveforms',
                    'nbrRoundRobins'
                ]
            }
            #Add the other necessities
            jsonDict['acquireMode'] = self.acquireMode
            jsonDict['clockType'] = self.clockType
        else:
            jsonDict = super(AlazarATS9870, self).json_encode(matlabCompatible)

        return jsonDict


if __name__ == "__main__":
    from Digitizers import AlazarATS9870
    digitizer = AlazarATS9870(name='scope')
    with enaml.imports():
        from DigitizersViews import TestAlazarWindow

    session = show_simple_view(TestAlazarWindow(instr=digitizer))