def reacquireImage(self,
                       imagedata,
                       test=False,
                       target=None,
                       griddata=None):
        presetname = imagedata['preset']['name']
        self.logger.debug('preset name: %s' % (presetname, ))
        presetdata = self.presetsclient.getPresetFromDB(presetname)

        try:
            t = 'TEM'
            self.instrument.setTEM(presetdata['tem']['name'])
            t = 'CCD Camera'
            self.instrument.setCCDCamera(presetdata['ccdcamera']['name'])
        except (ValueError, TypeError, AttributeError, KeyError):
            self.logger.error('Cannot access %s for preset' % t)
            if test:
                return False
            else:
                return None

        targetdata = leginondata.AcquisitionImageTargetData(
            initializer=imagedata['target'])
        emtargetdata = leginondata.EMTargetData(
            initializer=imagedata['emtarget'])

        movetype = emtargetdata['movetype']
        calclient = self.calibrationclients[movetype]
        row = -targetdata['delta row']
        column = -targetdata['delta column']
        if target is not None:
            row -= target[0]
            column -= target[1]
        target = {'row': row, 'col': column}
        scope, camera = targetdata['scope'], targetdata['camera']
        try:
            scopedata = calclient.transform(target, scope, camera)
        except calibrationclient.NoMatrixCalibrationError, e:
            self.logger.error('No calibration for reacquisition: %s' % e)
            if test:
                return False
            else:
                return None
