def test_crop_range(self):
        original_ws = Load(Filename='INTER00013460')

        # Crop out one spectra
        temp_ws = ConvertToWavelength.crop_range(original_ws, (0, original_ws.getNumberHistograms()-2))
        self.assertEqual(original_ws.getNumberHistograms()-1, temp_ws.getNumberHistograms())

        # Crop out all but 2 spectra from start and end.
        temp_ws = ConvertToWavelength.crop_range(original_ws, ( (0, 1), (3, 4) ) )
        self.assertEqual(2, temp_ws.getNumberHistograms())

        # Crop out all but 2 spectra from start and end. Exactly the same as above, but slightly different tuple syntax
        temp_ws = ConvertToWavelength.crop_range(original_ws, ( ( (0, 1), (3, 4) ) ))
        self.assertEqual(2, temp_ws.getNumberHistograms())

        # Crop out all but 1 spectra
        temp_ws = ConvertToWavelength.crop_range(original_ws, ( (1, 3) ) )
        self.assertEqual(3, temp_ws.getNumberHistograms())
        # First and last dectors are cropped off, so indexes go 2-4 rather than 1-5
        self.assertEqual(2, temp_ws.getDetector(0).getID())
        self.assertEqual(3, temp_ws.getDetector(1).getID())
        self.assertEqual(4, temp_ws.getDetector(2).getID())

        # Test resilience to junk inputs
        self.assertRaises(ValueError, ConvertToWavelength.crop_range, original_ws, 'a')
        self.assertRaises(ValueError, ConvertToWavelength.crop_range, original_ws, (1,2,3))
示例#2
0
    def test_convert(self):
        ws = Load(Filename='INTER00013460')
        converter = ConvertToWavelength(ws)

        monitor_ws, detector_ws = converter.convert(
            wavelength_min=0.0,
            wavelength_max=10.0,
            detector_workspace_indexes=(2, 4),
            monitor_workspace_index=0,
            correct_monitor=True,
            bg_min=2.0,
            bg_max=8.0)

        self.assertEqual(1, monitor_ws.getNumberHistograms(),
                         "Wrong number of spectra in monitor workspace")
        self.assertEqual(3, detector_ws.getNumberHistograms(),
                         "Wrong number of spectra in detector workspace")
        self.assertEqual("Wavelength",
                         detector_ws.getAxis(0).getUnit().unitID())
        self.assertEqual("Wavelength",
                         monitor_ws.getAxis(0).getUnit().unitID())
        x_min, x_max = ConvertToWavelengthTest.cropped_x_range(detector_ws, 0)

        self.assertTrue(x_min >= 0.0)
        self.assertTrue(x_max <= 10.0)
