Esempio n. 1
0
def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max,  background_min, background_max, int_min, int_max,
                   point_detector_start=0, point_detector_stop=0, multi_detector_start=0, theta=None,
                   pointdet=True,roi=[0,0], db=[0,0], trans='', debug=False, correction_strategy=NullCorrectionStrategy(),
                   stitch_start_overlap=None, stitch_end_overlap=None, stitch_params=None,
                   polcorr=False, crho=None, calpha=None, cAp=None, cPp=None, detector_component_name='point-detector',
                   sample_component_name='some-surface-holder', correct_positions=True ):

    '''
    Version of quick where all parameters are explicitly provided.
    '''

    _sample_ws = ConvertToWavelength.to_single_workspace(run)
    nHist =  _sample_ws.getNumberHistograms()
    to_lam = ConvertToWavelength(run)

    if pointdet:
        detector_index_ranges = (point_detector_start, point_detector_stop)
    else:
        detector_index_ranges = (multi_detector_start, nHist-1)


    _monitor_ws, _detector_ws = to_lam.convert(wavelength_min=lambda_min, wavelength_max=lambda_max, detector_workspace_indexes=detector_index_ranges, monitor_workspace_index=i0_monitor_index, correct_monitor=True, bg_min=background_min, bg_max=background_max )

    inst = _sample_ws.getInstrument()
    # Some beamline constants from IDF

    print i0_monitor_index
    print nHist

    if (run=='0'):
        RunNumber = '0'
    else:
        RunNumber = groupGet(_sample_ws.getName(),'samp','run_number')

    if not pointdet:
        # Proccess Multi-Detector; assume MD goes to the end:
        # if roi or db are given in the function then sum over the apropriate channels
        print "This is a multidetector run."

        _I0M = RebinToWorkspace(WorkspaceToRebin=_monitor_ws,WorkspaceToMatch=_detector_ws)
        IvsLam = _detector_ws / _I0M
        if (roi != [0,0]) :
            ReflectedBeam = SumSpectra(InputWorkspace=IvsLam, StartWorkspaceIndex=roi[0], EndWorkspaceIndex=roi[1])
        if (db != [0,0]) :
            DirectBeam = SumSpectra(InputWorkspace=_detector_ws, StartWorkspaceIndex=db[0], EndWorkspaceIndex=db[1])
            ReflectedBeam = ReflectedBeam / DirectBeam
        polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp)
        if (theta and correct_positions):
            IvsQ = l2q(ReflectedBeam, detector_component_name, theta, sample_component_name)
        else:
            IvsQ = ConvertUnits(InputWorkspace=ReflectedBeam, Target="MomentumTransfer")


    # Single Detector processing-------------------------------------------------------------
    else:
        print "This is a Point-Detector run."
        # handle transmission runs
        # process the point detector reflectivity
        _I0P = RebinToWorkspace(WorkspaceToRebin=_monitor_ws,WorkspaceToMatch=_detector_ws)
        IvsLam = Scale(InputWorkspace=_detector_ws,Factor=1)

        if not trans:
            print "No transmission file. Trying default exponential/polynomial correction..."
            IvsLam = correction_strategy.apply(_detector_ws)
            IvsLam = Divide(LHSWorkspace=IvsLam, RHSWorkspace=_I0P)
        else: # we have a transmission run
            _monInt = Integration(InputWorkspace=_I0P,RangeLower=int_min,RangeUpper=int_max)
            IvsLam = Divide(LHSWorkspace=_detector_ws,RHSWorkspace=_monInt)
            names = mtd.getObjectNames()

            IvsLam = transCorr(trans, IvsLam, lambda_min, lambda_max, background_min, background_max,
                               int_min, int_max, detector_index_ranges, i0_monitor_index, stitch_start_overlap,
                               stitch_end_overlap, stitch_params )


        IvsLam = polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp)



        # Convert to I vs Q
        # check if detector in direct beam
        if (theta == None or theta == 0 or theta == ''):
            inst = groupGet('IvsLam','inst')
            detLocation=inst.getComponentByName(detector_component_name).getPos()
            sampleLocation=inst.getComponentByName(sample_component_name).getPos()
            detLocation=inst.getComponentByName(detector_component_name).getPos()
            sample2detector=detLocation-sampleLocation    # metres
            source=inst.getSource()
            beamPos = sampleLocation - source.getPos()
            PI = 3.1415926535
            theta = groupGet(str(_sample_ws),'samp','theta')
            if not theta:
                theta = inst.getComponentByName(detector_component_name).getTwoTheta(sampleLocation, beamPos)*180.0/PI/2.0
            print "Det location: ", detLocation, "Calculated theta = ",theta
            if correct_positions:  # detector is not in correct place
                # Get detector angle theta from NeXuS
                logger.information('The detectorlocation is not at Y=0')
                print 'Nexus file theta =', theta
                IvsQ = l2q(IvsLam, detector_component_name, theta, sample_component_name)
            else:
                IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")

        else:
            if correct_positions:
                theta = float(theta)
                try:
                    IvsQ = l2q(IvsLam, detector_component_name, theta, sample_component_name)
                except AttributeError:
                    logger.warning("detector_component_name " + detector_component_name + " is unknown")
                    IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")
            else:
                IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")

    RenameWorkspace(InputWorkspace=IvsLam,OutputWorkspace=RunNumber+'_IvsLam')
    if isinstance(IvsLam, WorkspaceGroup):
        counter = 0
        for ws in IvsLam:
            RenameWorkspace(ws, OutputWorkspace=RunNumber+'_IvsLam_'+str(counter))
            counter += 1
    RenameWorkspace(InputWorkspace=IvsQ,OutputWorkspace=RunNumber+'_IvsQ')

    # delete all temporary workspaces unless in debug mode (debug=1)

    if not debug:
        cleanup()
        if mtd.doesExist('IvsLam'):
            DeleteWorkspace('IvsLam')
    return  mtd[RunNumber+'_IvsLam'], mtd[RunNumber+'_IvsQ'], theta
