def setSubdirectory(dirname):
    try:
        finder.find("GDAMetadata").setMetadataValue("subdirectory", dirname)
    except:
        exceptionType, exception, traceback = sys.exc_info()
        handle_messages.log(None, "problem setting metadata value for 'subdirectory' to " + dirname, exceptionType, exception, traceback, False)
        print "Failed to set metadata value for 'subdirectory' to:", dirname, exception
Пример #2
0
def time_command(numberOfLoops, cmd):
	print "time_scan : ", `cmd`
	timebase = time()
	filename = strftime("%Y-%m-%d_%H-%M-%S_time_command.dat")
	file = open(filename,"w")
	try:
		loop=0;
		loop_count=0
		while(True):
			exec(cmd)
			loop += 1
			timenow = time()
			t = timenow - timebase
			timebase = timenow
			file.write( `loop` + "," + `t`)
			if numberOfLoops > 0:
				loop_count += 1
				if loop_count >= numberOfLoops:
					break
	except :
		type, exception, traceback = sys.exc_info()	
		toRaise = not isinstance(exception, java.lang.InterruptedException)
		if toRaise:
			file.close
		handle_messages.log(None,"time_command exception", type, exception, traceback, toRaise)
	file.close
#	filename = strftime("%Y-%m-%d_%H-%M-%S_time_command.dat_srs")
#	if len(times)>0:
#		xName="loop"
#		yName="time"
#		sfh = plotData.getScanFileHolderY(xName,yName,times)
#		sfh.save( SRSLoader(filename))
#		sfh.plot(xName, yName)
	return filename
Пример #3
0
def time_command(numberOfLoops, cmd):
    print "time_scan : ", ` cmd `
    timebase = time()
    filename = strftime("%Y-%m-%d_%H-%M-%S_time_command.dat")
    file = open(filename, "w")
    try:
        loop = 0
        loop_count = 0
        while (True):
            exec(cmd)
            loop += 1
            timenow = time()
            t = timenow - timebase
            timebase = timenow
            file.write( ` loop ` + "," + ` t `)
            if numberOfLoops > 0:
                loop_count += 1
                if loop_count >= numberOfLoops:
                    break
    except:
        type, exception, traceback = sys.exc_info()
        toRaise = not isinstance(exception, java.lang.InterruptedException)
        if toRaise:
            file.close
        handle_messages.log(None, "time_command exception", type, exception,
                            traceback, toRaise)
    file.close
    #	filename = strftime("%Y-%m-%d_%H-%M-%S_time_command.dat_srs")
    #	if len(times)>0:
    #		xName="loop"
    #		yName="time"
    #		sfh = plotData.getScanFileHolderY(xName,yName,times)
    #		sfh.save( SRSLoader(filename))
    #		sfh.plot(xName, yName)
    return filename
def getSubdirectory():
    try:
        return finder.find("GDAMetadata").getMetadataValue("subdirectory")
    except:
        exceptionType, exception, traceback = sys.exc_info()
        handle_messages.log(None, "problem getting metadata value for 'subdirectory' ", exceptionType, exception, traceback, False)
        print "Failed to get metadata value for 'subdirectory':", exception
        return None
Пример #5
0
def update(controller,
           msg,
           exceptionType=None,
           exception=None,
           traceback=None,
           Raise=False):
    handle_messages.log(controller, msg, exceptionType, exception, traceback,
                        Raise)
Пример #6
0
 def __init__(self):
     self.comms_started=False
     try:
         self.leem_com=(Finder.find("leem2000_objects")).get("leem2000_com")
         self.leem_com.setReplyTerm('\0')
         self.leem_com.setCmdTerm('\0')
     except:
         exceptionType, exception, traceback=sys.exc_info();
         handle_messages.log(None, "Error getting leem2000_com from leem2000_objects", exceptionType, exception, traceback, True)
Пример #7
0
 def send(self, cmd):
     if not self.comms_started:
         try:
             self.leem_com.send("asc")
             self.comms_started=True
         except:
             exceptionType, exception, traceback=sys.exc_info();
             handle_messages.log(None, "Error sending asc command to leem2000 at " + str(self.leem_com.address) + ":" + str(self.leem_com.port) +". Try restarting Leem2000 ", exceptionType, exception, traceback, True)
     return self.leem_com.send(cmd)
def getVisit():
    """
    Returns string representing current visit ID, eg cm4963-2
    """
    try:
        gdaMetaProvider=GDAMetadataProvider.getInstance()
    except:
        exceptionType, exception, traceback = sys.exc_info()
        handle_messages.log(None, "problem getting GDA metadata provider", exceptionType, exception, traceback, False)
        print "Failed to get GDA metadata provider:", exception
    return gdaMetaProvider.getMetadataValue(GDAMetadataProvider.EXPERIMENT_IDENTIFIER)