示例#3
0
    def test_crop_range(self):
        original_ws = Load(Filename='INTER00013460')

        # Crop out one spectra
        temp_ws = ConvertToWavelength.crop_range(original_ws, (0, original_ws.getNumberHistograms()-2))
        self.assertEqual(original_ws.getNumberHistograms()-1, temp_ws.getNumberHistograms())

        # Crop out all but 2 spectra from start and end.
        temp_ws = ConvertToWavelength.crop_range(original_ws, ( (0, 1), (3, 4) ) )
        self.assertEqual(2, temp_ws.getNumberHistograms())

        # Crop out all but 2 spectra from start and end. Exactly the same as above, but slightly different tuple syntax
        temp_ws = ConvertToWavelength.crop_range(original_ws, ( ( (0, 1), (3, 4) ) ))
        self.assertEqual(2, temp_ws.getNumberHistograms())

        # Crop out all but 1 spectra
        temp_ws = ConvertToWavelength.crop_range(original_ws, ( (1, 3) ) )
        self.assertEqual(3, temp_ws.getNumberHistograms())
        # First and last dectors are cropped off, so indexes go 2-4 rather than 1-5
        self.assertEqual(2, temp_ws.getDetector(0).getID())
        self.assertEqual(3, temp_ws.getDetector(1).getID())
        self.assertEqual(4, temp_ws.getDetector(2).getID())

        # Test resilience to junk inputs
        self.assertRaises(ValueError, ConvertToWavelength.crop_range, original_ws, 'a')
        self.assertRaises(ValueError, ConvertToWavelength.crop_range, original_ws, (1,2,3))
    def test_convert(self):
        ws = Load(Filename='INTER00013460')
        converter = ConvertToWavelength(ws)

        monitor_ws, detector_ws = converter.convert(wavelength_min=0.0, wavelength_max=10.0, detector_workspace_indexes = (2,4), monitor_workspace_index=0, correct_monitor=True, bg_min=2.0, bg_max=8.0)

        self.assertEqual(1, monitor_ws.getNumberHistograms(), "Wrong number of spectra in monitor workspace")
        self.assertEqual(3, detector_ws.getNumberHistograms(), "Wrong number of spectra in detector workspace")
        self.assertEqual("Wavelength", detector_ws.getAxis(0).getUnit().unitID())
        self.assertEqual("Wavelength", monitor_ws.getAxis(0).getUnit().unitID())
        x_min, x_max = ConvertToWavelengthTest.cropped_x_range(detector_ws, 0)

        self.assertTrue(x_min >= 0.0)
        self.assertTrue(x_max <= 10.0)
    def test_construction_from_single_ws_name(self):
        ws = CreateWorkspace(DataY=[1, 2, 3], DataX=[1, 2, 3])

        converter = ConvertToWavelength(ws.name())
        self.assertNotEqual(converter, None,
                            "Should have been able to make a valid converter from a single workspace name")
        DeleteWorkspace(ws)
示例#6
0
 def test_conversion_throws_with_min_wavelength_greater_or_equal_to_max_wavelength(
         self):
     ws = CreateWorkspace(DataY=[1, 2, 3], DataX=[1, 2, 3])
     converter = ConvertToWavelength(ws)
     self.assertRaises(ValueError, converter.convert, 1.0, 0.0, (), 0)
     self.assertRaises(ValueError, converter.convert, 1.0, 1.0, (), 0)
     DeleteWorkspace(ws)
示例#7
0
 def test_construction_from_many_workspace_names(self):
     ws1 = CreateWorkspace(DataY=[1,2,3], DataX=[1,2,3])
     ws2 = CreateWorkspace(DataY=[1,2,3], DataX=[1,2,3])
     converter = ConvertToWavelength([ws1.name(), ws2.name()])
     self.assertNotEqual(converter,  None, "Should have been able to make a valid converter from many workspace objects")
     DeleteWorkspace(ws1)
     DeleteWorkspace(ws2)
示例#8
0
 def test_construction_from_semicolon_separated_workspaces(self):
     ws1 = CreateWorkspace(DataY=[1,2,3], DataX=[1,2,3])
     ws2 = CreateWorkspace(DataY=[1,2,3], DataX=[1,2,3])
     colon_separated_names = "%s: %s" % (ws1.name(), ws2.name())
     converter = ConvertToWavelength(colon_separated_names)
     self.assertNotEqual(converter,  None, "Should have been able to make a valid converter from many : separated workspace objects")
     DeleteWorkspace(ws1)
     DeleteWorkspace(ws2)
示例#9
0
 def test_construction_from_single_ws(self):
     ws = CreateWorkspace(DataY=[1, 2, 3], DataX=[1, 2, 3])
     converter = ConvertToWavelength(ws)
     self.assertTrue(
         converter != None,
         "Should have been able to make a valid converter from a single workspace"
     )
     DeleteWorkspace(ws)
