Ejemplo n.º 1
0
    def __init__(self, manager, config, name):
        self.config = config
        self.manager = manager
        self.hasPowerIndicator = False
        self.hasShutter = False
        self.hasTriggerableShutter = False
        self.hasQSwitch = False
        self.hasPCell = False
        self.hasTunableWavelength = False

        self.params = {
            'expectedPower': config.get('power', None),  ## Expected output
            'currentPower': None,  ## Last measured output power
            'scopeTransmission':
            None,  ## percentage of output power that is transmitted to slice
            'tolerance': 10.0,  ## in %
            'useExpectedPower': True,
            'powerAlert':
            True  ## set True if you want changes in output power to raise an error
        }

        daqConfig = {
        }  ### DAQ generic needs to know about powerIndicator, pCell, shutter, qswitch
        if 'powerIndicator' in config:
            self.hasPowerIndicator = True
            #### name of powerIndicator is config['powerIndicator']['channel'][0]
            #daqConfig['powerInd'] = {'channel': config['powerIndicator']['channel'], 'type': 'ai'}
        if 'shutter' in config:
            daqConfig['shutter'] = config['shutter']
            self.hasTriggerableShutter = True
            self.hasShutter = True
        if 'qSwitch' in config:
            daqConfig['qSwitch'] = config['qSwitch']
            self.hasQSwitch = True
        if 'pCell' in config:
            daqConfig['pCell'] = config['pCell']
            self.hasPCell = True

        daqConfig['power'] = {
            'type': 'ao',
            'units': 'W'
        }  ## virtual channel used for creating control widgets
        DAQGeneric.__init__(self, manager, daqConfig, name)
        OptomechDevice.__init__(self, manager, config, name)

        self.lock = Mutex(QtCore.QMutex.Recursive)
        self.variableLock = Mutex(QtCore.QMutex.Recursive)
        self.calibrationIndex = None
        self.pCellCalibration = None
        self.getPowerHistory()

        #self.scope = manager.getDevice(self.config['scope'])
        #self.scope.sigObjectiveChanged.connect(self.objectiveChanged)
        self.sigGlobalSubdeviceChanged.connect(
            self.opticStateChanged
        )  ## called when objectives/filters have been switched

        manager.declareInterface(name, ['laser'], self)
        manager.sigAbortAll.connect(self.closeShutter)
Ejemplo n.º 2
0
    def __init__(self, manager, config, name):
        try:
            import MMCorePy
        except ImportError:
            if sys.platform != 'win32':
                raise
            # MM does not install itself to standard path. User should take care of this,
            # but we can make a guess..
            path = config.get('path', 'C:\\Program Files\\Micro-Manager-1.4')
            sys.path.append(path)
            os.environ['PATH'] = os.environ['PATH'] + ';' + path
            try:
                import MMCorePy
            finally:
                sys.path.pop()

        self.camName = str(name)  # we will use this name as the handle to the MM camera
        self.mmc = MMCorePy.CMMCore()

        self._triggerProp = None  # the name of the property for setting trigger mode
        self._triggerModes = ({}, {})  # forward and reverse mappings for the names of trigger modes
        self._binningMode = None  # 'x' or 'xy' for binning strings like '1' and '1x1', respectively
        self.camLock = Mutex(Mutex.Recursive)  ## Lock to protect access to camera
        self._config = config
        Camera.__init__(self, manager, config, name)  ## superclass will call setupCamera when it is ready.
        self.acqBuffer = None
        self.frameId = 0
        self.lastFrameTime = None