Esempio n. 2
0
def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max,  background_min, background_max, int_min, int_max,
                   point_detector_start=0, point_detector_stop=0, multi_detector_start=0, theta=None,
                   pointdet=True,roi=[0,0], db=[0,0], trans='', debug=False, correction_strategy=NullCorrectionStrategy(),
                   stitch_start_overlap=None, stitch_end_overlap=None, stitch_params=None,
                   polcorr=False, crho=None, calpha=None, cAp=None, cPp=None, detector_component_name='point-detector',
                   sample_component_name='some-surface-holder', correct_positions=True ):

    '''
    Version of quick where all parameters are explicitly provided.
    '''

    _sample_ws = ConvertToWavelength.to_single_workspace(run)
    nHist =  _sample_ws.getNumberHistograms()
    to_lam = ConvertToWavelength(run)

    if pointdet:
        detector_index_ranges = (point_detector_start, point_detector_stop)
    else:
        detector_index_ranges = (multi_detector_start, nHist-1)


    _monitor_ws, _detector_ws = to_lam.convert(wavelength_min=lambda_min, wavelength_max=lambda_max, detector_workspace_indexes=detector_index_ranges, monitor_workspace_index=i0_monitor_index, correct_monitor=True, bg_min=background_min, bg_max=background_max )

    inst = _sample_ws.getInstrument()
    # Some beamline constants from IDF

    print i0_monitor_index
    print nHist

    if (run=='0'):
        RunNumber = '0'
    else:
        RunNumber = groupGet(_sample_ws.getName(),'samp','run_number')

    if not pointdet:
        # Proccess Multi-Detector; assume MD goes to the end:
        # if roi or db are given in the function then sum over the apropriate channels
        print "This is a multidetector run."

        _I0M = RebinToWorkspace(WorkspaceToRebin=_monitor_ws,WorkspaceToMatch=_detector_ws)
        IvsLam = _detector_ws / _I0M
        if (roi != [0,0]) :
            ReflectedBeam = SumSpectra(InputWorkspace=IvsLam, StartWorkspaceIndex=roi[0], EndWorkspaceIndex=roi[1])
        if (db != [0,0]) :
            DirectBeam = SumSpectra(InputWorkspace=_detector_ws, StartWorkspaceIndex=db[0], EndWorkspaceIndex=db[1])
            ReflectedBeam = ReflectedBeam / DirectBeam
        polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp)
        if (theta and correct_positions):
            IvsQ = l2q(ReflectedBeam, detector_component_name, theta, sample_component_name)
        else:
            IvsQ = ConvertUnits(InputWorkspace=ReflectedBeam, Target="MomentumTransfer")


    # Single Detector processing-------------------------------------------------------------
    else:
        print "This is a Point-Detector run."
        # handle transmission runs
        # process the point detector reflectivity
        _I0P = RebinToWorkspace(WorkspaceToRebin=_monitor_ws,WorkspaceToMatch=_detector_ws)
        IvsLam = Scale(InputWorkspace=_detector_ws,Factor=1)

        if not trans:
            print "No transmission file. Trying default exponential/polynomial correction..."
            IvsLam = correction_strategy.apply(_detector_ws)
            IvsLam = Divide(LHSWorkspace=IvsLam, RHSWorkspace=_I0P)
        else: # we have a transmission run
            _monInt = Integration(InputWorkspace=_I0P,RangeLower=int_min,RangeUpper=int_max)
            IvsLam = Divide(LHSWorkspace=_detector_ws,RHSWorkspace=_monInt)
            names = mtd.getObjectNames()

            IvsLam = transCorr(trans, IvsLam, lambda_min, lambda_max, background_min, background_max,
                               int_min, int_max, detector_index_ranges, i0_monitor_index, stitch_start_overlap,
                               stitch_end_overlap, stitch_params )


        IvsLam = polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp)



        # Convert to I vs Q
        # check if detector in direct beam
        if (theta == None or theta == 0 or theta == ''):
            inst = groupGet('IvsLam','inst')
            detLocation=inst.getComponentByName(detector_component_name).getPos()
            sampleLocation=inst.getComponentByName(sample_component_name).getPos()
            detLocation=inst.getComponentByName(detector_component_name).getPos()
            sample2detector=detLocation-sampleLocation    # metres
            source=inst.getSource()
            beamPos = sampleLocation - source.getPos()
            theta = groupGet(str(_sample_ws),'samp','theta')
            if not theta:
                theta = inst.getComponentByName(detector_component_name).getTwoTheta(sampleLocation, beamPos)*180.0/math.pi/2.0
            print "Det location: ", detLocation, "Calculated theta = ",theta
            if correct_positions:  # detector is not in correct place
                # Get detector angle theta from NeXuS
                logger.information('The detectorlocation is not at Y=0')
                print 'Nexus file theta =', theta
                IvsQ = l2q(IvsLam, detector_component_name, theta, sample_component_name)
            else:
                IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")

        else:
            if correct_positions:
                theta = float(theta)
                try:
                    IvsQ = l2q(IvsLam, detector_component_name, theta, sample_component_name)
                except AttributeError:
                    logger.warning("detector_component_name " + detector_component_name + " is unknown")
                    IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")
            else:
                IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")

    RenameWorkspace(InputWorkspace=IvsLam,OutputWorkspace=RunNumber+'_IvsLam')
    if isinstance(IvsLam, WorkspaceGroup):
        counter = 0
        for ws in IvsLam:
            RenameWorkspace(ws, OutputWorkspace=RunNumber+'_IvsLam_'+str(counter))
            counter += 1
    RenameWorkspace(InputWorkspace=IvsQ,OutputWorkspace=RunNumber+'_IvsQ')

    # delete all temporary workspaces unless in debug mode (debug=1)

    if not debug:
        cleanup()
        if mtd.doesExist('IvsLam'):
            DeleteWorkspace('IvsLam')
    return  mtd[RunNumber+'_IvsLam'], mtd[RunNumber+'_IvsQ'], theta