示例#10
0
 def test_sum_workspaces(self):
     ws1 = CreateWorkspace(DataY=[1,2,3], DataX=[1,2,3])
     ws2 = CloneWorkspace(ws1)
     ws3 = CloneWorkspace(ws1)
     sum = ConvertToWavelength.sum_workspaces([ws1, ws2, ws3])
     self.assertEqual(set([3,6,9]), set(sum.readY(0)), "Fail to sum workspaces correctly")
     DeleteWorkspace(ws1)
     DeleteWorkspace(ws2)
     DeleteWorkspace(ws3)
     DeleteWorkspace(sum)
 def test_sum_workspaces(self):
     ws1 = CreateWorkspace(DataY=[1,2,3], DataX=[1,2,3])
     ws2 = CloneWorkspace(ws1)
     ws3 = CloneWorkspace(ws1)
     sum = ConvertToWavelength.sum_workspaces([ws1, ws2, ws3])
     self.assertEqual(set([3,6,9]), set(sum.readY(0)), "Fail to sum workspaces correctly")
     DeleteWorkspace(ws1)
     DeleteWorkspace(ws2)
     DeleteWorkspace(ws3)
     DeleteWorkspace(sum)
示例#12
0
 def test_construction_from_comma_separated_workspaces(self):
     ws1 = CreateWorkspace(DataY=[1, 2, 3], DataX=[1, 2, 3])
     ws2 = CreateWorkspace(DataY=[1, 2, 3], DataX=[1, 2, 3])
     comma_separated_names = "%s, %s" % (ws1.getName(), ws2.getName())
     converter = ConvertToWavelength(comma_separated_names)
     self.assertTrue(
         converter != None,
         "Should have been able to make a valid converter from many , separated workspace objects"
     )
     DeleteWorkspace(ws1)
     DeleteWorkspace(ws2)
示例#13
0
文件: quick.py 项目: mcvine/mantid
def quick(run, theta=None, pointdet=True, roi=[0, 0], db=[0, 0], trans='', polcorr=False, usemon=-1, outputType='pd',
          debug=False, stitch_start_overlap=10, stitch_end_overlap=12, stitch_params=[1.5, 0.02, 17],
          detector_component_name='point-detector', sample_component_name='some-surface-holder',
          correct_positions=True, tof_prefix="_"):
    '''
    Original quick parameters fetched from IDF
    '''
    run_ws = ConvertToWavelength.to_workspace(run, ws_prefix=tof_prefix)
    idf_defaults = get_defaults(run_ws, polcorr)

    i0_monitor_index = idf_defaults['I0MonitorIndex']
    multi_detector_start = idf_defaults['MultiDetectorStart']
    lambda_min = idf_defaults['LambdaMin']
    lambda_max = idf_defaults['LambdaMax']
    point_detector_start = idf_defaults['PointDetectorStart']
    point_detector_stop = idf_defaults['PointDetectorStop']
    multi_detector_start = idf_defaults['MultiDetectorStart']
    background_min = idf_defaults['MonitorBackgroundMin']
    background_max = idf_defaults['MonitorBackgroundMax']
    int_min = idf_defaults['MonitorIntegralMin']
    int_max = idf_defaults['MonitorIntegralMax']
    correction_strategy = idf_defaults['AlgoritmicCorrection']
    crho = None
    calpha = None
    cAp = None
    cPp = None
    if polcorr and (polcorr != PolarisationCorrection.NONE):
        crho = idf_defaults['crho']
        calpha = idf_defaults['calpha']
        cAp = idf_defaults['cAp']
        cPp = idf_defaults['cPp']

    return quick_explicit(run=run, i0_monitor_index=i0_monitor_index, lambda_min=lambda_min, lambda_max=lambda_max, \
                          point_detector_start=point_detector_start, point_detector_stop=point_detector_stop, \
                          multi_detector_start=multi_detector_start, background_min=background_min,
                          background_max=background_max, \
                          int_min=int_min, int_max=int_max, theta=theta, pointdet=pointdet, roi=roi, db=db, trans=trans, \
                          debug=debug, correction_strategy=correction_strategy,
                          stitch_start_overlap=stitch_start_overlap, \
                          stitch_end_overlap=stitch_end_overlap, stitch_params=stitch_params, polcorr=polcorr,
                          crho=crho, calpha=calpha, cAp=cAp, cPp=cPp, \
                          detector_component_name=detector_component_name, sample_component_name=sample_component_name,
                          correct_positions=correct_positions)