def getVisitRootPath():
    """
    Returns string representing current visit root path, eg /dls/i12/data/2014/cm4963-2
    """
    try:
        subDirname = finder.find("GDAMetadata").getMetadataValue("subdirectory")
    except:
        exceptionType, exception, traceback = sys.exc_info()
        handle_messages.log(None, "problem getting metadata value for 'subdirectory' ", exceptionType, exception, traceback, False)
        print "Failed to get metadata value for subdirectory:", exception
    workDirpath = wd()
    if (subDirname is not None) and (subDirname != ""):
        visitRootpath = rreplace(workDirpath, os.sep+subDirname,"",1)
    else:
        visitRootpath = workDirpath
    return visitRootpath
Пример #10
0
def cameraFactory(cam_name, peak2d_name, max2d_name, camdet, camdet_for_snaps):
    # ----------------------------------------------------------------------
    try:
        print "Creating %s, %s and %s" % \
            (cam_name, peak2d_name, max2d_name)
        # This has no hardware triggered mode configured. This class is used to hijack its DetectorSnapper implementation.
        cam = SwitchableHardwareTriggerableProcessingDetectorWrapper(
            cam_name, camdet, None, camdet_for_snaps, [],
            panel_name=None, panel_name_rcp='Plot 1',
            toreplace=None, replacement=None, iFileLoader=TIFFImageLoader,
            fileLoadTimout=15, returnPathAsImageNumberOnly=True)
        peak2d = DetectorDataProcessorWithRoi(peak2d_name, cam, [TwodGaussianPeak()])
        max2d = DetectorDataProcessorWithRoi(max2d_name, cam, [SumMaxPositionAndValue()])
    # ----------------------------------------------------------------------
        return cam, peak2d, max2d
    except:
        import sys
        typ, exception, traceback = sys.exc_info()
        handle_messages.log(None, "%s error -  " % cam_name, typ, exception, traceback, False)
Пример #11
0
def time_scan(numberOfLoops, scan_constructor, scanPlotSettings, args):
    print "time_scan : ", ` scan_constructor `, ` args `
    times = []
    timebase = time()
    filename = strftime("%Y-%m-%d_%H-%M-%S_time_scan.dat")
    file = open(filename, "w")
    try:
        loop = 0
        loop_count = 0
        while (True):
            scan = scan_constructor(args)
            if scanPlotSettings != None:
                scan.setScanPlotSettings(scanPlotSettings)
            scan.runScan()
            loop += 1
            timenow = time()
            t = timenow - timebase
            timebase = timenow
            times.append(t)
            file.write( ` loop ` + "," + ` t `)
            if numberOfLoops > 0:
                loop_count += 1
                if loop_count >= numberOfLoops:
                    break
    except:
        type, exception, traceback = sys.exc_info()
        toRaise = not isinstance(exception, java.lang.InterruptedException)
        handle_messages.log(None, "time_scan exception", type, exception,
                            traceback, toRaise)
    file.close
    filename = strftime("%Y-%m-%d_%H-%M-%S_time_scan.dat_srs")
    if len(times) > 0:
        xName = "loop"
        yName = "time"
        sfh = plotData.getScanFileHolderY(xName, yName, times)
        sfh.save(SRSLoader(filename))
        sfh.plot(xName, yName)
    return filename
Пример #12
0
def scan(*args):
    """
	Moves several scannable objects simultaneously,	the same number of steps. 
	After each movement data is collected from items in the allDetectors vector.
	Expect arguments in the following format:
	scannable1 start stop step scannable2 [start] [[stop] step] scannable3 [start] [[stop] step]
	The number of steps is calculated from scannable1.
	For subsequent scannables: if only start then they are moved only to that position. If no start value given then
	the current position will be used (so this scannable will not be moved, but will be included in any output from the
	scan.)
	If a step value given then the scannable will be moved each time
	If a stop value is also given then this is treated as a nested scan containing one scannable. 
	This scan will be run in full at each node of the main scan. 
	If there are multiple nested scans then they are nested inside each other to
	create a multidimensional scan space (rasta scan).	
	"""
    print args
    try:
        ConcurrentScan(args[0]).runScan()
    except:
        type, exception, traceback = sys.exc_info()
        handle_messages.log(None, "scan failed", type, exception, traceback,
                            True)