Ejemplo n.º 3
0
    def __init__(self, dm, config, name):
        Device.__init__(self, dm, config, name)
        self.config = config
        self.lock = Mutex(QtCore.QMutex.Recursive)
        self.port = config['port']
        self.scale = config['scale']
        self.pos = [0, 0]
        self.buttons = [0, 0]

        ## Reload the last known state of the mouse if it was last modified recently enough
        self.stateFile = os.path.join('devices', self.name + "_last_state.cfg")
        state = dm.readConfigFile(self.stateFile)
        if state != {} and time.time() - state.get('time', 0) < 36000:
            self.pos = state['pos']
            self.buttons = state['buttons']

        self.mThread = MouseThread(self, {
            'pos': self.pos[:],
            'btns': self.buttons[:]
        })
        self.mThread.sigPositionChanged.connect(self.posChanged)
        self.mThread.sigButtonChanged.connect(self.btnChanged)
        #self.proxy1 = proxyConnect(None, self.sigPositionChanged, self.storeState, 3.0) ## wait 3 seconds before writing changes
        #self.proxy2 = proxyConnect(None, self.sigSwitchChanged, self.storeState, 3.0)
        self.proxy1 = SignalProxy(self.sigPositionChanged,
                                  slot=self.storeState,
                                  delay=3.0)
        self.proxy2 = SignalProxy(self.sigSwitchChanged,
                                  slot=self.storeState,
                                  delay=3.0)

        self.mThread.start()
Ejemplo n.º 4
0
 def __init__(self, dev, driver, lock):
     Thread.__init__(self)
     self.lock = Mutex(QtCore.QMutex.Recursive)
     self.dev = dev
     self.driver = driver
     self.driverLock = lock
     self.cmds = {}
Ejemplo n.º 5
0
 def __init__(self):
     Thread.__init__(self)
     self.prot = None
     self._stop = False
     self._frame = None
     self._paused = False
     self.lock = Mutex(recursive=True)
Ejemplo n.º 6
0
    def __init__(self, dm, config, name):
        Device.__init__(self, dm, config, name)
        OptomechDevice.__init__(self, dm, config, name)

        self.config = config
        self.lock = Mutex(QtCore.QMutex.Recursive)
        self.switchDevice = None
        self.currentSwitchPosition = None
        self.currentObjective = None
        self._focusDevice = None
        self._positionDevice = None
        self._surfaceDepth = None

        self.objectives = collections.OrderedDict()
        ## Format of self.objectives is:
        ## {
        ##    switchPosition1: {objName1: objective1, objName2: objective, ...},
        ##    switchPosition2: {objName1: objective1, objName2: objective, ...},
        ## }

        for k1, objs in config['objectives'].iteritems(
        ):  ## Set default values for each objective
            self.objectives[k1] = collections.OrderedDict()
            for k2, o in objs.iteritems():
                obj = Objective(o, self, (k1, k2))
                self.objectives[k1][k2] = obj
                #obj.sigTransformChanged.connect(self.objectiveTransformChanged)

        ## Keep track of the objective currently in use for each position
        ## Format is: { switchPosition1: objective1,  ... }
        self.selectedObjectives = collections.OrderedDict([
            (i, self.objectives[i].values()[0]) for i in self.objectives
        ])
        for obj in self.selectedObjectives.values():
            self.addSubdevice(obj)

        ## if there is a light source, configure it here
        if 'lightSource' in config:
            self.lightSource = dm.getDevice(config['lightSource'])
            self.lightSource.sigLightChanged.connect(self._lightChanged)
        else:
            self.lightSource = None

        ## If there is a switch device, configure it here
        if 'objectiveSwitch' in config:
            self.switchDevice = dm.getDevice(
                config['objectiveSwitch'][0])  ## Switch device
            self.objSwitchId = config['objectiveSwitch'][1]  ## Switch ID
            #self.currentSwitchPosition = str(self.switchDevice.getSwitch(self.objSwitchId))
            self.switchDevice.sigSwitchChanged.connect(
                self.objectiveSwitchChanged)
            self.objectiveSwitchChanged()
        else:
            self.setObjectiveIndex(0)

        cal = self.readConfigFile('calibration')
        if 'surfaceDepth' in cal:
            self.setSurfaceDepth(cal['surfaceDepth'])

        dm.declareInterface(name, ['microscope'], self)