示例#14
0
def quick(run, theta=None, pointdet=True, roi=[0, 0], db=[0, 0], trans='', polcorr=False, usemon=-1, outputType='pd',
          debug=False, stitch_start_overlap=10, stitch_end_overlap=12, stitch_params=[1.5, 0.02, 17],
          detector_component_name='point-detector', sample_component_name='some-surface-holder',
          correct_positions=True, tof_prefix="_"):
    '''
    Original quick parameters fetched from IDF
    '''
    run_ws = ConvertToWavelength.to_workspace(run, ws_prefix=tof_prefix)
    idf_defaults = get_defaults(run_ws, polcorr)

    i0_monitor_index = idf_defaults['I0MonitorIndex']
    multi_detector_start = idf_defaults['MultiDetectorStart']
    lambda_min = idf_defaults['LambdaMin']
    lambda_max = idf_defaults['LambdaMax']
    point_detector_start = idf_defaults['PointDetectorStart']
    point_detector_stop = idf_defaults['PointDetectorStop']
    multi_detector_start = idf_defaults['MultiDetectorStart']
    background_min = idf_defaults['MonitorBackgroundMin']
    background_max = idf_defaults['MonitorBackgroundMax']
    int_min = idf_defaults['MonitorIntegralMin']
    int_max = idf_defaults['MonitorIntegralMax']
    correction_strategy = idf_defaults['AlgoritmicCorrection']
    crho = None
    calpha = None
    cAp = None
    cPp = None
    if polcorr and (polcorr != PolarisationCorrection.NONE):
        crho = idf_defaults['crho']
        calpha = idf_defaults['calpha']
        cAp = idf_defaults['cAp']
        cPp = idf_defaults['cPp']

    return quick_explicit(run=run, i0_monitor_index=i0_monitor_index, lambda_min=lambda_min, lambda_max=lambda_max,
                          point_detector_start=point_detector_start, point_detector_stop=point_detector_stop,
                          multi_detector_start=multi_detector_start, background_min=background_min,
                          background_max=background_max,
                          int_min=int_min, int_max=int_max, theta=theta, pointdet=pointdet, roi=roi, db=db, trans=trans,
                          debug=debug, correction_strategy=correction_strategy,
                          stitch_start_overlap=stitch_start_overlap,
                          stitch_end_overlap=stitch_end_overlap, stitch_params=stitch_params, polcorr=polcorr,
                          crho=crho, calpha=calpha, cAp=cAp, cPp=cPp,
                          detector_component_name=detector_component_name, sample_component_name=sample_component_name,
                          correct_positions=correct_positions)
示例#15
0
 def test_conversion_throws_with_some_flat_background_params_but_not_all(self):
     ws = CreateWorkspace(DataY=[1,2,3], DataX=[1,2,3])
     converter = ConvertToWavelength(ws)
     self.assertRaises(ValueError, converter.convert, 0.0, 1.0, (), 0, True)
     DeleteWorkspace(ws)