Пример #13
0
def time_scan(numberOfLoops, scan_constructor, scanPlotSettings, args):
	print "time_scan : ", `scan_constructor`,`args`
	times=[]
	timebase = time()
	filename = strftime("%Y-%m-%d_%H-%M-%S_time_scan.dat")
	file = open(filename,"w")
	try:
		loop=0;
		loop_count=0
		while(True):
			scan = scan_constructor(args)
			if scanPlotSettings != None:
				scan.setScanPlotSettings(scanPlotSettings)
			scan.runScan()
			loop += 1
			timenow = time()
			t = timenow - timebase
			timebase = timenow
			times.append(t)
			file.write( `loop` + "," + `t`)
			if numberOfLoops > 0:
				loop_count += 1
				if loop_count >= numberOfLoops:
					break
	except :
		type, exception, traceback = sys.exc_info()	
		toRaise = not isinstance(exception, java.lang.InterruptedException)
		handle_messages.log(None,"time_scan exception", type, exception, traceback, toRaise)
	file.close
	filename = strftime("%Y-%m-%d_%H-%M-%S_time_scan.dat_srs")
	if len(times)>0:
		xName="loop"
		yName="time"
		sfh = plotData.getScanFileHolderY(xName,yName,times)
		sfh.save( SRSLoader(filename))
		sfh.plot(xName, yName)
	return filename
Пример #14
0
def reload_tables(logInfo=True):
    """reloads all lookup tables on the ObjectServer"""
    ok = True
    controller = None
    prefix = "reload_tables:"
    if( logInfo ):
        handle_messages.log(controller, prefix + " - started") 
    finder = Finder.getInstance()
    converters = finder.listAllObjects("IReloadableQuantitiesConverter")
    for converter in converters:
        try:
            if( logInfo ):
                handle_messages.log(controller, prefix + "..." + converter.getName() )      
            converter.reloadConverter()
        except:
            type1, exception, traceback = sys.exc_info()
            handle_messages.log(controller, prefix + " - ", type1, exception, traceback, False)
            ok = False
    if( logInfo ):
        handle_messages.log(controller, prefix + " - completed")
    if( not ok):
        print "reload_tables completed with error"
    return ok
Пример #15
0
def reloadLookupTablesEx(logInfo):
    """version of reloadLookupTables that can be used in tests to only generate output when an error is detected"""
    ok = True
    controller = None
    prefix = "reloadLookupTables:"
    if (logInfo):
        handle_messages.log(controller, prefix + " - started")
        converters = Finder.listFindablesOfType(IReloadableQuantitiesConverter)
        for converter in converters:
            try:
                if (logInfo):
                    handle_messages.log(controller,
                                        prefix + "..." + converter.getName())
                    converter.reloadConverter()
            except:
                type, exception, traceback = sys.exc_info()
                handle_messages.log(controller, prefix + " - ", type,
                                    exception, traceback, False)
                ok = False
    if (logInfo):
        handle_messages.log(controller, prefix + " - completed")
    if (not ok):
        print "reloadLookupTables completed with error"
    return ok
Пример #16
0
    #UNOmotor1 = arduinoMotor.arduinoMotor("UNOmotor1", 4096, UNOmotor1a, UNOmotor1b, UNOmotor1c, UNOmotor1d)

    #===================================================
    #End of Raspberry Pi Specific Objects
    #===================================================

    #run user editable startup script 
    if isLive():
        run("localStationUser.py")




except:
    exceptionType, exception, traceback = sys.exc_info()
    handle_messages.log(None, "Error in localStation", exceptionType, exception, traceback, False)



def roboscan(sample,quality=2):
    carousel.sampleCarousel(sample)
    robotarm.loadSample(sample)
    sleep(5)
    scan turntable 0 720 14.4 picamera
    robotarm.unloadSample(sample)
    carousel.sampleCarousel(1)
    print "*** " + picamera.datFile