Esempio n. 2
0
    def acquire(self, presetdata, emtarget=None, attempt=None, target=None):
        '''
		this replaces Acquisition.acquire()
		Instead of acquiring an image, we acquire a series of beam tilt images
		'''
        if self.catchBadSettings(presetdata) == 'error':
            return 'error'

        self.rpixelsize = None
        self.defocus = presetdata['defocus']
        ## sometimes have to apply or un-apply deltaz if image shifted on
        ## tilted specimen
        if emtarget is None:
            self.deltaz = 0
        else:
            self.deltaz = emtarget['delta z']

        # aquire and save the focus image
        oldbt = self.instrument.tem.BeamTilt
        tiltlist, anglelist, radlist = self.getBeamTiltList()

        ## initialize a new tableau
        self.initTableau()

        ## first target is the one given, the remaining are created now
        emtargetlist = []
        emtargetlist.append(emtarget)
        for i in range(len(tiltlist) - 1):
            ## check if target is simulated or not
            if target['type'] == 'simulated':
                newtarget = self.newSimulatedTarget(preset=presetdata)
                newemtarget = leginondata.EMTargetData(initializer=emtarget,
                                                       target=newtarget)
            else:
                lastnumber = self.lastTargetNumber(image=target['image'],
                                                   session=self.session)
                newnumber = lastnumber + 1
                newtarget = leginondata.AcquisitionImageTargetData(
                    initializer=target, number=newnumber)
                newemtarget = leginondata.EMTargetData(initializer=emtarget,
                                                       target=newtarget)

            newemtarget.insert(force=True)
            emtargetlist.append(newemtarget)

        displace = []
        for i, bt in enumerate(tiltlist):
            emtarget = emtargetlist[i]
            if i == 0:
                channel = 0
            else:
                channel = 1
            self.logger.info('Old beam tilt: %.4f, %.4f' % (
                oldbt['x'],
                oldbt['y'],
            ))
            newbt = {'x': oldbt['x'] + bt['x'], 'y': oldbt['y'] + bt['y']}
            self.instrument.tem.BeamTilt = newbt
            self.logger.info('New beam tilt: %.4f, %.4f' % (
                newbt['x'],
                newbt['y'],
            ))
            status = manualfocuschecker.ManualFocusChecker.acquire(
                self, presetdata, emtarget, channel=channel)
            imagedata = self.imagedata
            # get these values once
            if not self.rpixelsize or not self.ht or not self.cs:
                self.rpixelsize = self.btcalclient.getImageReciprocalPixelSize(
                    imagedata)
                self.ht = imagedata['scope']['high tension']
                self.cs = imagedata['scope']['tem']['cs']
            self.setImage(imagedata['image'], 'Image')
            self.instrument.tem.BeamTilt = oldbt
            angle = anglelist[i]
            rad = radlist[i]

            if self.settings['tableau type'] == 'split image-power':
                self.splitTableau(imagedata)
            elif 'beam tilt series' in self.settings['tableau type']:
                self.insertTableau(imagedata, angle, rad)
            if self.settings['tableau type'] == 'beam tilt series-image':
                try:
                    shiftinfo = self.correlateOriginal(i, imagedata)
                except Exception, e:
                    self.logger.error('Failed correlation: %s' % e)
                    return 'error'
                pixelshift = shiftinfo['pixel shift']
                displace.append((pixelshift['row'], pixelshift['col']))
	def targetToEMTargetData(self, targetdata, z=None):
		'''
		convert an ImageTargetData to an EMTargetData object
		using chosen move type.
		The result is a valid scope state that will center
		the target on the camera, but not necessarily at the
		desired preset.  It is shifted from the preset of the 
		original targetdata.

		Certain fields are reset to None becuase they are not
		necessary, and cause problems if used between different
		magnification modes (LM, M, SA).
		'''
		emtargetdata = leginondata.EMTargetData()
		if targetdata is not None:
			# get relevant info from target data
			targetdeltarow = targetdata['delta row']
			targetdeltacolumn = targetdata['delta column']
			origscope = targetdata['scope']
			targetscope = leginondata.ScopeEMData(initializer=origscope)
			## copy these because they are dictionaries that could
			## otherwise be shared (although transform() should be
			## smart enough to create copies as well)
			targetscope['stage position'] = dict(origscope['stage position'])
			targetscope['image shift'] = dict(origscope['image shift'])
			targetscope['beam shift'] = dict(origscope['beam shift'])

			if z is not None:
				# since presetsmanager settings 'only xy' is always True, this
				# is only good for database record
				targetscope['stage position']['z'] = z

			movetype = self.settings['move type']
			oldpreset = targetdata['preset']

			zdiff = 0.0
			### simulated target does not require transform
			if targetdata['type'] == 'simulated':
				newscope = origscope
			else:
				targetcamera = targetdata['camera']
		
				## to shift targeted point to center...
				deltarow = -targetdeltarow
				deltacol = -targetdeltacolumn
		
				pixelshift = {'row':deltarow, 'col':deltacol}
		
				## figure out scope state that gets to the target
				calclient = self.calclients[movetype]
				try:
					newscope = calclient.transform(pixelshift, targetscope, targetcamera)
				except calibrationclient.NoMatrixCalibrationError, e:
					raise NoMoveCalibration(e)

				## if stage is tilted and moving by image shift,
				## calculate z offset between center of image and target
				if movetype in ('image shift','image beam shift','beam shift') and abs(targetscope['stage position']['a']) > 0.02:
					calclient = self.calclients['stage position']
					try:
						tmpscope = calclient.transform(pixelshift, targetscope, targetcamera)
					except calibrationclient.NoMatrixCalibrationError,e:
						raise NoMoveCalibration(e)
					ydiff = tmpscope['stage position']['y'] - targetscope['stage position']['y']
					zdiff = ydiff * numpy.sin(targetscope['stage position']['a'])
        def targetToEMTargetData(self, targetdata,movetype):
                '''
                copied from acquisition but get move type from old emtarget
                '''
                emtargetdata = leginondata.EMTargetData()
                if targetdata is not None:
                        # get relevant info from target data
                        targetdeltarow = targetdata['delta row']
                        targetdeltacolumn = targetdata['delta column']
                        origscope = targetdata['scope']
                        targetscope = leginondata.ScopeEMData(initializer=origscope)
                        ## copy these because they are dictionaries that could
                        ## otherwise be shared (although transform() should be
                        ## smart enough to create copies as well)
                        targetscope['stage position'] = dict(origscope['stage position'])
                        targetscope['image shift'] = dict(origscope['image shift'])
                        targetscope['beam shift'] = dict(origscope['beam shift'])

                        oldpreset = targetdata['preset']

                        zdiff = 0.0
                        ### simulated target does not require transform
                        if targetdata['type'] == 'simulated':
                                newscope = origscope
                        else:
                                targetcamera = targetdata['camera']

                                ## to shift targeted point to center...
                                deltarow = -targetdeltarow
                                deltacol = -targetdeltacolumn

                                pixelshift = {'row':deltarow, 'col':deltacol}
                                ## figure out scope state that gets to the target
                                calclient = self.calclients[movetype]
                                try:
                                        newscope = calclient.transform(pixelshift, targetscope, targetcamera)
                                except calibrationclient.NoMatrixCalibrationError, e:
                                        m = 'No calibration for acquisition move to target: %s'
                                        self.logger.error(m % (e,))
                                        raise NoMoveCalibration(m)

                                ## if stage is tilted and moving by image shift,
                                ## calculate z offset between center of image and target
                                if movetype in ('image shift','image beam shift','beam shift') and abs(targetscope['stage position']['a']) > 0.02:
                                        calclient = self.calclients['stage position']
                                        try:
                                                tmpscope = calclient.transform(pixelshift, targetscope, targetcamera)
                                        except calibrationclient.NoMatrixCalibrationError:
                                                message = 'No stage calibration for z measurement'
                                                self.logger.error(message)
                                                raise NoMoveCalibration(message)
                                        ydiff = tmpscope['stage position']['y'] - targetscope['stage position']['y']
                                        zdiff = ydiff * numpy.sin(targetscope['stage position']['a'])

                        ### check if stage position is valid
                        if newscope['stage position']:
                                self.validateStagePosition(newscope['stage position'])

                        emtargetdata['preset'] = oldpreset
                        emtargetdata['movetype'] = movetype
                        emtargetdata['image shift'] = dict(newscope['image shift'])
                        emtargetdata['beam shift'] = dict(newscope['beam shift'])
                        emtargetdata['stage position'] = dict(newscope['stage position'])
                        emtargetdata['delta z'] = zdiff