示例#16
0
def make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_params,
                    lambda_min=None, lambda_max=None, background_min=None,
                    background_max=None, int_min=None, int_max=None, detector_index_ranges=None,
                    i0_monitor_index=None):
    '''
    Make the transmission correction workspace.
    '''


    # Check to see whether all optional inputs have been provide. If not we have to get them from the IDF.
    if not all((lambda_min, lambda_max, background_min, background_max, int_min, int_max, detector_index_ranges, i0_monitor_index)):
        logger.notice("make_trans_corr: Fetching missing arguments from the IDF")
        instrument_source = transrun
        if isinstance(transrun, str):
            instrument_source = transrun.split(',')[0]
        trans_ws = ConvertToWavelength.to_workspace(instrument_source)
        idf_defaults = get_defaults(trans_ws)

        # Fetch defaults for anything not specified
        if not i0_monitor_index:
            i0_monitor_index = idf_defaults['I0MonitorIndex']
        if not lambda_min:
            lambda_min = idf_defaults['LambdaMin']
        if not lambda_max:
            lambda_max = idf_defaults['LambdaMax']
        if not detector_index_ranges:
            point_detector_start = idf_defaults['PointDetectorStart']
            point_detector_stop =  idf_defaults['PointDetectorStop']
            detector_index_ranges = (point_detector_start, point_detector_stop)
        if not background_min:
            background_min = idf_defaults['MonitorBackgroundMin']
        if not background_max:
            background_max = idf_defaults['MonitorBackgroundMax']
        if not int_min:
            int_min = idf_defaults['MonitorIntegralMin']
        if not int_max:
            int_max = idf_defaults['MonitorIntegralMax']


    transWS = None
    if isinstance(transrun, str) and (',' in transrun):
        slam = transrun.split(',')[0]
        llam = transrun.split(',')[1]
        print "Transmission runs: ", transrun

        to_lam = ConvertToWavelength(slam)
        _monitor_ws_slam, _detector_ws_slam = 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 )

        _i0p_slam = RebinToWorkspace(WorkspaceToRebin=_monitor_ws_slam, WorkspaceToMatch=_detector_ws_slam)
        _mon_int_trans = Integration(InputWorkspace=_i0p_slam, RangeLower=int_min, RangeUpper=int_max)
        _detector_ws_slam = Divide(LHSWorkspace=_detector_ws_slam, RHSWorkspace=_mon_int_trans)

        to_lam = ConvertToWavelength(llam)
        _monitor_ws_llam, _detector_ws_llam = 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 )

        _i0p_llam = RebinToWorkspace(WorkspaceToRebin=_monitor_ws_llam, WorkspaceToMatch=_detector_ws_llam)
        _mon_int_trans = Integration(InputWorkspace=_i0p_llam, RangeLower=int_min,RangeUpper=int_max)
        _detector_ws_llam = Divide(LHSWorkspace=_detector_ws_llam, RHSWorkspace=_mon_int_trans)

        print stitch_start_overlap, stitch_end_overlap, stitch_params
        transWS, outputScaling = Stitch1D(LHSWorkspace=_detector_ws_slam, RHSWorkspace=_detector_ws_llam, StartOverlap=stitch_start_overlap,\
                                           EndOverlap=stitch_end_overlap,  Params=stitch_params)

        transWS = RenameWorkspace(InputWorkspace=transWS, OutputWorkspace="TRANS_" + slam + "_" + llam)
    else:

        to_lam = ConvertToWavelength(transrun)
        _monitor_ws_trans, _detector_ws_trans = 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 )
        _i0p_trans = RebinToWorkspace(WorkspaceToRebin=_monitor_ws_trans, WorkspaceToMatch=_detector_ws_trans)

        _mon_int_trans = Integration( InputWorkspace=_i0p_trans, RangeLower=int_min, RangeUpper=int_max )
        transWS = Divide( LHSWorkspace=_detector_ws_trans, RHSWorkspace=_mon_int_trans )

        transWS = RenameWorkspace(InputWorkspace=transWS, OutputWorkspace="TRANS_" + transrun)
    return transWS
示例#17
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()
            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