Пример #17
0
def tomoScanWithFrames(description,
                       inBeamPosition,
                       outOfBeamPosition,
                       exposureTime=1.,
                       start=0.,
                       stop=180.,
                       step=0.1,
                       darkFieldInterval=0,
                       flatFieldInterval=0,
                       imagesPerDark=10,
                       imagesPerFlat=10,
                       optimizeBeamInterval=0,
                       pattern="default",
                       nframes=1,
                       tomoRotationAxis=0,
                       addNXEntry=True,
                       autoAnalyse=True,
                       additionalScannables=[]):
    """
    Function to collect a tomography step scan with multiple projection frames per scan point 
    Arguments:
    description - description of the scan or the sample that is being scanned. This is generally user-specific information that may be used to map to this scan later and is available in the NeXus file)
    inBeamPosition - position of X drive to move sample into the beam to take a projection
    outOfBeamPosition - position of X drive to move sample out of the beam to take a flat field image
    exposureTime - exposure time in seconds (default=1.0)
    start - first rotation angle (default=0.0)
    stop  - last rotation angle (default=180.0)
    step - rotation step size (default=0.1)
    darkFieldInterval - number of projection-frame sub-series between each dark-field sub-series. 
        NOTE: at least 1 dark is ALWAYS taken both at the start and end of the scan, provided imagesPerDark>0 
        (default=0: use this value if you DON'T want to take any darks between projections)
    flatFieldInterval - number of projection-frame sub-series between each flat-field sub-series. 
        NOTE: at least 1 flat is ALWAYS taken both at the start and end the scan, provided imagesPerFlat>0 
        (default=0: use this value if you DON'T want to take any flats between projections)
    imagesPerDark - number of images to be taken in each dark-field sub-series (default=10)
    imagesPerFlat - number of images to be taken in each flat-field sub-series (default=10)
    nframes - number of projection frames per angular position (default=1)
    
    General scan sequence is: D, F, P,..., P, F, D
    where D stands for dark field, F - for flat field, and P - for projection.
    """
    dataFormat = LocalProperties.get("gda.data.scan.datawriter.dataFormat")
    try:
        darkFieldInterval = int(darkFieldInterval)
        flatFieldInterval = int(flatFieldInterval)
        optimizeBeamInterval = int(optimizeBeamInterval)

        image_key_frame = 3
        nframes = int(nframes)
        if nframes < 1:
            nframes = 1

        jns = beamline_parameters.JythonNameSpaceMapping(
            InterfaceProvider.getJythonNamespace())
        tomography_theta = jns.tomography_theta
        if tomography_theta is None:
            raise NameError(
                "tomography_theta is not defined in Jython namespace")
        tomography_shutter = jns.tomography_shutter
        if tomography_shutter is None:
            raise NameError(
                "tomography_shutter is not defined in Jython namespace")
        tomography_translation = jns.tomography_translation
        if tomography_translation is None:
            raise NameError(
                "tomography_translation is not defined in Jython namespace")

        tomography_detector = jns.tomography_detector
        if tomography_detector is None:
            raise NameError(
                "tomography_detector is not defined in Jython namespace")

        tomography_optimizer = jns.tomography_optimizer
        if tomography_optimizer is None:
            raise NameError(
                "tomography_optimizer is not defined in Jython namespace")

        tomography_time = jns.tomography_time
        if tomography_time is None:
            raise NameError(
                "tomography_time is not defined in Jython namespace")

        tomography_beammonitor = jns.tomography_beammonitor
        if tomography_beammonitor is None:
            raise NameError(
                "tomography_beammonitor is not defined in Jython namespace")

        tomography_camera_stage = jns.tomography_camera_stage
        if tomography_camera_stage is None:
            raise NameError(
                "tomography_camera_stage is not defined in Jython namespace")

        tomography_sample_stage = jns.tomography_sample_stage
        if tomography_sample_stage is None:
            raise NameError(
                "tomography_sample_stage is not defined in Jython namespace")

        tomo_additional_scannables = jns.tomography_additional_scannables
        if tomo_additional_scannables is None:
            raise NameError(
                "tomo_additional_scannables is not defined in Jython namespace"
            )

        index = SimpleScannable()
        index.setCurrentPosition(0.0)
        index.setInputNames(["imageNumber"])
        index.setName("imageNumber")
        index.configure()

        image_key = SimpleScannable()
        image_key.setCurrentPosition(0.0)
        image_key.setInputNames(["image_key"])
        image_key.setName("image_key")
        image_key.configure()

        tomoScanDevice = make_tomoScanDevice(tomography_theta,
                                             tomography_shutter,
                                             tomography_translation,
                                             tomography_optimizer, image_key,
                                             index)

        #        return tomoScanDevice
        #generate list of positions
        numberSteps = ScannableUtils.getNumberSteps(tomography_theta, start,
                                                    stop, step)
        theta_points = []
        theta_points.append(start)
        previousPoint = start
        for i in range(numberSteps):
            nextPoint = ScannableUtils.calculateNextPoint(previousPoint, step)
            theta_points.append(nextPoint)
            previousPoint = nextPoint

        #generateScanPoints
        optimizeBeamNo = 0
        optimizeBeamYes = 1
        shutterOpen = 1
        shutterClosed = 0
        shutterNoChange = 2
        scan_points = []
        theta_pos = theta_points[0]
        index = 0
        #Added shutterNoChange state for the shutter. The scan points are added using the (pseudo) ternary operator,
        #if index is 0 then the shutterPosition is added to the scan point, else shutterNoChange is added to scan points.
        for i in range(imagesPerDark):
            scan_points.append(
                (theta_pos, [shutterClosed, shutterNoChange][i != 0],
                 inBeamPosition, optimizeBeamNo, image_key_dark, index))  #dark
            index = index + 1

        for i in range(imagesPerFlat):
            scan_points.append(
                (theta_pos, [shutterOpen,
                             shutterNoChange][i != 0], outOfBeamPosition,
                 optimizeBeamNo, image_key_flat, index))  #flat
            index = index + 1
        for frm in range(nframes):
            scan_points.append(
                (theta_pos, shutterOpen, inBeamPosition, optimizeBeamNo,
                 image_key_project if frm == 0 else image_key_frame,
                 index))  #first
            index = index + 1
        imageSinceDark = 1
        imageSinceFlat = 1
        optimizeBeam = 0
        for i in range(numberSteps):
            theta_pos = theta_points[i + 1]
            for frm in range(nframes):
                scan_points.append(
                    (theta_pos, [shutterOpen, shutterNoChange
                                 ][i != 0], inBeamPosition, optimizeBeamNo,
                     image_key_project if frm == 0 else image_key_frame,
                     index))  #main image
                index = index + 1

            imageSinceFlat = imageSinceFlat + 1
            if imageSinceFlat == flatFieldInterval and flatFieldInterval != 0:
                for i in range(imagesPerFlat):
                    scan_points.append(
                        (theta_pos, [shutterOpen, shutterNoChange
                                     ][i != 0], outOfBeamPosition,
                         optimizeBeamNo, image_key_flat, index))
                    index = index + 1
                    imageSinceFlat = 0

            imageSinceDark = imageSinceDark + 1
            if imageSinceDark == darkFieldInterval and darkFieldInterval != 0:
                for i in range(imagesPerDark):
                    scan_points.append(
                        (theta_pos, [shutterClosed,
                                     shutterNoChange][i != 0], inBeamPosition,
                         optimizeBeamNo, image_key_dark, index))
                    index = index + 1
                    imageSinceDark = 0

            optimizeBeam = optimizeBeam + 1
            if optimizeBeam == optimizeBeamInterval and optimizeBeamInterval != 0:
                scan_points.append(
                    (theta_pos, [shutterOpen,
                                 shutterNoChange][i != 0], inBeamPosition,
                     optimizeBeamYes, image_key_project, index))
                index = index + 1
                optimizeBeam = 0

        #add dark and flat only if not done in last steps
        if imageSinceFlat != 0:
            for i in range(imagesPerFlat):
                scan_points.append(
                    (theta_pos, [shutterOpen,
                                 shutterNoChange][i != 0], outOfBeamPosition,
                     optimizeBeamNo, image_key_flat, index))  #flat
                index = index + 1
        if imageSinceDark != 0:
            for i in range(imagesPerDark):
                scan_points.append(
                    (theta_pos, [shutterClosed,
                                 shutterNoChange][i != 0], inBeamPosition,
                     optimizeBeamNo, image_key_dark, index))  #dark
                index = index + 1