Esempio n. 3
0
def quick(run, theta=0, roi=[0,0], db=[0,0], trans='', outputType='pd', debug=0):
	'''
	call signature(s)::

	x=quick(RunNumber)
	x=quick(RunNumber, roi=[0,0], db=[0,0], trans=0, outputType='pd')
	x=quick(RunNumber,[1,10])
	x=quick(RunNumber,[1,10],[20,40])
	x=quick(RunNumber, trans=2568)
	x=quick(RunNumber, trans='SomeSavedWorkspaceName')
		
	Reduces a ISIS  raw or nexus file created on one of the reflectometers applying 
	only a minimum ammount of corrections. The data is left in terms of lambda.
	
	Required arguments
	=========   =====================================================================
	RunNumber	Either an ISIS run number when the paths are set up correctly or 
			the full path and filename if an ISIS raw file.
	=========   =====================================================================

	Optional keyword arguments:	
	=========   =====================================================================
	Keyword     	Description
	=========   =====================================================================
	roi		Region of interest marking the extent of the reflected beam. 
			default [0,0]
 	db		Region of interest marking the extent of the direct beam. 
			default [0,0]
	trans		transmission run number or saved workspace. The default is 0 (No 
			transmission run).  trans=-1 will supress the division of the 
			detector by the monitor.
	outputType	'pd' = point detector (Default), 'md'=  Multidetector   Will use
			this to build the equivalent of gd in the old matlab code but 
			keep all of the simple detector processing in one well organized
			function.  This should not be used by the average user.
	=========   =====================================================================

	Outputs:
	=========   =====================================================================
	x		Either a single mantid workspace or worspace group or an array 
			of them. 
	=========   =====================================================================

	Working examples:
	>>> # reduce a data set with the default parameters 
	>>> x=quick(/Users/trc/Dropbox/Work/PolrefTest/POLREF00003014.raw")

	>>> # reduce a data set with a transmission run 
	>>> t=quick(/Users/trc/Dropbox/Work/PolrefTest/POLREF00003010.raw")
	>>> x=quick(/Users/trc/Dropbox/Work/PolrefTest/POLREF00003014.raw", trans=t)
	
	>>> # reduce a data set using the multidetector and output a single reflectivity 
	>>> # where the reflected beam is between channel 121 and 130. 
	>>> x=quick(/Users/trc/Dropbox/Work/PolrefTest/POLREF00003014.raw", [121,130])


	Also see: pol

	ToDo:
		1) code for the transmisson DONE!
		2) Similar to the genie on polref add extraction from the multidetector
		3) need to make the variables stored in the frame work contain the run number. DONE!
		
	'''

	''' Notes for developers:

		Naming conventions for workspaces which live in the mantid framework are as follows:

			It's nearly random.  this needs to be fixed so that name clashes do not occur.  
			May try adding a pair of underscores to the front of the name.

	'''
	
	
	[I0MonitorIndex, MultiDetectorStart, nHist] = toLam(run,'')
	print I0MonitorIndex
	print nHist
	if (nHist > 5):
		# Proccess Multi-Detector; assume MD goes to the end:
		# if roi or db are given in the function then sum over the apropriate channels
		print "This is a multidetector run."
		try:
			CropWorkspace(InputWorkspace="_D",OutputWorkspace="_DM",StartWorkspaceIndex=MultiDetectorStart)
			RebinToWorkspace(WorkspaceToRebin="_M",WorkspaceToMatch="_DM",OutputWorkspace="_M_M")
			CropWorkspace(InputWorkspace="_M_M",OutputWorkspace="_I0M",StartWorkspaceIndex=I0MonitorIndex)
			Divide(LHSWorkspace="_DM",RHSWorkspace="_I0M",OutputWorkspace="IvsLam")
			if (roi != [0,0]) :
				SumSpectra(InputWorkspace="IvsLam",OutputWorkspace="DMR",StartWorkspaceIndex=roi[0], EndWorkspaceIndex=roi[1])
				ReflectedBeam=mtd['DMR']
			if (db != [0,0]) :
				SumSpectra(InputWorkspace="_DM",OutputWorkspace="_DMD",StartWorkspaceIndex=db[0], EndWorkspaceIndex=db[1])
				DirectBeam=mtd['_DMD']
		except SystemExit:
			print "Point-Detector only run."
		RunNumber = groupGet('IvsLam','samp','run_number')
		if (theta):
			IvsQ = l2q(mtd['DMR'], 'linear-detector', theta)
		else:
			ConvertUnits(InputWorkspace='DMR',OutputWorkspace="IvsQ",Target="MomentumTransfer")
				
	# Single Detector processing-------------------------------------------------------------
	else:
		print "This is a Point-Detector run."
		# handle transmission runs
		# process the point detector reflectivity  
		RebinToWorkspace(WorkspaceToRebin="_M",WorkspaceToMatch="_DP",OutputWorkspace="_M_P")
		CropWorkspace(InputWorkspace="_M_P",OutputWorkspace="_I0P",StartWorkspaceIndex=I0MonitorIndex,EndWorkspaceIndex=I0MonitorIndex)
		Scale("_DP","IvsLam",1)
		#Divide(LHSWorkspace="_DP",RHSWorkspace="_I0P",OutputWorkspace="IvsLam")
		#  Normalise by good frames
		GoodFrames = groupGet('IvsLam','samp','goodfrm')
		print "run frames: ", GoodFrames
		if (run=='0'):
			RunNumber = '0'
		else:
			RunNumber = groupGet('IvsLam','samp','run_number') 
		#mtd['IvsLam'].getSampleDetails().getLogData("goodfrm").value
		#Scale('IvsLam','IvsLam',GoodFrames**-1,'Multiply')
		#IvsLam = mtd['IvsLam']*GoodFrames**-1
		if (trans==''):
			#monitor2Eff('M')  # This doesn't seem to work.
			#heliumDetectorEff('DP')  # point detector  #Nor does this.
			# Multidetector   (Flood)   TODO		
			print "No transmission file. Using monitor spectrum"
			# normalise by monitor spectrum
			# RebinToWorkspace(WorkspaceToRebin="_M",WorkspaceToMatch="_DP",OutputWorkspace="_M_M")
			# CropWorkspace(InputWorkspace="M_M",OutputWorkspace="I0M",StartWorkspaceIndex=I0MonitorIndex)
			# Divide(LHSWorkspace="DM",RHSWorkspace="I0M",OutputWorkspace="RM")	
			Divide(LHSWorkspace="_DP",RHSWorkspace="_I0P",OutputWorkspace="IvsLam")
		else: # we have a transmission run
			names = mtd.getWorkspaceNames()
			if trans in names:
				Divide(LHSWorkspace="_DP",RHSWorkspace="_I0P",OutputWorkspace="IvsLam")
				RebinToWorkspace(trans,"IvsLam",trans)
				#IvsLam = mtd['IvsLam']*GoodFrames**-1
				Divide(LHSWorkspace="IvsLam",RHSWorkspace=trans,OutputWorkspace="IvsLam")
			else:
				Divide(LHSWorkspace="_DP",RHSWorkspace="_I0P",OutputWorkspace="IvsLam")
				#IvsLam = mtd['IvsLam']*GoodFrames**-1
				[I0MonitorIndex, MultiDetectorStart, nHist] = toLam(trans,'_TRANS')
				RebinToWorkspace(WorkspaceToRebin="_M_TRANS",WorkspaceToMatch="_DP_TRANS",OutputWorkspace="_M_P_TRANS")
				CropWorkspace(InputWorkspace="_M_P_TRANS",OutputWorkspace="_I0P_TRANS",StartWorkspaceIndex=I0MonitorIndex)
				Divide(LHSWorkspace="_DP_TRANS",RHSWorkspace="_I0P_TRANS",OutputWorkspace=str(trans)+"_IvsLam_TRANS")
				# Normalise TRANS run by good frames
				print str(trans)+'_IvsLam_TRANS'
				GoodFramesTr = groupGet(str(trans)+'_IvsLam_TRANS','samp','goodfrm')
				print "trans frames: ", GoodFramesTr
				#mtd['IvsLam_TRANS'].getSampleDetails().getLogData("goodfrm").value
				
				#Scale(str(trans)+'_IvsLam_TRANS',Factor=GoodFramesTr**-1,OutputWorkspace=str(trans)+'_IvsLam_TRANS')
				#got sometimes very slight binning diferences, so do this again:
				RebinToWorkspace(WorkspaceToRebin=str(trans)+'_IvsLam_TRANS',WorkspaceToMatch="IvsLam",OutputWorkspace=str(trans)+'_IvsLam_TRANS')
				Divide(LHSWorkspace="IvsLam",RHSWorkspace=str(trans)+"_IvsLam_TRANS",OutputWorkspace="IvsLam")
				# try:
					# Divide(LHSWorkspace=str(trans)+"_IvsLam",RHSWorkspace=str(trans)+"_IvsLam_TRANS",OutputWorkspace="IvsLam")
				# except:
					# try:
						# Divide(LHSWorkspace="IvsLam_1",RHSWorkspace=str(trans)+"_IvsLam_TRANS_1",OutputWorkspace="IvsLam_1")
						# print 'Handling run-time error: possibly empty periods...'
					# except:
						# print 'Handling run-time error: possibly empty periods...'
			   

		# Need to process the optional args to see what needs to be output and what division needs to be made
		
		# Convert to I vs Q
		# check if detector in direct beam
		if (theta == 0 or theta == ''):
			if (theta == ''):
				theta = 0
			print "given theta = ",theta
			inst = groupGet('IvsLam','inst')
			detLocation=inst.getComponentByName('point-detector').getPos()
			sampleLocation=inst.getComponentByName('some-surface-holder').getPos()
			detLocation=inst.getComponentByName('point-detector').getPos()
			sample2detector=detLocation-sampleLocation    # meters
			source=inst.getSource()
			beamPos = sampleLocation - source.getPos()
			PI = 3.1415926535
			theta = inst.getComponentByName('point-detector').getTwoTheta(sampleLocation, beamPos)*180.0/PI
			print "Det location: ", detLocation, "Calculated theta = ",theta
			if detLocation.getY() == 0:  # detector is not in correct place
				print "det at 0"
				# Load corresponding NeXuS file
				runno = '_' + str(run)
				#templist.append(runno)
				if type(run)==type(int()):
					LoadNexus(Filename=run,OutputWorkspace=runno)
				else:
					LoadNexus(Filename=run.replace("raw","nxs",1),OutputWorkspace=runno)
				# Get detector angle theta from NeXuS
				theta = groupGet(runno,'samp','theta')
				print 'Nexus file theta =', theta
				IvsQ = l2q(IvsLam, 'point-detector', theta)
			else:
				ConvertUnits(InputWorkspace='IvsLam',OutputWorkspace="IvsQ",Target="MomentumTransfer",AlignBins="1")
			
		else:
			theta = float(theta)
			IvsQ = l2q(mtd['IvsLam'], 'point-detector', theta)		
	
	RenameWorkspace('IvsLam',RunNumber+'_IvsLam')
	RenameWorkspace('IvsQ',RunNumber+'_IvsQ')
		
	# delete all temporary workspaces unless in debug mode (debug=1)
    
	if debug == 0:
		cleanup()
	return  mtd[RunNumber+'_IvsLam'], mtd[RunNumber+'_IvsQ'], theta