Ejemplo n.º 7
0
    def __init__(self, dm, config, name):
        Device.__init__(self, dm, config, name)
        OptomechDevice.__init__(self, dm, config, name)

        # total device transform will be composed of a base transform (defined in the config)
        # and a dynamic translation provided by the hardware.
        self._baseTransform = Qt.QMatrix4x4(self.deviceTransform())
        self._stageTransform = Qt.QMatrix4x4()
        self._invStageTransform = Qt.QMatrix4x4()

        self.config = config
        self.lock = Mutex(Qt.QMutex.Recursive)
        self.pos = [0] * 3
        self._defaultSpeed = 'fast'
        self.pitch = config.get('pitch', 27)
        self.setFastSpeed(config.get('fastSpeed', 1e-3))
        self.setSlowSpeed(config.get('slowSpeed', 10e-6))

        # used to emit signal when position passes a threshold
        self.switches = {}
        self.switchThresholds = {}
        for name, spec in config.get('switches', {}).items():
            self.switches[name] = None
            self.switchThresholds[name] = spec

        self._limits = [(None, None), (None, None), (None, None)]

        self._progressDialog = None
        self._progressTimer = Qt.QTimer()
        self._progressTimer.timeout.connect(self.updateProgressDialog)

        dm.declareInterface(name, ['stage'], self)
Ejemplo n.º 8
0
 def __init__(self):
     QtCore.QObject.__init__(self)
     if DataManager.INSTANCE is not None:
         raise Exception("Attempted to create more than one DataManager!")
     DataManager.INSTANCE = self
     self.cache = {}
     self.lock = Mutex(QtCore.QMutex.Recursive)
Ejemplo n.º 9
0
    def __init__(self):
        self.cams = {}
        self.lock = Mutex()

        #self.pvcam = windll.Pvcam32
        if _PVCamClass.PVCAM_CREATED:
            raise Exception(
                "Will not create another pvcam instance--use the pre-existing PVCam object."
            )
        init = LIB.pvcam_init()()
        if init < 1:
            raise Exception(
                "Could not initialize pvcam library (pl_pvcam_init): %s" %
                self.error())
        # This should happen before every new exposure (?)
        if LIB.exp_init_seq()() < 1:
            raise Exception(
                "Could not initialize pvcam library (pl_exp_init_seq): %s" %
                self.error())
        _PVCamClass.PVCAM_CREATED = True

        global externalParams

        self.paramTable = OrderedDict()
        for p in externalParams:
            self.paramTable[p] = self.paramFromString(p)

        atexit.register(self.quit)
Ejemplo n.º 10
0
    def __init__(self, manager):
        Qt.QMainWindow.__init__(self)
        self.setWindowTitle("Log")
        path = os.path.dirname(__file__)
        self.setWindowIcon(Qt.QIcon(os.path.join(path, 'logIcon.png')))
        self.wid = LogWidget(self, manager)
        self.wid.ui.input = Qt.QLineEdit()
        self.wid.ui.gridLayout.addWidget(self.wid.ui.input, 2, 0, 1, 3)
        self.wid.ui.dirLabel.setText("Current Storage Directory: None")
        self.setCentralWidget(self.wid)
        self.resize(1000, 500)
        self.manager = manager
        #global WIN
        global WIN
        WIN = self
        self.msgCount = 0
        self.logCount = 0
        self.logFile = None
        configfile.writeConfigFile(
            '', self.fileName()
        )  ## start a new temp log file, destroying anything left over from the last session.
        self.buttons = [
        ]  ## weak references to all Log Buttons get added to this list, so it's easy to make them all do things, like flash red.
        self.lock = Mutex()
        self.errorDialog = ErrorDialog()

        self.wid.ui.input.returnPressed.connect(self.textEntered)
        self.sigLogMessage.connect(self.queuedLogMsg, Qt.Qt.QueuedConnection)
Ejemplo n.º 11
0
 def __init__(self, deviceManager, config, name):
     QtCore.QObject.__init__(self)
     self._lock_ = Mutex(QtCore.QMutex.Recursive)  ## no, good idea
     self._lock_tb_ = None
     self.dm = deviceManager
     self.dm.declareInterface(name, ['device'], self)
     self._name = name
Ejemplo n.º 12
0
 def __init__(self, dev):
     self.dev = dev
     self.lock = Mutex(recursive=True)
     self.stopped = False
     self.interval = 0.3
     
     Thread.__init__(self)