#        scan_points1 = generateScanPoints(inBeamPosition, outOfBeamPosition, theta_points, darkFieldInterval, flatFieldInterval,
#              imagesPerDark, imagesPerFlat, optimizeBeamInterval, pattern=pattern)
#        if pattern == 'default' or pattern == 'DFPFD':
#            i = 0
#            for pt1 in scan_points1:
#                pt = scan_points[i]
#                if pt1 != pt:
#                    print "Mismatch - please tell Kaz about your scan and its arguments!"
#                    print "i = ", i
#                    print "pt = ", pt
#                    print "pt1 = ", pt1
#                i += 1
#return None
        positionProvider = tomoScan_positions(start, stop, step, darkFieldInterval, imagesPerDark, flatFieldInterval, imagesPerFlat, \
                                               inBeamPosition, outOfBeamPosition, optimizeBeamInterval, scan_points)
        scan_args = [
            tomoScanDevice, positionProvider, tomography_time,
            tomography_beammonitor, tomography_detector, exposureTime,
            tomography_camera_stage, tomography_sample_stage
        ]
        #scan_args.append(RotationAxisScannable("approxCOR", tomoRotationAxis))
        #meta_add(RotationAxisScannable("approxCOR", tomoRotationAxis))
        #meta_add("RotationCoord_as_list", [tomoRotationAxis])
        meta_add("approxCOR", tomoRotationAxis)
        for scannable in additionalScannables:
            scan_args.append(scannable)
        for scannable in tomo_additional_scannables:
            scan_args.append(scannable)
        ''' setting the description provided as the title'''
        if not description == None:
            setTitle(description)
        else:
            setTitle("undefined")

        dataFormat = LocalProperties.get("gda.data.scan.datawriter.dataFormat")
        if not dataFormat == "NexusDataWriter":
            handle_messages.simpleLog(
                "Data format inconsistent. Setting 'gda.data.scan.datawriter.dataFormat' to 'NexusDataWriter'"
            )
            LocalProperties.set("gda.data.scan.datawriter.dataFormat",
                                "NexusDataWriter")
        scanObject = createConcurrentScan(scan_args)
        if addNXEntry:
            addNXTomoSubentry(scanObject, tomography_detector.name,
                              tomography_theta.name)
        scanObject.runScan()
        if autoAnalyse:
            lsdp = jns.lastScanDataPoint()
            OSCommandRunner.runNoWait([
                "/dls_sw/apps/tomopy/tomopy/bin/gda/tomo_at_scan_end_kz",
                lsdp.currentFilename
            ], OSCommandRunner.LOGOPTION.ALWAYS, None)
        return scanObject
    except InterruptedException:
        exceptionType, exception, traceback = sys.exc_info()
        handle_messages.log(None, "User interrupted the scan", exceptionType,
                            exception, traceback, False)
        raise InterruptedException("User interrupted the scan")
    except:
        exceptionType, exception, traceback = sys.exc_info()
        handle_messages.log(None, "Error during tomography scan",
                            exceptionType, exception, traceback, False)
        raise Exception("Error during tomography scan", exception)
    finally:
        handle_messages.simpleLog(
            "Data Format reset to the original setting: " + dataFormat)
        LocalProperties.set("gda.data.scan.datawriter.dataFormat", dataFormat)