def autoreduce(RBno,cycle, transRun=[], runRange=[], oldList=[], auto=0, angles=[], diagnostics=False):
    if not runRange:
        rlist = INTERsearch(RBno, cycle, diagnostics=diagnostics) 
    else:
        rlist = INTERsearch(RBno, cycle, runRange, diagnostics=diagnostics) 
    tupsort = make_tuples(rlist)
    sortedList = sort_runs(tupsort)
    
    newList = [item for item in sortedList if item not in oldList]
    
    for sample in newList:
        wq_list=[]
        overlapLow=[]
        overlapHigh=[]
        index=0
        for item in sample:
            runno = item[0]
            angle = item[1]
            runnos=string.split(runno,'+')
            runnos = [int(i) for i in runnos] # check if runs have been added together
            
            try:
                angle=float(angle)
            except ValueError:
                angle=0.0
                print "Could not determine theta! Skipping run."
                        
            if len(runRange) and not len(set(runRange) & set(runnos)):
                angle=0.0 # will be skipped below
            
            if float(angle)>0.0:
                ws = ConvertToWavelength.to_workspace(runno+'.raw', ws_prefix="")
                if not mtd.doesExist(runno+'_IvsQ'):
                    th = angle
                    #if len(transRun)>1 and index>0:
                    if len(transRun)>1:
                        if not angles:
                            angle=angle
                        else:
							try:
								angle=angles[index]
							except:
								print("Not enough angles specified.")
							#angle=angles[1]
                        try:
							transmRun=transRun[index]
							cutoff = INTERexptype()[index]
							print(cutoff,"=cutoff")
							ReflectometryReductionOneAuto(InputWorkspace=ws, FirstTransmissionRun=transmRun, WavelengthMin=cutoff, thetaIn=angle, OutputWorkspaceBinned=runno+'_IvsQ_binned', OutputWorkspace=runno+'_IvsQ', OutputWorkspaceWavelength=runno+'_IvsLam')
							wq=mtd[runno+'_IvsQ']
							th = angle
                        except:
                            print("Not enough transmission runs specified or transmission workspace doesn't exist, for run "+str(ws))
                    else:
                        if not angles:
                            angle=angle
                        #else:
                            #angle=angles[0]
                        #cutoff = INTERexptype()
                        cutoff = INTERexptype()[index]
                        print(cutoff,"=cutoff")
                        ReflectometryReductionOneAuto(InputWorkspace=ws, FirstTransmissionRun=transRun[0], thetaIn=angle, WavelengthMin=cutoff, OutputWorkspaceBinned=runno+'_IvsQ_binned', OutputWorkspace=runno+'_IvsQ', OutputWorkspaceWavelength=runno+'_IvsLam') 
                        wq=mtd[runno+'_IvsQ']
                        th = angle
                else:
                    wq=mtd[runno+'_IvsQ']
                    th=angle
                wq_list.append(runno+'_IvsQ')
                inst = wq.getInstrument()
                lmin = 1.8 #inst.getNumberParameter('LambdaMin')[0] + 1
                lmax = 15 #inst.getNumberParameter('LambdaMax')[0] - 2
                qmin = 4 * math.pi / lmax * math.sin(th * math.pi / 180)
                qmax = 4 * math.pi / lmin * math.sin(th * math.pi / 180)
                overlapLow.append(qmin)
                overlapHigh.append(qmax)
                dqq = NRCalculateSlitResolution(Workspace=wq)
            index=index+1
        if len(wq_list):
            w1 = getWorkspace(wq_list[0])
            w2 = getWorkspace(wq_list[-1])
            Qmin = min(w1.readX(0))
            Qmax = max(w2.readX(0))
            Qmax = 0.3

               
            #print Qmin, Qmax, dqq 
            #print overlapHigh
            if len(wq_list)>1:
                outputwksp = string.split(wq_list[0],sep='_')[0] + '_' + string.split(wq_list[-1],sep='_')[0][3:]
            else:
                outputwksp = string.split(wq_list[0],sep='_')[0] + '_IvsQ_binned'
                SaveAscii(InputWorkspace=outputwksp,Filename=savepath+outputwksp+'.dat',Separator='Space',ColumnHeader=False,ScientificFormat=True,WriteSpectrumID=False)      
            if not mtd.doesExist(outputwksp):
                wcomb = combineDataMulti(wq_list,outputwksp , overlapLow, overlapHigh,Qmin, Qmax, -dqq, 0, keep=True)
                SaveAscii(InputWorkspace=outputwksp,Filename=savepath+outputwksp+'.dat',Separator='Space',ColumnHeader=False,ScientificFormat=True,WriteSpectrumID=False)
            
    return sortedList
示例#19
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.name(), '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)

            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 is 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()
            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