Ejemplo n.º 13
0
    def __init__(self, dm, config, name):

        Device.__init__(self, dm, config, name)
        OptomechDevice.__init__(self, dm, config, name)

        self.scopeDev = None
        self.currentFilter = None
        p = self
        while p is not None:
            p = p.parentDevice()
            if isinstance(p, Microscope):
                self.scopeDev = p

        self.port = config[
            'port']  ## windows com ports start at COM1, pyserial ports start at 0
        self.baud = config.get('baud', 115200)
        #self.positionLabels = config.get('postionLabels')

        self.driver = FilterWheelDriver(self.port, self.baud)
        self.driverLock = Mutex(
            QtCore.QMutex.Recursive)  ## access to low level driver calls
        self.filterWheelLock = Mutex(
            QtCore.QMutex.Recursive)  ## access to self.attributes

        self.filters = OrderedDict()
        ## Format of self.filters is:
        ## {
        ##    filterWheelPosition1: {filterName: filter},
        ##    filterWheelPosition2: {filterName: filter},
        ## }
        nPos = self.getPositionCount()
        for k in range(nPos):  ## Set value for each filter
            filt = Filter(config['filters'], self, k)
            self.filters[k] = filt

        #print self.filters.values()
        #print self.filters[1].name(), self.filters[1].description()
        #if len(self.positionLabels) != self.getPositionCount():
        #    raise Exception("Number of FilterWheel positions %s must correspond to number of labels!" % self.getPositionCount())

        with self.driverLock:
            self.currentFWPosition = self.driver.getPos()
            self.currentFilter = self.getFilter()

        self.fwThread = FilterWheelThread(self, self.driver, self.driverLock)
        self.fwThread.fwPosChanged.connect(self.positionChanged)
        self.fwThread.start()
Ejemplo n.º 14
0
 def __init__(self, ui):
     self.ui = ui
     self.manager = ui.manager
     self.clampName = ui.clampName
     Thread.__init__(self)
     self.lock = Mutex(QtCore.QMutex.Recursive)
     self.stopThread = True
     self.paramsUpdated = True
Ejemplo n.º 15
0
 def __init__(self, path, manager):
     QtCore.QObject.__init__(self)
     self.manager = manager
     self.delayedChanges = []
     self.path = os.path.abspath(path)
     self.parentDir = None
     self.lock = Mutex(QtCore.QMutex.Recursive)
     self.sigproxy = SignalProxy(self.sigChanged, slot=self.delayedChange)
Ejemplo n.º 16
0
 def __init__(self, laserDev, scannerDev):
     Thread.__init__(self)
     self._abort = False
     self._video = True
     self._closeShutter = True  # whether to close shutter at end of acquisition
     self.lock = Mutex(recursive=True)
     self.manager = acq4.Manager.getManager()
     self.laserDev = laserDev
     self.scannerDev = scannerDev
Ejemplo n.º 17
0
 def __init__(self, *args, **kargs):
     self.camLock = Mutex(Mutex.Recursive)  ## Lock to protect access to camera
     self.ringSize = 50
     Camera.__init__(self, *args, **kargs)  ## superclass will call setupCamera when it is ready.
     self.acqBuffer = None
     self.frameId = 0
     self.lastIndex = None
     self.lastFrameTime = None
     self.stopOk = False
Ejemplo n.º 18
0
 def __init__(self, task, frames, daqResult):
     self.lock = Mutex(recursive=True)
     self._task = task
     self._frames = frames
     self._daqResult = daqResult
     self._marr = None
     self._arr = None
     self._frameTimes = None
     self._frameTimesPrecise = False
Ejemplo n.º 19
0
    def __init__(self, dev, cmd, parentTask):
        DeviceTask.__init__(self, dev, cmd, parentTask)
        self.cmd = cmd
        self.daqTasks = []
        self.spotSize = None

        # We use this flag to exit from the sleep loop in start() in case the
        # task is aborted during that time.
        self.aborted = False
        self.abortLock = Mutex(recursive=True)
Ejemplo n.º 20
0
 def __init__(self, ui):
     Thread.__init__(self)
     self.ui = ui
     self.dm = self.ui.manager
     self.lock = Mutex(Qt.QMutex.Recursive)
     self.stopThread = True
     self.abortThread = False
     self.paused = False
     self._currentTask = None
     self._systrace = None