Пример #18
0
def tomoScan(
    description,
    inBeamPosition,
    outOfBeamPosition,
    exposureTime=1.0,
    start=0.0,
    stop=180.0,
    step=0.1,
    darkFieldInterval=0,
    flatFieldInterval=0,
    imagesPerDark=10,
    imagesPerFlat=10,
    optimizeBeamInterval=0,
    pattern="default",
    tomoRotationAxis=0,
    addNXEntry=True,
    autoAnalyse=True,
    additionalScannables=[],
):
    """
    Function to collect a tomography step scan
    Arguments:
    description - description of the scan or the sample that is being scanned. This is generally user-specific information that may be used to map to this scan later and is available in the NeXus file)
    inBeamPosition - position of X drive to move sample into the beam to take a projection
    outOfBeamPosition - position of X drive to move sample out of the beam to take a flat field image
    exposureTime - exposure time in seconds (default=1.0)
    start - first rotation angle (default=0.0)
    stop  - last rotation angle (default=180.0)
    step - rotation step size (default=0.1)
    darkFieldInterval - number of projections between each dark-field sub-sequence. 
        NOTE: at least 1 dark is ALWAYS taken both at the start and end of the scan provided imagesPerDark>0 
        (default=0: use this value if you DON'T want to take any darks between projections)
    flatFieldInterval - number of projections between each flat-field sub-sequence. 
        NOTE: at least 1 flat is ALWAYS taken both at the start and end the scan provided imagesPerFlat>0 
        (default=0: use this value if you DON'T want to take any flats between projections)
    imagesPerDark - number of images to be taken for each dark-field sub-sequence (default=10)
    imagesPerFlat - number of images to be taken for each flat-field sub-sequence (default=10)
    
    General scan sequence is: D, F, P,..., P, F, D
    where D stands for dark field, F - for flat field, and P - for projection.
    """
    dataFormat = LocalProperties.get("gda.data.scan.datawriter.dataFormat")
    try:
        darkFieldInterval = int(darkFieldInterval)
        flatFieldInterval = int(flatFieldInterval)
        optimizeBeamInterval = int(optimizeBeamInterval)

        jns = beamline_parameters.JythonNameSpaceMapping(InterfaceProvider.getJythonNamespace())
        tomography_theta = jns.tomography_theta
        if tomography_theta is None:
            raise "tomography_theta is not defined in Jython namespace"
        tomography_shutter = jns.tomography_shutter
        if tomography_shutter is None:
            raise "tomography_shutter is not defined in Jython namespace"
        tomography_translation = jns.tomography_translation
        if tomography_translation is None:
            raise "tomography_translation is not defined in Jython namespace"

        tomography_detector = jns.tomography_detector
        if tomography_detector is None:
            raise "tomography_detector is not defined in Jython namespace"

        tomography_optimizer = jns.tomography_optimizer
        if tomography_optimizer is None:
            raise "tomography_optimizer is not defined in Jython namespace"

        tomography_time = jns.tomography_time
        if tomography_time is None:
            raise "tomography_time is not defined in Jython namespace"

        tomography_beammonitor = jns.tomography_beammonitor
        if tomography_beammonitor is None:
            raise "tomography_beammonitor is not defined in Jython namespace"

        tomography_camera_stage = jns.tomography_camera_stage
        if tomography_camera_stage is None:
            raise "tomography_camera_stage is not defined in Jython namespace"

        tomography_sample_stage = jns.tomography_sample_stage
        if tomography_sample_stage is None:
            raise "tomography_sample_stage is not defined in Jython namespace"

        tomo_additional_scannables = jns.tomography_additional_scannables
        if tomo_additional_scannables is None:
            raise "tomo_additional_scannables is not defined in Jython namespace"

        index = SimpleScannable()
        index.setCurrentPosition(0.0)
        index.setInputNames(["imageNumber"])
        index.setName("imageNumber")
        index.configure()

        image_key = SimpleScannable()
        image_key.setCurrentPosition(0.0)
        image_key.setInputNames(["image_key"])
        image_key.setName("image_key")
        image_key.configure()

        tomoScanDevice = make_tomoScanDevice(
            tomography_theta, tomography_shutter, tomography_translation, tomography_optimizer, image_key, index
        )

        #        return tomoScanDevice
        # generate list of positions
        numberSteps = ScannableUtils.getNumberSteps(tomography_theta, start, stop, step)
        theta_points = []
        theta_points.append(start)
        previousPoint = start
        for i in range(numberSteps):
            nextPoint = ScannableUtils.calculateNextPoint(previousPoint, step)
            theta_points.append(nextPoint)
            previousPoint = nextPoint

        # generateScanPoints
        optimizeBeamNo = 0
        optimizeBeamYes = 1
        shutterOpen = 1
        shutterClosed = 0
        shutterNoChange = 2
        scan_points = []
        theta_pos = theta_points[0]
        index = 0
        # Added shutterNoChange state for the shutter. The scan points are added using the (pseudo) ternary operator,
        # if index is 0 then the shutterPosition is added to the scan point, else shutterNoChange is added to scan points.
        for i in range(imagesPerDark):
            scan_points.append(
                (
                    theta_pos,
                    [shutterClosed, shutterNoChange][i != 0],
                    inBeamPosition,
                    optimizeBeamNo,
                    image_key_dark,
                    index,
                )
            )  # dark
            index = index + 1

        for i in range(imagesPerFlat):
            scan_points.append(
                (
                    theta_pos,
                    [shutterOpen, shutterNoChange][i != 0],
                    outOfBeamPosition,
                    optimizeBeamNo,
                    image_key_flat,
                    index,
                )
            )  # flat
            index = index + 1
        scan_points.append((theta_pos, shutterOpen, inBeamPosition, optimizeBeamNo, image_key_project, index))  # first
        index = index + 1
        imageSinceDark = 1
        imageSinceFlat = 1
        optimizeBeam = 0
        for i in range(numberSteps):
            theta_pos = theta_points[i + 1]
            scan_points.append(
                (
                    theta_pos,
                    [shutterOpen, shutterNoChange][i != 0],
                    inBeamPosition,
                    optimizeBeamNo,
                    image_key_project,
                    index,
                )
            )  # main image
            index = index + 1

            imageSinceFlat = imageSinceFlat + 1
            if imageSinceFlat == flatFieldInterval and flatFieldInterval != 0:
                for i in range(imagesPerFlat):
                    scan_points.append(
                        (
                            theta_pos,
                            [shutterOpen, shutterNoChange][i != 0],
                            outOfBeamPosition,
                            optimizeBeamNo,
                            image_key_flat,
                            index,
                        )
                    )
                    index = index + 1
                    imageSinceFlat = 0

            imageSinceDark = imageSinceDark + 1
            if imageSinceDark == darkFieldInterval and darkFieldInterval != 0:
                for i in range(imagesPerDark):
                    scan_points.append(
                        (
                            theta_pos,
                            [shutterClosed, shutterNoChange][i != 0],
                            inBeamPosition,
                            optimizeBeamNo,
                            image_key_dark,
                            index,
                        )
                    )
                    index = index + 1
                    imageSinceDark = 0

            optimizeBeam = optimizeBeam + 1
            if optimizeBeam == optimizeBeamInterval and optimizeBeamInterval != 0:
                scan_points.append(
                    (
                        theta_pos,
                        [shutterOpen, shutterNoChange][i != 0],
                        inBeamPosition,
                        optimizeBeamYes,
                        image_key_project,
                        index,
                    )
                )
                index = index + 1
                optimizeBeam = 0

        # add dark and flat only if not done in last steps
        if imageSinceFlat != 0:
            for i in range(imagesPerFlat):
                scan_points.append(
                    (
                        theta_pos,
                        [shutterOpen, shutterNoChange][i != 0],
                        outOfBeamPosition,
                        optimizeBeamNo,
                        image_key_flat,
                        index,
                    )
                )  # flat
                index = index + 1
        if imageSinceDark != 0:
            for i in range(imagesPerDark):
                scan_points.append(
                    (
                        theta_pos,
                        [shutterClosed, shutterNoChange][i != 0],
                        inBeamPosition,
                        optimizeBeamNo,
                        image_key_dark,
                        index,
                    )
                )  # dark
                index = index + 1
        scan_points1 = generateScanPoints(
            inBeamPosition,
            outOfBeamPosition,
            theta_points,
            darkFieldInterval,
            flatFieldInterval,
            imagesPerDark,
            imagesPerFlat,
            optimizeBeamInterval,
            pattern=pattern,
        )
        if pattern == "default" or pattern == "DFPFD":
            i = 0
            for pt1 in scan_points1:
                pt = scan_points[i]
                if pt1 != pt:
                    print "Mismatch - please tell Kaz about your scan and its arguments!"
                    print "i = ", i
                    print "pt = ", pt
                    print "pt1 = ", pt1
                i += 1
        # return None
        positionProvider = tomoScan_positions(
            start,
            stop,
            step,
            darkFieldInterval,
            imagesPerDark,
            flatFieldInterval,
            imagesPerFlat,
            inBeamPosition,
            outOfBeamPosition,
            optimizeBeamInterval,
            scan_points,
        )
        scan_args = [
            tomoScanDevice,
            positionProvider,
            tomography_time,
            tomography_beammonitor,
            tomography_detector,
            exposureTime,
            tomography_camera_stage,
            tomography_sample_stage,
        ]
        # scan_args.append(RotationAxisScannable("approxCOR", tomoRotationAxis))
        # meta_add(RotationAxisScannable("approxCOR", tomoRotationAxis))
        # meta_add("RotationCoord_as_list", [tomoRotationAxis])
        meta_add("approxCOR", tomoRotationAxis)
        for scannable in additionalScannables:
            scan_args.append(scannable)
        for scannable in tomo_additional_scannables:
            scan_args.append(scannable)
        """ setting the description provided as the title"""
        if not description == None:
            setTitle(description)
        else:
            setTitle("undefined")

        dataFormat = LocalProperties.get("gda.data.scan.datawriter.dataFormat")
        if not dataFormat == "NexusDataWriter":
            handle_messages.simpleLog(
                "Data format inconsistent. Setting 'gda.data.scan.datawriter.dataFormat' to 'NexusDataWriter'"
            )
            LocalProperties.set("gda.data.scan.datawriter.dataFormat", "NexusDataWriter")
        scanObject = createConcurrentScan(scan_args)
        if addNXEntry:
            addNXTomoSubentry(scanObject, tomography_detector.name, tomography_theta.name)
        scanObject.runScan()
        if autoAnalyse:
            lsdp = jns.lastScanDataPoint()
            OSCommandRunner.runNoWait(
                ["/dls_sw/apps/tomopy/tomopy/bin/gda/tomo_at_scan_end", lsdp.currentFilename],
                OSCommandRunner.LOGOPTION.ALWAYS,
                None,
            )
        return scanObject
    except InterruptedException:
        exceptionType, exception, traceback = sys.exc_info()
        handle_messages.log(None, "User interrupted the scan", exceptionType, exception, traceback, False)
        raise InterruptedException("User interrupted the scan")
    except:
        exceptionType, exception, traceback = sys.exc_info()
        handle_messages.log(None, "Error during tomography scan", exceptionType, exception, traceback, False)
        raise Exception("Error during tomography scan", exception)
    finally:
        handle_messages.simpleLog("Data Format reset to the original setting: " + dataFormat)
        LocalProperties.set("gda.data.scan.datawriter.dataFormat", dataFormat)