class Reference(watcher.Watcher, targethandler.TargetHandler):
    panelclass = gui.wx.Reference.ReferencePanel
    settingsclass = leginondata.ReferenceSettingsData
    eventinputs = watcher.Watcher.eventinputs + \
                              presets.PresetsClient.eventinputs + \
                              [event.ReferenceTargetPublishEvent]
    eventoutputs = watcher.Watcher.eventoutputs + \
                                    presets.PresetsClient.eventoutputs

    defaultsettings = {
        'move type': 'stage position',
        'pause time': 3.0,
        'interval time': 0.0,
    }

    def __init__(self, *args, **kwargs):
        try:
            watch = kwargs['watchfor']
        except KeyError:
            watch = []
        kwargs['watchfor'] = watch + [event.ReferenceTargetPublishEvent]
        watcher.Watcher.__init__(self, *args, **kwargs)
        targethandler.TargetHandler.__init__(self)

        self.instrument = instrument.Proxy(self.objectservice, self.session)

        self.calibration_clients = {
            'image shift':
            calibrationclient.ImageShiftCalibrationClient(self),
            'stage position':
            calibrationclient.StageCalibrationClient(self),
            'modeled stage position':
            calibrationclient.ModeledStageCalibrationClient(self),
            'image beam shift':
            calibrationclient.ImageBeamShiftCalibrationClient(self),
            'beam shift':
            calibrationclient.BeamShiftCalibrationClient(self),
        }

        self.presets_client = presets.PresetsClient(self)

        self.player = player.Player(callback=self.onPlayer)
        self.panel.playerEvent(self.player.state())
        self.lock = threading.RLock()
        self.reference_target = None

        self.last_processed = None

        if self.__class__ == Reference:
            self.start()

    def processData(self, incoming_data):
        if isinstance(incoming_data, leginondata.ReferenceTargetData):
            self.processReferenceTarget(incoming_data)

    def processReferenceTarget(self, target_data):
        self.lock.acquire()
        self.reference_target = target_data
        self.lock.release()

    def getEMTargetData(self, check_preset_name=None):
        target_data = self.reference_target
        if target_data is None:
            raise MoveError('no reference target available')
        move_type = self.settings['move type']
        calibration_client = self.calibration_clients[move_type]

        target_delta_row = target_data['delta row']
        target_delta_column = target_data['delta column']
        pixel_shift = {'row': -target_delta_row, 'col': -target_delta_column}
        target_scope = leginondata.ScopeEMData(
            initializer=target_data['scope'])
        for i in ['image shift', 'beam shift', 'stage position']:
            target_scope[i] = dict(target_data['scope'][i])
        target_camera = target_data['camera']

        args = (pixel_shift, target_scope, target_camera)
        try:
            scope = calibration_client.transform(*args)
        except calibrationclient.NoMatrixCalibrationError, e:
            message = 'no %s calibration to move to reference target: %s'
            raise MoveError(message % (move_type, e))

        em_target_data = leginondata.EMTargetData()
        if check_preset_name is None:
            em_target_data['preset'] = target_data['preset']
        else:
            check_preset_data = self.presets_client.getPresetByName(
                check_preset_name)
            em_target_data['preset'] = check_preset_data
        for i in ['image shift', 'beam shift']:
            em_target_data[i] = em_target_data['preset'][i]
        em_target_data['stage position'] = scope['stage position']
        em_target_data['movetype'] = move_type
        if move_type == 'modeled stage position':
            scope_move_type = 'stage position'
        else:
            scope_move_type = move_type
        em_target_data[scope_move_type] = scope[scope_move_type]
        em_target_data['target'] = leginondata.AcquisitionImageTargetData(
            initializer=target_data)

        return em_target_data