Ejemplo n.º 21
0
 def __init__(self):
     self.pos = np.zeros(3)
     self.target = None
     self.speed = None
     self.velocity = None
     self._quit = False
     self.lock = Mutex()
     self.interval = 30e-3
     self.lastUpdate = None
     self.currentMove = None
     Thread.__init__(self)
Ejemplo n.º 22
0
    def __init__(self, dev):
        Thread.__init__(self)
        self.dev = dev
        #self.cam = self.dev.getCamera()
        self.camLock = self.dev.camLock
        #size = self.cam.getSize()
        #self.state = {'binning': 1, 'exposure': .001, 'region': [0, 0, size[0]-1, size[1]-1], 'mode': 'No Trigger'}
        #self.state = self.dev.getParams(['binning', 'exposure', 'region', 'triggerMode'])
        self.stopThread = False
        self.lock = Mutex()
        self.acqBuffer = None
        #self.frameId = 0
        self.bufferTime = 5.0
        #self.ringSize = 30
        self.tasks = []

        ## This thread does not run an event loop,
        ## so we may need to deliver frames manually to some places
        self.connections = set()
        self.connectMutex = Mutex()
Ejemplo n.º 23
0
    def __init__(self, dev):
        self.dev = dev
        self.lock = Mutex(recursive=True)
        self.stopped = False
        self.interval = 0.3

        self.nextMoveId = 0
        self.moveRequest = None
        self._moveStatus = {}

        Thread.__init__(self)
Ejemplo n.º 24
0
 def __init__(self, dev, startState=None):
     Thread.__init__(self)
     self.lock = Mutex(QtCore.QMutex.Recursive)
     self.dev = dev
     self.port = self.dev.port
     if startState is None:
         self.pos = [0, 0]
         self.btns = [0, 0]
     else:
         self.pos = startState['pos']
         self.btns = startState['btns']
Ejemplo n.º 25
0
    def __init__(self, dm, config, name):
        self.port = config[
            'port'] - 1  ## windows com ports start at COM1, pyserial ports start at 0
        self.baud = config.get('baud', 19200)
        self.driver = Coherent(self.port, self.baud)
        self.driverLock = Mutex(
            QtCore.QMutex.Recursive)  ## access to low level driver calls

        self.coherentLock = Mutex(
            QtCore.QMutex.Recursive)  ## access to self.attributes
        self.coherentPower = 0
        self.coherentWavelength = 0

        self.mThread = CoherentThread(self, self.driver, self.driverLock)
        self.mThread.sigPowerChanged.connect(self.powerChanged)
        self.mThread.sigWavelengthChanged.connect(self.wavelengthChanged)
        self.mThread.start()
        Laser.__init__(self, dm, config, name)

        self.hasShutter = True
        self.hasTunableWavelength = True
Ejemplo n.º 26
0
    def __init__(self, deviceManager, config, name):
        QtCore.QObject.__init__(self)

        # task reservation lock -- this is a recursive lock to allow a task to run its own subtasks
        # (for example, setting a holding value before exiting a task).
        # However, under some circumstances we might try to run two concurrent tasks from the same
        # thread (eg, due to calling processEvents() while waiting for the task to complete). We
        # don't have a good solution for this problem at present..
        self._lock_ = Mutex(QtCore.QMutex.Recursive)
        self._lock_tb_ = None
        self.dm = deviceManager
        self.dm.declareInterface(name, ['device'], self)
        self._name = name
Ejemplo n.º 27
0
    def __init__(self, dm, config, name):
        Device.__init__(self, dm, config, name)
        OptomechDevice.__init__(self, dm, config, name)
        self.config = config
        self.configFile = os.path.join('devices', name + '_config.cfg')
        self.lock = Mutex(QtCore.QMutex.Recursive)
        self.port = config[
            'port']  ## windows com ports start at COM1, pyserial ports start at 0

        # whether this device has an arduino interface protecting it from roe/serial collisions
        # (see acq4/drivers/SutterMP285/mp285_hack)
        # If not, then position monitoring is disabled.
        self.useArduino = config.get('useArduino', False)

        self.scale = config.pop('scale', (1, 1, 1))
        # Interpret "COM1" as port 0
        if isinstance(self.port,
                      basestring) and self.port.lower()[:3] == 'com':
            self.port = int(self.port[3:]) - 1

        self.baud = config.get('baud',
                               9600)  ## 9600 is probably factory default
        self.pos = [0, 0, 0]
        self.limits = [[[0, False], [0, False]], [[0, False], [0, False]],
                       [[0, False], [0, False]]]
        self.maxSpeed = 1e-3
        self.loadConfig()

        self.mp285 = SutterMP285Driver(self.port, self.baud)
        self.driverLock = Mutex(QtCore.QMutex.Recursive)

        self.mThread = SutterMP285Thread(self, self.mp285, self.driverLock,
                                         self.scale, self.limits,
                                         self.maxSpeed)
        self.mThread.sigPositionChanged.connect(self.posChanged)
        if self.useArduino:
            self.mThread.start()

        dm.declareInterface(name, ['stage'], self)