示例#20
0
def make_trans_corr(transrun,
                    stitch_start_overlap,
                    stitch_end_overlap,
                    stitch_params,
                    lambda_min=None,
                    lambda_max=None,
                    background_min=None,
                    background_max=None,
                    int_min=None,
                    int_max=None,
                    detector_index_ranges=None,
                    i0_monitor_index=None):
    '''
    Make the transmission correction workspace.
    '''

    # Check to see whether all optional inputs have been provide. If not we have to get them from the IDF.
    if not all((lambda_min, lambda_max, background_min, background_max,
                int_min, int_max, detector_index_ranges, i0_monitor_index)):
        logger.notice(
            "make_trans_corr: Fetching missing arguments from the IDF")
        instrument_source = transrun
        if isinstance(transrun, str):
            instrument_source = transrun.split(',')[0]
        trans_ws = ConvertToWavelength.to_workspace(instrument_source)
        idf_defaults = get_defaults(trans_ws)

        # Fetch defaults for anything not specified
        if not i0_monitor_index:
            i0_monitor_index = idf_defaults['I0MonitorIndex']
        if not lambda_min:
            lambda_min = idf_defaults['LambdaMin']
        if not lambda_max:
            lambda_max = idf_defaults['LambdaMax']
        if not detector_index_ranges:
            point_detector_start = idf_defaults['PointDetectorStart']
            point_detector_stop = idf_defaults['PointDetectorStop']
            detector_index_ranges = (point_detector_start, point_detector_stop)
        if not background_min:
            background_min = idf_defaults['MonitorBackgroundMin']
        if not background_max:
            background_max = idf_defaults['MonitorBackgroundMax']
        if not int_min:
            int_min = idf_defaults['MonitorIntegralMin']
        if not int_max:
            int_max = idf_defaults['MonitorIntegralMax']

    transWS = None
    if isinstance(transrun, str) and (',' in transrun):
        slam = transrun.split(',')[0]
        llam = transrun.split(',')[1]
        print("Transmission runs: ", transrun)

        to_lam = ConvertToWavelength(slam)
        _monitor_ws_slam, _detector_ws_slam = 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)

        _i0p_slam = RebinToWorkspace(WorkspaceToRebin=_monitor_ws_slam,
                                     WorkspaceToMatch=_detector_ws_slam)
        _mon_int_trans = Integration(InputWorkspace=_i0p_slam,
                                     RangeLower=int_min,
                                     RangeUpper=int_max)
        _detector_ws_slam = Divide(LHSWorkspace=_detector_ws_slam,
                                   RHSWorkspace=_mon_int_trans)

        to_lam = ConvertToWavelength(llam)
        _monitor_ws_llam, _detector_ws_llam = 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)

        _i0p_llam = RebinToWorkspace(WorkspaceToRebin=_monitor_ws_llam,
                                     WorkspaceToMatch=_detector_ws_llam)
        _mon_int_trans = Integration(InputWorkspace=_i0p_llam,
                                     RangeLower=int_min,
                                     RangeUpper=int_max)
        _detector_ws_llam = Divide(LHSWorkspace=_detector_ws_llam,
                                   RHSWorkspace=_mon_int_trans)

        print(stitch_start_overlap, stitch_end_overlap, stitch_params)
        transWS, _outputScaling = Stitch1D(LHSWorkspace=_detector_ws_slam,
                                           RHSWorkspace=_detector_ws_llam,
                                           StartOverlap=stitch_start_overlap,
                                           EndOverlap=stitch_end_overlap,
                                           Params=stitch_params)

        transWS = RenameWorkspace(InputWorkspace=transWS,
                                  OutputWorkspace="TRANS_" + slam + "_" + llam)
    else:

        to_lam = ConvertToWavelength(transrun)
        _monitor_ws_trans, _detector_ws_trans = 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)
        _i0p_trans = RebinToWorkspace(WorkspaceToRebin=_monitor_ws_trans,
                                      WorkspaceToMatch=_detector_ws_trans)

        _mon_int_trans = Integration(InputWorkspace=_i0p_trans,
                                     RangeLower=int_min,
                                     RangeUpper=int_max)
        transWS = Divide(LHSWorkspace=_detector_ws_trans,
                         RHSWorkspace=_mon_int_trans)

        transWS = RenameWorkspace(InputWorkspace=transWS,
                                  OutputWorkspace="TRANS_" + transrun)
    return transWS