Пример #19
0
def localStation_exception(exc_info, msg):
    typ, exception, traceback = exc_info
    simpleLog("! Failure %s !" % msg)
    localStation_exceptions.append("    %s" % msg)
    handle_messages.log(None, "Error %s -  " % msg , typ, exception, traceback, False)
Пример #20
0
    alias("caget")
    
    from gda.scan.RepeatScan import create_repscan, repscan
    vararg_alias("repscan")

    #setup tools to create metadata in Nexus files
    from gdascripts.metadata.metadata_commands import setTitle, meta_add, meta_ll, meta_ls, meta_rm
    alias("setTitle")
    alias("meta_add")
    alias("meta_ll")
    alias("meta_ls")
    alias("meta_rm")
    from gda.data.scan.datawriter import NexusDataWriter
    LocalProperties.set(NexusDataWriter.GDA_NEXUS_METADATAPROVIDER_NAME,"metashop")
    
    #create time scannables
    from gdascripts.pd.time_pds import waittimeClass2, showtimeClass, showincrementaltimeClass, actualTimeClass
    waittime=waittimeClass2('waittime')
    showtime=showtimeClass('showtime')
    inctime=showincrementaltimeClass('inctime')
    actualTime=actualTimeClass("actualTime")

    #run user editable startup script 
    if isLive():
        run("localStationUser.py")

except:
    exceptionType, exception, traceback = sys.exc_info()
    handle_messages.log(None, "Error in localStation", exceptionType, exception, traceback, False)