Ejemplo n.º 28
0
    def __init__(self, dm, config, name):
        Device.__init__(self, dm, config, name)
        self._DGLock = Mutex(
            Qt.QMutex.Recursive)  ## protects access to _DGHolding, _DGConfig
        ## Do some sanity checks here on the configuration

        # 'channels' key is expected; for backward compatibility we just use the top-level config.
        config = config.get('channels', config)
        self._DGConfig = config
        self._DGHolding = {}
        for ch in config:
            if config[ch]['type'][0] != 'a' and ('scale' in config[ch]
                                                 or 'offset' in config[ch]):
                raise Exception(
                    "Scale/offset only allowed for analog channels. (%s.%s)" %
                    (name, ch))

            if 'scale' not in config[ch]:
                config[ch][
                    'scale'] = 1  ## must be int to prevent accidental type conversion on digital data
            if 'offset' not in config[ch]:
                config[ch]['offset'] = 0
            if config[ch].get('invert', False):
                if config[ch]['type'][0] != 'd':
                    raise Exception(
                        "Inversion only allowed for digital channels. (%s.%s)"
                        % (name, ch))
                config[ch]['scale'] = -1
                config[ch]['offset'] = -1

            #print "chan %s scale %f" % (ch, config[ch]['scale'])
            if 'holding' not in config[ch]:
                config[ch]['holding'] = 0.0

            ## It is possible to create virtual channels with no real hardware connection
            if 'device' not in config[ch]:
                #print "Assuming channel %s is virtual:" % ch, config[ch]
                config[ch]['virtual'] = True

            ## set holding value for all output channels now
            if config[ch]['type'][1] == 'o':
                self.setChanHolding(ch, config[ch]['holding'])
            #self._DGHolding[ch] = config[ch]['holding']

        dm.declareInterface(name, ['daqChannelGroup'], self)
        for ch in config:
            dm.declareInterface(name + "." + ch, ['daqChannel'],
                                ChannelHandle(self, ch))
Ejemplo n.º 29
0
 def __init__(self, dm, config, name):
     Device.__init__(self, dm, config, name)
     OptomechDevice.__init__(self, dm, config, name)
     
     self.config = config
     self.lock = Mutex(QtCore.QMutex.Recursive)
     self.devGui = None
     self.lastRunTime = None
     self.calibrationIndex = None
     self.targetList = [1.0, {}]  ## stores the grids and points used by TaskGui so that they persist
     self.currentCommand = [0,0] ## The last requested voltage values (but not necessarily the current voltage applied to the mirrors)
     self.currentVoltage = [0, 0]
     self.shutterOpen = True ## indicates whether the virtual shutter is closed (the beam is steered to its 'off' position).
     if 'offVoltage' in config:
         self.setShutterOpen(False)
     dm.declareInterface(name, ['scanner'], self)
Ejemplo n.º 30
0
 def __init__(self, dev, driver, driverLock, scale, limits, maxSpd):
     Thread.__init__(self)
     self.lock = Mutex(QtCore.QMutex.Recursive)
     self.scale = scale
     self.mp285 = driver
     self.driverLock = driverLock
     #self.monitor = True
     self.update = False
     self.resolution = 'fine'
     self.dev = dev
     #self.port = port
     #self.pos = [0, 0, 0]
     #self.baud = baud
     self.velocity = [0, 0, 0]
     self.limits = deepcopy(limits)
     self.limitChanged = False
     self.maxSpeed = maxSpd