def test_minimal_inputs(self):

        in_ws = Load('INTER00013460.nxs', OutputWorkspace="13460")
        trans1 = Load('INTER00013463.nxs', OutputWorkspace="trans1")
        
        inst = trans1.getInstrument()
        
        out_ws, out_wsl_lam, thetafinal = ReflectometryReductionOneAuto(InputWorkspace=in_ws, AnalysisMode="PointDetectorAnalysis"
                                                                        ,OutputWorkspace="InQ", OutputWorkspaceWavelength="InLam")
        history = out_ws.getHistory()
        alg = history.lastAlgorithm()
        
        '''
        Here we are checking that the applied values (passed to CreateTransmissionWorkspace come from the instrument parameters.
        '''
        self.assertEqual(inst.getNumberParameter("LambdaMin")[0], alg.getProperty("WavelengthMin").value)
        self.assertEqual(inst.getNumberParameter("LambdaMax")[0], alg.getProperty("WavelengthMax").value)
        self.assertEqual(inst.getNumberParameter("MonitorBackgroundMin")[0], alg.getProperty("MonitorBackgroundWavelengthMin").value)
        self.assertEqual(inst.getNumberParameter("MonitorBackgroundMax")[0], alg.getProperty("MonitorBackgroundWavelengthMax").value)
        self.assertEqual(inst.getNumberParameter("MonitorIntegralMin")[0], alg.getProperty("MonitorIntegrationWavelengthMin").value)
        self.assertEqual(inst.getNumberParameter("MonitorIntegralMax")[0], alg.getProperty("MonitorIntegrationWavelengthMax").value)
        self.assertEqual(inst.getNumberParameter("I0MonitorIndex")[0], alg.getProperty("I0MonitorIndex").value)
        self.assertEqual(inst.getNumberParameter("PointDetectorStart")[0], float(alg.getProperty("ProcessingInstructions").value.split(',')[0]))
        self.assertEqual(inst.getNumberParameter("PointDetectorStop")[0], float(alg.getProperty("ProcessingInstructions").value.split(',')[1]))
    
        DeleteWorkspace(in_ws)
        DeleteWorkspace(trans1)
示例#2
0
    def test_plus_operator_sums_multiple_set_files_to_give_group(self):
        summed_data = Load("TSC15352+15353.raw,TSC15352+15354.raw", OutputWorkspace=self.wsname)

        self.assertTrue(isinstance(summed_data, WorkspaceGroup))
        self.assertEquals(2, summed_data.getNumberOfEntries())

        # First group
        data = summed_data[0]
        self.assertEquals(149, data.getNumberHistograms())
        self.assertEquals(24974, data.blocksize())

        self.assertAlmostEqual(9.0, data.readX(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(46352.0, data.readY(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(215.29514625276622, data.readE(2)[1], places=DIFF_PLACES)

        # Second group
        data = summed_data[1]
        self.assertEquals(149, data.getNumberHistograms())
        self.assertEquals(24974, data.blocksize())

        self.assertAlmostEqual(9.0, data.readX(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(35640.0, data.readY(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(188.78559267062727, data.readE(2)[1], places=DIFF_PLACES)

        deleted_names = ["TSC15352", "TSC15353", "TSC15354"]
        for name in deleted_names:
            self.assertTrue(name not in AnalysisDataService)
def beam_center_gravitational_drop(beam_center_file, sdd=1.13):
    '''
    This method is used for correcting for gravitational drop
    @param beam_center_file :: file where the beam center was found
    @param sdd :: sample detector distance to apply the beam center
    '''
    def calculate_neutron_drop(path_length, wavelength):
        '''
        Calculate the gravitational drop of the neutrons
        path_length in meters
        wavelength in Angstrom
        '''
        wavelength *= 1e-10
        neutron_mass = 1.674927211e-27
        gravity = 9.80665
        h_planck = 6.62606896e-34
        l_2 = (gravity * neutron_mass**2 / (2.0 * h_planck**2 )) * path_length**2
        return wavelength**2 * l_2

    # Get beam center used in the previous reduction
    pm = mantid.PropertyManagerDataService[ReductionSingleton().property_manager]
    beam_center_x = pm['LatestBeamCenterX'].value
    beam_center_y = pm['LatestBeamCenterY'].value
    Logger("CommandInterface").information("Beam Center before: [%.2f, %.2f] pixels" % (beam_center_x, beam_center_y))

    try:
        # check if the workspace still exists
        wsname = "__beam_finder_" + os.path.splitext(beam_center_file)[0]
        ws = mantid.mtd[wsname]
        Logger("CommandInterface").debug("Using Workspace: %s." % (wsname))
    except KeyError:
        # Let's try loading the file. For some reason the beamcenter ws is not there...
        try:
            ws = Load(beam_center_file)
            Logger("CommandInterface").debug("Using filename %s." % (beam_center_file))
        except IOError:
            Logger("CommandInterface").error("Cannot read input file %s." % beam_center_file)
            return

    i = ws.getInstrument()
    y_pixel_size_mm = i.getNumberParameter('y-pixel-size')[0]
    Logger("CommandInterface").debug("Y Pixel size = %.2f mm" % y_pixel_size_mm)
    y_pixel_size = y_pixel_size_mm * 1e-3  # In meters
    distance_detector1 = i.getComponentByName("detector1").getPos()[2]
    path_length = distance_detector1 - sdd
    Logger("CommandInterface").debug("SDD detector1 = %.3f meters. SDD for wing = %.3f meters." % (distance_detector1, sdd))
    Logger("CommandInterface").debug("Path length for gravitational drop = %.3f meters." % (path_length))
    r = ws.run()
    wavelength = r.getProperty("wavelength").value
    Logger("CommandInterface").debug("Wavelength = %.2f A." % (wavelength))

    drop = calculate_neutron_drop(path_length, wavelength)
    Logger("CommandInterface").debug("Gravitational drop = %.6f meters." % (drop))
    # 1 pixel -> y_pixel_size
    # x pixel -> drop
    drop_in_pixels = drop / y_pixel_size
    new_beam_center_y = beam_center_y + drop_in_pixels
    Logger("CommandInterface").information("Beam Center after:   [%.2f, %.2f] pixels" % (beam_center_x, new_beam_center_y))
    return beam_center_x, new_beam_center_y
示例#4
0
 def test_Load_call_with_args_that_do_not_apply_executes_correctly(self):
     try:
         raw = Load('IRS21360.raw', SpectrumMax=1, Append=True)
     except RuntimeError:
         self.fail(
             "Load with a filename and extra args should not raise an exception"
         )
     self.assertEquals(1, raw.getNumberHistograms())
 def do_reduction(calibration):
     # load data
     data = Load("HRP39180.RAW")
     # copy parameters from calibration to data
     CopyInstrumentParameters(calibration, data)
     # Now move component on data workspace using a relative move, where that component was a detector in the calibrated workspace
     MoveInstrumentComponent(data, DetectorID=1100,X=0.0,Y=0.0,Z=5.0,RelativePosition=True)
     return data.getDetector(0).getPos()
示例#6
0
    def _create_experimental_data_workspace(self):
        """
        Loads experimental data into workspaces.
        :returns: workspace with experimental data
        """
        experimental_wrk = Load(self._experimental_file)
        self._set_workspace_units(wrk=experimental_wrk.name())

        return experimental_wrk
示例#7
0
    def test_extra_properties_passed_to_loader_for_multiple_files(self):
        data = Load("EQSANS_1466_event.nxs,EQSANS_3293_event.nxs", OutputWorkspace = self.wsname,
                    BankName = "bank1", SingleBankPixelsOnly = False)

        self.assertTrue(isinstance(data, WorkspaceGroup))
        self.assertEquals(2, data.getNumberOfEntries())
        # Test number of events in each
        self.assertEquals(740, data[0].getNumberEvents())
        self.assertEquals(105666, data[1].getNumberEvents())
示例#8
0
  def PyExec(self):
      filename = self.getProperty("Filename").value
      from mantid.simpleapi import Load
 
      # lifted from script
      _tmp = Load(Filename=filename)
      _tmp = _tmp.convertUnits(_tmp,Target="Energy")
 
      self.setProperty("OutputWorkspace",_tmp)
      _tmp.delete() # Remove temporary reference from MantidPlot view
示例#9
0
    def test_stepped_range_operator_loads_correct_number_of_files(self):
        data = Load("TSC15352:15354:2.raw", OutputWorkspace=self.wsname)

        self.assertTrue(isinstance(data, WorkspaceGroup))
        self.assertEquals(2, data.getNumberOfEntries())

        self.assertTrue(isinstance(data[0], MatrixWorkspace))
        self.assertTrue(isinstance(data[1], MatrixWorkspace))

        # Cursory check that the correct ones were loaded
        self.assertTrue("TO96_2" in data[0].getTitle())
        self.assertTrue("TO96_4" in data[1].getTitle())
示例#10
0
 def load_file_and_apply(self, filename, ws_name):
     Load(Filename=filename,
          OutputWorkspace=ws_name,
          FilterByTofMin=self.getProperty("FilterByTofMin").value,
          FilterByTofMax=self.getProperty("FilterByTofMax").value)
     if self._load_inst:
         LoadInstrument(Workspace=ws_name,
                        Filename=self.getProperty("LoadInstrument").value,
                        RewriteSpectraMap=False)
     if self._apply_cal:
         ApplyCalibration(
             Workspace=ws_name,
             CalibrationTable=self.getProperty("ApplyCalibration").value)
     if self._detcal:
         LoadIsawDetCal(InputWorkspace=ws_name,
                        Filename=self.getProperty("DetCal").value)
     if self._copy_params:
         CopyInstrumentParameters(OutputWorkspace=ws_name,
                                  InputWorkspace=self.getProperty(
                                      "CopyInstrumentParameters").value)
     if self._masking:
         if not mtd.doesExist('__mask'):
             LoadMask(Instrument=mtd[ws_name].getInstrument().getName(),
                      InputFile=self.getProperty("MaskFile").value,
                      OutputWorkspace='__mask')
         MaskDetectors(Workspace=ws_name, MaskedWorkspace='__mask')
     if self.XMin != Property.EMPTY_DBL and self.XMax != Property.EMPTY_DBL:
         ConvertUnits(InputWorkspace=ws_name,
                      OutputWorkspace=ws_name,
                      Target='Momentum')
         CropWorkspaceForMDNorm(InputWorkspace=ws_name,
                                OutputWorkspace=ws_name,
                                XMin=self.XMin,
                                XMax=self.XMax)
示例#11
0
def example_plots():
    #create slices and cuts
    w = Load(
        Filename=
        '/SNS/HYS/IPTS-14189/shared/autoreduce/4pixel/HYS_102102_4pixel_spe.nxs'
    )
    SetUB(w, 4.53, 4.53, 11.2, 90, 90, 90, "1,0,0", "0,0,1")
    mde = ConvertToMD(w, QDimensions='Q3D')
    sl1d = CutMD(InputWorkspace=mde,
                 P1Bin='-5,5',
                 P2Bin='-5,5',
                 P3Bin='2,4',
                 P4Bin='-10,0.5,15',
                 NoPix=True)
    sl2d = CutMD(InputWorkspace=mde,
                 P1Bin='-5,5',
                 P2Bin='-5,5',
                 P3Bin='-5,0.1,5',
                 P4Bin='-10,1,15',
                 NoPix=True)

    #2 subplots per page
    fig, ax = plt.subplots(2, 1)
    Plot1DMD(ax[0], sl1d, NumEvNorm=True, fmt='ro')
    ax[0].set_ylabel("Int(a.u.)")
    pcm = Plot2DMD(ax[1], sl2d, NumEvNorm=True)
    fig.colorbar(pcm, ax=ax[1])

    #save to png
    plt.tight_layout(1.08)
    fig.savefig('/tmp/test.png')
    def test_not_in_deltaE(self):
        red_ws_not_deltaE = Load('irs26176_graphite002_red.nxs')

        red_ws_not_deltaE = ConvertUnits(InputWorkspace=self._red_ws,
                                         Target='Wavelength',
                                         EMode='Indirect',
                                         EFixed=1.845)

        kwargs = {
            'ReducedWorkspace': red_ws_not_deltaE,
            'SqwWorkspace': self._sqw_ws,
            'ChemicalFormula': 'H2-O',
            'SampleMassDensity': 1.0,
            'NeutronPathsSingle': 50,
            'NeutronPathsMultiple': 50,
            'Height': 2.0,
            'Shape': 'FlatPlate',
            'Width': 1.4,
            'Thickness': 2.1
        }

        with self.assertRaises(RuntimeError):
            SimpleShapeDiscusInelastic(**kwargs)

        DeleteWorkspace(red_ws_not_deltaE)
示例#13
0
def main(input_file, output_dir):
    validate(input_file, output_dir)

    params = web_var.standard_vars

    mapping_file = r"/archive/NDXGEM/user/scripts/autoreduction/gem_cycle_mapping.yaml"
    calib_dir = r"/archive/NDXGEM/user/scripts/autoreduction/Calibration"

    user = "******"

    if params['mode'] == '' or params['mode'] == None:
        ws = Load(input_file)
        mode = determine_mode(ws)
        if mode:
            print("Using {} mode for reduction.".format(mode))
            params['mode'] = mode
        else:
            raise ValueError(
                "No mode supplied and unable to determine from logs please ensure "
                "Phase T0, 6m and 9m are expected. "
                "Re-run and manually supply mode in the parameters.")

    cropping_values = [
        (550, 19900),  # Bank 1
        (550, 19900),  # Bank 2
        (550, 19900),  # Bank 3
        (550, 19900),  # Bank 4
        (550, 18500),  # Bank 5
        (550, 16750)  # Bank 6
    ]
    if params['mode'] == 'Rietveld':
        cropping_values = [
            (700, 19500),  # Bank 1
            (1000, 19500),  # Bank 2
            (1000, 19500),  # Bank 3
            (1000, 19500),  # Bank 4
            (1000, 18500),  # Bank 5
            (1000, 18000)  # Bank 6
        ]
    gem = Gem(
        user_name=user,
        calibration_directory=calib_dir,
        output_directory=output_dir,
        calibration_mapping_file=mapping_file,
        do_absorb_corrections=params['do_absorb_corrections'],
        vanadium_normalisation=params['vanadium_normalisation'],
        input_mode=params['input_mode'],
        mode=params['mode'],
        multiple_scattering=params['multiple_scattering'],
        focused_cropping_values=cropping_values,
    )

    # Prior to running this script, you need to have created a vanadium for cycle 17_2 like so:
    #gem.create_vanadium(do_absorb_corrections=True,
    #                    mode="PDF",
    #                    first_cycle_run_no=87568)

    # Focus run
    run_num = get_run_number(input_file)
    gem.focus(run_number=run_num, do_absorb_corrections=False)
def GenerateEventsFilterFromFiles(filenames, OutputWorkspace,
                                  InformationWorkspace, **kwargs):

    logName = kwargs.get('LogName', None)
    minValue = kwargs.get('MinimumLogValue', None)
    maxValue = kwargs.get('MaximumLogValue', None)
    logInterval = kwargs.get('LogValueInterval', None)
    unitOfTime = kwargs.get('UnitOfTime', 'Nanoseconds')

    # TODO - handle multi-file filtering. Delete this line once implemented.
    if len(filenames) == 1:
        error = 'Multi-file filtering is not yet supported. (Stay tuned...)'
        raise Exception(error)

    for i, filename in enumerate(filenames):
        Load(Filename=filename, OutputWorkspace=filename)
        splitws, infows = GenerateEventsFilter(InputWorkspace=filename,
                                               UnitOfTime=unitOfTime,
                                               LogName=logName,
                                               MinimumLogValue=minValue,
                                               MaximumLogValue=maxValue,
                                               LogValueInterval=logInterval)
        if i == 0:
            GroupWorkspaces(splitws, OutputWorkspace=OutputWorkspace)
            GroupWorkspaces(infows, OutputWorkspace=InformationWorkspace)
        else:
            mtd[OutputWorkspace].add(splitws)
            mtd[InformationWorkspace].add(infows)
    return
示例#15
0
def find_reduced_run(run_number, run_rb, current_run_number,
                     output_workspace_binned):
    """
    Contains the logic to find the reduced run.

    First checks for a manually pre-reduced run inside RB/single_angles.

    If not found, then looks for an autoreduced run.
    """
    # try to find the file in a pre-reduced single_angles folder
    run_file_path = find_pre_reduced_run(run_number, run_rb)

    # did not find a pre-reduced run, try to load an autoreduced one
    if not run_file_path:
        if run_number == current_run_number:
            # if we are looking for the current run number, we have this calculated in a local variable
            return output_workspace_binned
        else:
            # only search for a file if the run is not the current one
            run_file_path = find_autoreduced_run(run_number, run_rb)

    # found a reduced run at some location, load it into a workspace and return it
    if run_file_path:
        ws = Load(run_file_path)
        return ws
    else:
        return None
    def test_model_with_filtered_data(self):
        wsTuple = Load('POLREF00014966.nxs')
        #get the first child workspace of the group
        ws = wsTuple[0]
        model = SampleLogsModel(ws)

        log_names = model.get_log_names()
        self.assertEqual(len(log_names), 140)
        self.assertIn("raw_uah_log", log_names)
        self.assertIn("current_period", log_names)
        self.assertIn("period", log_names)

        values = model.get_log_display_values("raw_uah_log")
        self.assertEqual(values[0], "raw_uah_log")
        self.assertEqual(values[1], "float series")
        self.assertEqual(values[2], "(429 entries)")
        self.assertEqual(values[3], "uAh")

        self.assertTrue(model.is_log_plottable("raw_uah_log"))
        self.assertFalse(model.is_log_plottable("current_period"))
        self.assertTrue(model.is_log_plottable("period"))

        self.assertTrue(model.get_is_log_filtered("raw_uah_log"))
        self.assertFalse(model.get_is_log_filtered("period"))
        self.assertFalse(model.get_is_log_filtered("current_period"))

        stats = model.get_statistics("raw_uah_log", filtered=True)
        self.assertAlmostEqual(stats.maximum, 193.333, 3)
        stats = model.get_statistics("raw_uah_log", filtered=False)
        self.assertAlmostEqual(stats.maximum, 194.296, 3)

        self.assertFalse(model.isMD())
示例#17
0
    def setUp(self):
        config['default.facility'] = 'ILL'
        config['default.instrument'] = 'D7'
        config.appendDataSearchSubDir('ILL/D7/')
        Load('numerical_attenuation.nxs',
             OutputWorkspace='numerical_attenuation_ws')

        self._sampleProperties = {
            'SampleChemicalFormula': 'V',
            'SampleMass': 8.54,
            'FormulaUnitMass': 50.94,
            'SampleInnerRadius': 2,
            'SampleOuterRadius': 2.5,
            'SampleRadius': 2.5,
            'Height': 2,
            'SampleThickness': 0.5,
            'SampleDensity': 0.1,
            'SampleAngle': 0,
            'SampleWidth': 2.5,
            'BeamWidth': 3.0,
            'BeamHeight': 3.0,
            'ContainerRadius': 2.7,
            'ContainerInnerRadius': 1.99,
            'ContainerOuterRadius': 2.7,
            'ContainerFrontThickness': 0.2,
            'ContainerBackThickness': 0.2,
            'ContainerChemicalFormula': 'Al',
            'ContainerDensity': 0.01,
            'EventsPerPoint': 100,
            'ElementSize': 1.0,
            'IncoherentCrossSection': 0.1,
            'SampleSpin': 1.5
        }
示例#18
0
    def runTest(self):
        UseCompatibilityMode()
        config['default.instrument'] = 'SANS2D'
        SANS2DTUBES()
        Set1D()
        Detector("rear-detector")
        # This contains two MASKFILE commands, each resulting in a separate call to MaskDetectors.
        MaskFile('SANS2DTube_ZerroErrorFreeTest.txt')

        # Saves a file which produces an output file which does not contain any zero errors
        csv_file = FileFinder.getFullPath(
            "SANS2DTUBES_ZeroErrorFree_batch.csv")
        save_alg = {"SaveNexus": "nxs"}
        BatchReduce(csv_file,
                    'nxs',
                    saveAlgs=save_alg,
                    plotresults=False,
                    save_as_zero_error_free=True)
        DeleteWorkspace('zero_free_out_rear_1D_1.75_12.5')

        # The zero correction only occurs for the saved files. Stephen King mentioned that the
        # original workspaces should not be tampered with
        self._final_output = os.path.join(
            config['defaultsave.directory'],
            'zero_free_out_rear_1D_1.75_12.5.nxs')
        self._final_workspace = 'ws'
        Load(Filename=self._final_output,
             OutputWorkspace=self._final_workspace)
 def runTest(self):
     flood = CreateFloodWorkspace('OFFSPEC00035946.nxs', StartSpectrum=250, EndSpectrum=600,
                                  ExcludeSpectra=[260, 261, 262, 516, 517, 518], OutputWorkspace='flood')
     data = Load('OFFSPEC00044998.nxs')
     data = Rebin(data, [0,1000,100000], PreserveEvents=False)
     data = ConvertUnits(data, 'Wavelength')
     ApplyFloodWorkspace(InputWorkspace=data, FloodWorkspace=flood, OutputWorkspace=self.out_ws_name)
    def setUp(self):
        red_ws = Load('irs26176_graphite002_red.nxs')
        red_ws = ConvertUnits(InputWorkspace=red_ws,
                              Target='Wavelength',
                              EMode='Indirect',
                              EFixed=1.845)

        self._arguments = {
            'ChemicalFormula': 'H2-O',
            'DensityType': 'Mass Density',
            'Density': 1.0,
            'EventsPerPoint': 200,
            'BeamHeight': 3.5,
            'BeamWidth': 4.0,
            'Height': 2.0
        }

        self._red_ws = red_ws

        corrected = SimpleShapeMonteCarloAbsorption(
            InputWorkspace=self._red_ws,
            Shape='FlatPlate',
            Width=2.0,
            Thickness=2.0,
            **self._arguments)

        # store the basic flat plate workspace so it can be compared with others
        self._corrected_flat_plate = corrected
    def test_ILL_reduced(self):

        ill_red_ws = Load('ILL/IN16B/091515_red.nxs')

        ill_red_ws = ConvertUnits(ill_red_ws,
                                  Target='Wavelength',
                                  EMode='Indirect',
                                  EFixed=1.845)

        kwargs = self._arguments
        corrected = SimpleShapeMonteCarloAbsorption(InputWorkspace=ill_red_ws,
                                                    Shape='FlatPlate',
                                                    Width=2.0,
                                                    Thickness=2.0,
                                                    **kwargs)

        x_unit = corrected.getAxis(0).getUnit().unitID()
        self.assertEquals(x_unit, 'Wavelength')

        y_unit = corrected.YUnitLabel()
        self.assertEquals(y_unit, 'Attenuation factor')

        num_hists = corrected.getNumberHistograms()
        self.assertEquals(num_hists, 18)

        blocksize = corrected.blocksize()
        self.assertEquals(blocksize, 1024)

        DeleteWorkspace(ill_red_ws)
示例#22
0
    def validateWorkspaceToNeXus(self):
        '''
        Assumes the second item from self.validate() is a nexus file and loads it 
        to compare to the supplied workspace.
        '''
        valNames = list(self.validate())
        from mantid.simpleapi import Load
        numRezToCheck=len(valNames)
        mismatchName=None;

        validationResult =True;
        for ik in range(0,numRezToCheck,2): # check All results
            workspace2 = valNames[ik+1]
            if workspace2.endswith('.nxs'):
                Load(Filename=workspace2,OutputWorkspace="RefFile")
                workspace2 = "RefFile"
            else:
                raise RuntimeError("Should supply a NeXus file: %s" % workspace2)
            valPair=(valNames[ik],"RefFile");
            if numRezToCheck>2:
                mismatchName = valNames[ik];

            if not(self.validateWorkspaces(valPair,mismatchName)):
                validationResult = False;
                print 'Workspace {0} not equal to its reference file'.format(valNames[ik]);
        #end check All results

        return validationResult;
示例#23
0
 def runTest(self):
     """
     Override parent method, does the work of running the test
     """
     try:
         # Load files and create workspace group
         names = ('BASIS_63652_sqw', 'BASIS_63700_sqw')
         [
             Load(Filename=name + '.nxs', OutputWorkspace=name)
             for name in names
         ]
         GroupWorkspaces(InputWorkspaces=names,
                         OutputWorkspace='elwin_input')
         ElasticWindowMultiple(InputWorkspaces='elwin_input',
                               IntegrationRangeStart=-0.0035,
                               IntegrationRangeEnd=0.0035,
                               BackgroundRangeStart=-0.1,
                               BackgroundRangeEnd=-0.05,
                               SampleEnvironmentLogName='SensorA',
                               SampleEnvironmentLogValue='average',
                               OutputInQ='outQ',
                               OutputInQSquared='outQ2',
                               OutputELF='ELF',
                               OutputELT='ELT')
     finally:
         self.preptear()
 def setUp(self):
     Load(Filename='irs26176_graphite002_red.nxs', OutputWorkspace='sample')
     SetSample(InputWorkspace='sample',
               Geometry={
                   'Shape': 'FlatPlate',
                   'Height': 2.0,
                   'Width': 2.0,
                   'Thick': 0.1,
                   'Center': [0., 0., 0.]
               },
               Material={
                   'ChemicalFormula': 'H2-O',
                   'MassDensity': 1.0
               },
               ContainerGeometry={
                   'Shape': 'FlatPlateHolder',
                   'Height': 2.0,
                   'Width': 2.0,
                   'Thick': 0.1,
                   'FrontThick': 0.02,
                   'BackThick': 0.02,
                   'Center': [0., 0., 0.]
               },
               ContainerMaterial={
                   'ChemicalFormula': 'V',
                   'MassDensity': 6.0
               })
示例#25
0
    def Untest_exportVulcanFile(self):
        """ Test to export logs without header file
        File 2: VULCAN_41739_event
        """
        from mantid.simpleapi import Load

        # Generate the matrix workspace with some logs
        Load(
            Filename=
            "/home/wzz/Projects/MantidProjects/Mantid2/Code/debug/VULCAN_41703_event.nxs",
            OutputWorkspace="VULCAN_41703",
            MetaDataOnly=True,
            LoadLog=True)

        # Test algorithm
        alg_test = run_algorithm(
            "ExportSampleLogsToCSVFile",
            InputWorkspace="VULCAN_41703",
            OutputFilename="/tmp/furnace41703.txt",
            SampleLogNames=["furnace.temp1", "furnace.temp2", "furnace.power"],
            WriteHeaderFile=False)

        # Validate
        self.assertTrue(alg_test.isExecuted())

        return
class TableWorkspaceDisplayDecoderTest(unittest.TestCase):
    def setUp(self):
        self.ws = Load("SavedTableWorkspace.nxs", OutputWorkspace="ws")
        self.decoder = TableWorkspaceDisplayDecoder()

    def test_decoder_returns_view(self):
        self.assertEqual(
            self.decoder.decode(TABLEWORKSPACEDISPLAY_DICT).__class__,
            StatusBarView)

    def test_decoder_returns_custom_features(self):
        view = self.decoder.decode(TABLEWORKSPACEDISPLAY_DICT)
        self.assertEqual(self.ws.name(), view.presenter.model.ws.name())
        self.assertEqual(TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_y"],
                         view.presenter.model.marked_columns.as_y)
        self.assertEqual(TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_x"],
                         view.presenter.model.marked_columns.as_x)
        self.assertEqual(
            TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_y_err"][0]
            ["column"], view.presenter.model.marked_columns.as_y_err[0].column)
        self.assertEqual(
            TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_y_err"][0]
            ["relatedY"],
            view.presenter.model.marked_columns.as_y_err[0].related_y_column)
        self.assertEqual(1, len(view.presenter.model.marked_columns.as_y_err))
示例#27
0
def do_load(file_specifier, output_ws_name, ipf_filename, load_logs,
            load_opts):
    """
    Loads the files, passing the given file specifier in the load command.

    :param file_specifier:  The file specifier (single file, range or sum)
    :param output_ws_name:  The name of the output workspace to create
    :param ipf_filename:    The instrument parameter file to load with
    :param load_opts:       Additional loading options
    :param load_logs:       If True, load logs
    """
    from mantid.simpleapi import LoadVesuvio, LoadParameterFile

    if 'VESUVIO' in ipf_filename:
        # Load all spectra. They are cropped later
        LoadVesuvio(Filename=str(file_specifier),
                    OutputWorkspace=output_ws_name,
                    SpectrumList='1-198',
                    **load_opts)
    else:
        Load(Filename=file_specifier,
             OutputWorkspace=output_ws_name,
             LoadLogFiles=load_logs,
             **load_opts)

    # Load the instrument parameters
    LoadParameterFile(Workspace=output_ws_name, Filename=ipf_filename)
示例#28
0
    def test_exp(self):
        """
        Tests if experimental data is loaded correctly.
        @return:
        """
        Abins(AbInitioProgram=self._ab_initio_program,
              VibrationalOrPhononFile="benzene_Abins.phonon",
              ExperimentalFile="benzene_Abins.dat",
              TemperatureInKelvin=self._temperature,
              SampleForm=self._sample_form,
              Instrument=self._instrument_name,
              Atoms=self._atoms,
              Scale=self._scale,
              SumContributions=self._sum_contributions,
              QuantumOrderEventsNumber=self._quantum_order_events_number,
              ScaleByCrossSection=self._cross_section_factor,
              OutputWorkspace="benzene_exp")

        # load experimental data
        Load(Filename="benzene.dat", OutputWorkspace="benzene_only_exp")

        (result,
         messages) = CompareWorkspaces(Workspace1=mtd["experimental_wrk"],
                                       Workspace2=mtd["benzene_only_exp"],
                                       CheckAxes=False,
                                       Tolerance=self._tolerance)
        self.assertEqual(result, True)
示例#29
0
    def validateWorkspaceToNeXus(self):
        '''
        Assumes the second item from self.validate() is a nexus file and loads it
        to compare to the supplied workspace.
        '''
        valNames = list(self.validate())
        numRezToCheck = len(valNames)
        mismatchName = None

        validationResult = True
        # results are in pairs
        for valname, refname in zip(valNames[::2], valNames[1::2]):
            if refname.endswith('.nxs'):
                Load(Filename=refname, OutputWorkspace="RefFile")
                refname = "RefFile"
            else:
                raise RuntimeError("Should supply a NeXus file: %s" % refname)
            valPair = (valname, "RefFile")
            if numRezToCheck > 2:
                mismatchName = valname

            if not(self.validateWorkspaces(valPair, mismatchName)):
                validationResult = False
                print('Workspace {0} not equal to its reference file'.format(valname))

        return validationResult
示例#30
0
    def test_csv_list_with_same_instrument_produces_single_group(self):
        data = Load("OFFSPEC10791,10792,10793.raw", OutputWorkspace = self.wsname)

        self.assertTrue(isinstance(data, WorkspaceGroup))
        self.assertEquals(6, data.getNumberOfEntries())
        ads_names = ["OFFSPEC00010791_1", "OFFSPEC00010791_2",
                     "OFFSPEC00010792_1", "OFFSPEC00010792_2",
                     "OFFSPEC00010793_1", "OFFSPEC00010793_2"]
        for name in ads_names:
            self.assertTrue(name in AnalysisDataService)

        deleted_names = ["OFFSPEC10791", "OFFSPEC10792", "OFFSPEC10793"]
        for name in deleted_names:
            self.assertTrue(name not in AnalysisDataService)

        self.cleanup_names = ads_names
示例#31
0
    def __determineCharacterizations(self, filename, wkspname, loadFile):
        useCharac = bool(self.charac is not None)

        # input workspace is only needed to find a row in the characterizations table
        tempname = None
        if loadFile:
            if useCharac:
                tempname = '__%s_temp' % wkspname
                Load(Filename=filename, OutputWorkspace=tempname,
                     MetaDataOnly=True)
        else:
            tempname = wkspname # assume it is already loaded

        # put together argument list
        args = dict(ReductionProperties=self.getProperty('ReductionProperties').valueAsStr)
        for name in PROPS_FOR_PD_CHARACTER:
            prop = self.getProperty(name)
            if not prop.isDefault:
                args[name] = prop.value
        if tempname is not None:
            args['InputWorkspace']=tempname
        if useCharac:
            args['Characterizations'] = self.charac

        PDDetermineCharacterizations(**args)

        if loadFile and useCharac:
            DeleteWorkspace(Workspace=tempname)
示例#32
0
    def test_csv_list_with_same_instrument_produces_single_group(self):
        data = Load("OFFSPEC10791,10792,10793.raw", OutputWorkspace = self.wsname)

        self.assertTrue(isinstance(data, WorkspaceGroup))
        self.assertEquals(6, data.getNumberOfEntries())
        ads_names = ["OFFSPEC00010791_1", "OFFSPEC00010791_2",
                     "OFFSPEC00010792_1", "OFFSPEC00010792_2",
                     "OFFSPEC00010793_1", "OFFSPEC00010793_2"]
        for name in ads_names:
            self.assertTrue(name in AnalysisDataService)

        deleted_names = ["OFFSPEC10791", "OFFSPEC10792", "OFFSPEC10793"]
        for name in deleted_names:
            self.assertTrue(name not in AnalysisDataService)

        self.cleanup_names = ads_names
    def setUpClass(cls):
        ConfigService.Instance().setString("default.facility", "ISIS")
        # A small workspace for general tests
        test_workspace = LoadNexusProcessed(Filename="LOQ48127")
        cls.immutable_test_workspace = test_workspace

        # A full workspace on which we can test region of interest selection
        region_of_interest_workspace = Load(Filename="LOQ74044")
        cls.region_of_interest_workspace = region_of_interest_workspace

        # A region of interest xml file
        roi_content = ("<?xml version=\"1.0\"?>\n"
                       "\t<detector-masking>\n"
                       "\t\t<group>\n"
                       "\t\t\t<detids>6990-6996</detids>\n"
                       "\t\t</group>\n"
                       "\t</detector-masking>\n")
        cls.roi_file_path = cls._get_path(cls.roi_file)
        cls._save_file(cls.roi_file_path, roi_content)

        # A mask file
        mask_content = ("<?xml version=\"1.0\"?>\n"
                        "\t<detector-masking>\n"
                        "\t\t<group>\n"
                        "\t\t\t<detids>6991</detids>\n"
                        "\t\t</group>\n"
                        "\t</detector-masking>\n")
        cls.mask_file_path = cls._get_path(cls.mask_file)
        cls._save_file(cls.mask_file_path, mask_content)
        ConfigService.Instance().setString("default.facility", " ")
示例#34
0
    def test_history(self):
        ws_name = "GEM38370_Focussed_Legacy"
        file_name = FileFinder.getFullPath(ws_name + ".nxs")
        Load(file_name, OutputWorkspace=ws_name)

        ws = mtd[ws_name]
        history = ws.getHistory()

        self.assertEqual(history.empty(), False)
        self.assertEqual(history.size(), 4)

        alg_hists = history.getAlgorithmHistories()
        self.assertEqual(len(alg_hists), 4)
        self.assertEqual(alg_hists[0].name(), "LoadRaw")
        self.assertEqual(alg_hists[1].name(), "AlignDetectors")
        self.assertEqual(alg_hists[2].name(), "DiffractionFocussing")
        self.assertEqual(alg_hists[3].name(), "Load")

        self.assertEqual(history.getAlgorithmHistory(0).name(), "LoadRaw")
        self.assertEqual(
            history.getAlgorithmHistory(1).name(), "AlignDetectors")
        self.assertEqual(
            history.getAlgorithmHistory(2).name(), "DiffractionFocussing")
        self.assertEqual(history.getAlgorithmHistory(3).name(), "Load")

        alg = history.lastAlgorithm()
        self.assertEqual(alg.name(), "Load")

        alg = history.getAlgorithm(history.size() - 1)
        self.assertEqual(alg.name(), "Load")
示例#35
0
def main(input_file, output_dir):
    standard_params = web_var.standard_vars
    advanced_params = web_var.advanced_vars
    config['defaultsave.directory'] = output_dir
    print("Input file", input_file, "output dir", output_dir)

    input_workspace, datafile_name = load_workspace(input_file)
    flood_workspace = Load(advanced_params["flood_workspace"])
    matplotlib_figure, (det_image_ax, spec_pixel_ax) = plt.subplots(
        figsize=(13, 4.8), ncols=2, subplot_kw={'projection': 'mantid'})
    matplotlib_figure.suptitle(input_workspace.getTitle())

    plot_detector_image(input_workspace, matplotlib_figure, det_image_ax)
    plotly_fig = plot_specular_pixel_check(input_workspace, flood_workspace,
                                           spec_pixel_ax)
    save_plotly_figure(plotly_fig, datafile_name, "peak", output_dir)
    matplotlib_figure.savefig(os.path.join(output_dir, f"{datafile_name}.png"))

    full_run_title = input_workspace.getTitle()
    run_rb = str(input_workspace.getRun().getLogData("rb_proposal").value)
    run_number = str(input_workspace.getRun().getLogData("run_number").value)

    print("Run title:", full_run_title, "RB:", run_rb)

    # only reduce if not a transmission run
    if "trans" in full_run_title.lower():
        print(
            "Skipping reduction due to having 'trans' in the title: {full_run_title}"
        )
    else:
        sample_name = get_sample_name(full_run_title)
        settings_file = find_settings_json(
            sample_name, standard_params['JSON Settings File'],
            f"/instrument/INTER/RBNumber/RB{run_rb}")

        output_workspace_binned = None
        if settings_file:
            output_workspace_binned = run_reduction(input_workspace,
                                                    datafile_name,
                                                    settings_file, output_dir)
        else:
            print("Skipping reduction due to missing settings file")
        group_run_numbers = find_group_runs(sample_name, run_rb, input_file)
        print("Found group_run_numbers:", group_run_numbers)

        if group_run_numbers:
            try:
                group_plot_fig = plot_group_runs(group_run_numbers,
                                                 sample_name, run_rb,
                                                 run_number,
                                                 output_workspace_binned)
                if group_plot_fig:
                    with open(
                            os.path.join(output_dir,
                                         f"{datafile_name}_group.json"),
                            'w') as figfile:
                        figfile.write(group_plot_fig)
            except Exception as err:
                print("Encountered error while trying to plot group:", err)
示例#36
0
    def __loadAndTest__(self, filename):
        """Do all of the real work of loading and testing the file"""
        print("----------------------------------------")
        print("Loading '%s'" % filename)
        from mantid.api import Workspace
        # Output can be a tuple if the Load algorithm has extra output properties
        # but the output workspace should always be the first argument
        outputs = Load(filename)
        if isinstance(outputs, tuple):
            wksp = outputs[0]
        else:
            wksp = outputs

        if not isinstance(wksp, Workspace):
            print("Unexpected output type from Load algorithm: Type found=%s" %
                  str(type(outputs)))
            return False

        if wksp is None:
            print('Load returned None')
            return False

        # generic checks
        if wksp.name() is None or len(wksp.name()) <= 0:
            print("Workspace does not have a name")
            del wksp
            return False

        wid = wksp.id()
        if wid is None or len(wid) <= 0:
            print("Workspace does not have an id")
            del wksp
            return False

        # checks based on workspace type
        if hasattr(wksp, "getNumberHistograms"):
            if wksp.getNumberHistograms() <= 0:
                print("Workspace has zero histograms")
                del wksp
                return False
            if "managed" not in wid.lower() and wksp.getMemorySize() <= 0:
                print("Workspace takes no memory: Memory used=" +
                      str(wksp.getMemorySize()))
                del wksp
                return False

        # checks for EventWorkspace
        if hasattr(wksp, "getNumberEvents"):
            if wksp.getNumberEvents() <= 0:
                print("EventWorkspace does not have events")
                del wksp
                return False

        # do the extra checks
        result = self.__runExtraTests__(wksp, filename)

        # cleanup
        del wksp
        return result
示例#37
0
def fetch_correction_workspaces(vanadium_path, instrument, rb_num=""):
    """
    Fetch workspaces from the file system or create new ones.
    :param vanadium_path: The path to the requested vanadium run raw data.
    :param instrument: The instrument the data came from.
    :param rb_num: A user identifier, usually an experiment number.
    :return: The resultant integration and curves workspaces.
    """
    vanadium_number = path_handling.get_run_number_from_path(
        vanadium_path, instrument)
    integ_path, curves_path = _generate_saved_workspace_file_paths(
        vanadium_number)
    force_recalc = get_setting(path_handling.INTERFACES_SETTINGS_GROUP,
                               path_handling.ENGINEERING_PREFIX,
                               "recalc_vanadium",
                               return_type=bool)
    if path.exists(curves_path) and path.exists(
            integ_path
    ) and not force_recalc:  # Check if the cached files exist.
        try:
            integ_workspace = Load(Filename=integ_path,
                                   OutputWorkspace=INTEGRATED_WORKSPACE_NAME)
            curves_workspace = Load(Filename=curves_path,
                                    OutputWorkspace=CURVES_WORKSPACE_NAME)
            if rb_num:
                user_integ, user_curves = _generate_saved_workspace_file_paths(
                    vanadium_number, rb_num=rb_num)
                if not path.exists(user_integ) and not path.exists(
                        user_curves):
                    _save_correction_files(integ_workspace, user_integ,
                                           curves_workspace, user_curves)
            return integ_workspace, curves_workspace
        except RuntimeError as e:
            logger.error(
                "Problem loading existing vanadium calculations. Creating new files. Description: "
                + str(e))
    integ_workspace, curves_workspace = _calculate_vanadium_correction(
        vanadium_path)
    _save_correction_files(integ_workspace, integ_path, curves_workspace,
                           curves_path)
    if rb_num:
        user_integ, user_curves = _generate_saved_workspace_file_paths(
            vanadium_number, rb_num=rb_num)
        _save_correction_files(integ_workspace, user_integ, curves_workspace,
                               user_curves)
    return integ_workspace, curves_workspace
示例#38
0
 def test_get_history_chained_calls(self):
     ws_name = "GEM38370_Focussed_Legacy"
     file_name = FileFinder.getFullPath(ws_name + ".nxs")
     Load(file_name, OutputWorkspace=ws_name)
     ws = mtd[ws_name]
     load_filename = ws.getHistory().lastAlgorithm().getProperty(
         "Filename").value
     self.assertEqual(file_name, load_filename[0])
 def test_TotScatCalculateSelfScattering_executes(self):
     raw_ws = Load(Filename='POLARIS98533.nxs')
     correction_ws = TotScatCalculateSelfScattering(
         InputWorkspace=raw_ws,
         CalFileName=self.cal_file_path,
         SampleGeometry=self.geometry,
         SampleMaterial=self.material)
     self.assertEqual(correction_ws.getNumberHistograms(), 5)
示例#40
0
 def test_Load_returns_correct_args_when_extra_output_props_are_added_at_execute_time(
         self):
     try:
         data, monitors = Load('IRS21360.raw', LoadMonitors='Separate')
     except Exception, exc:
         self.fail(
             "An error occurred when returning outputs declared at algorithm execution: '%s'"
             % str(exc))
示例#41
0
    def test_csv_list_with_different_instrument_produces_single_group(self):
        # Combine test of different instruments with giving the output name
        # the same name as one of the members of the group
        self.wsname = "LOQ99631"
        data = Load("LOQ99631.RAW, CSP85423.raw", OutputWorkspace=self.wsname)

        self.assertTrue(isinstance(data, WorkspaceGroup))
        self.assertEquals(3, data.getNumberOfEntries())
        ads_names = ["LOQ99631", "CSP85423_1", "CSP85423_2"]
        for name in ads_names:
            self.assertTrue(name in AnalysisDataService)

        deleted_names = ["CSP85423"]
        for name in deleted_names:
            self.assertTrue(name not in AnalysisDataService)

        self.cleanup_names = ads_names
        self.wsname = "__LoadTest"
    def _run_number_changed(self):
        """ Handling event if run number is changed... If it is a valid run number,
        the load the meta data
        """

        # 1. Form the file
        newrunnumberstr = self._content.run_number_edit.text()
        instrument = self._instrument_name
        eventnxsname = "%s_%s_event.nxs" % (instrument, newrunnumberstr)
        msg = str("Load event nexus file %s" % (eventnxsname))
        self._content.info_text_browser.setText(msg)

        # 2. Load file
        metawsname = "%s_%s_meta" % (instrument, newrunnumberstr)
        try:
            metaws = Load(Filename=str(eventnxsname), OutputWorkspace=str(metawsname), MetaDataOnly=True)
        except ValueError:
            metaws = None

        # 3. Update the log name combo box
        if metaws is None:
            self._content.info_text_browser.setText(
                str("Error! Failed to load data file %s.  Current working directory is %s. " % (eventnxsname, os.getcwd())))
        else:
            self._metaws = metaws

            # a) Clear
            self._content.log_name_combo.clear()

            # b) Get properties
            wsrun = metaws.getRun()
            ps = wsrun.getProperties()
            properties = []
            for p in ps:
                if p.__class__.__name__ == "FloatTimeSeriesProperty":
                    if p.size() > 1:
                        properties.append(p.name)
                        Logger('FilterSetupWidget').information('{}[{}]'.format(p.name, p.size()))
            # ENDFOR p
            properties = sorted(properties)

            # c) Add
            for p in properties:
                self._content.log_name_combo.addItem(p)
示例#43
0
    def test_plus_operator_for_input_groups(self):
        summed_data = Load("OFFSPEC10791+10792.raw", OutputWorkspace=self.wsname)

        self.assertTrue(isinstance(summed_data, WorkspaceGroup))
        self.assertEquals(2, summed_data.getNumberOfEntries())

        # First group
        data = summed_data[0]
        self.assertEquals(245, data.getNumberHistograms())
        self.assertEquals(5000, data.blocksize())

        self.assertAlmostEqual(25.0, data.readX(1)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(4.0, data.readY(1)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(2.0, data.readE(1)[1], places=DIFF_PLACES)

        # Second group
        data = summed_data[1]
        self.assertEquals(245, data.getNumberHistograms())
        self.assertEquals(5000, data.blocksize())

        self.assertAlmostEqual(25.0, data.readX(1)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(1.0, data.readY(1)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(1.0, data.readE(1)[1], places=DIFF_PLACES)
示例#44
0
    def test_sum_range_operator_with_step_sums_to_single_workspace(self):
        data = Load("TSC15352-15354:2.raw", OutputWorkspace=self.wsname)

        self.assertTrue(isinstance(data, MatrixWorkspace))
        self.assertEquals(149, data.getNumberHistograms())
        self.assertEquals(24974, data.blocksize())

        self.assertAlmostEqual(9.0, data.readX(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(35640.0, data.readY(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(188.78559267062727, data.readE(2)[1], places=DIFF_PLACES)
示例#45
0
    def test_sum_range_operator_sums_to_single_workspace(self):
        data = Load("TSC15352-15353.raw", OutputWorkspace=self.wsname)

        self.assertTrue(isinstance(data, MatrixWorkspace))
        self.assertEquals(149, data.getNumberHistograms())
        self.assertEquals(24974, data.blocksize())

        self.assertAlmostEqual(9.0, data.readX(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(46352.0, data.readY(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(215.29514625276622, data.readE(2)[1], places=DIFF_PLACES)
示例#46
0
    def runTest(self):
        self.input_ws = Load(Filename=self.input_ws_path(), OutputWorkspace="input_ws")

        gsas_path = self.path_to_gsas()
        if not gsas_path:
            self.fail("Could not find GSAS-II installation")

        self.fitted_peaks_ws, self.lattice_params_table, self.rwp, self.sigma, self.gamma = \
            GSASIIRefineFitPeaks(RefinementMethod=self._get_refinement_method(),
                                 InputWorkspace=self.input_ws,
                                 PhaseInfoFiles=self.phase_file_paths(),
                                 InstrumentFile=self.inst_param_file_path(),
                                 PathToGSASII=gsas_path,
                                 SaveGSASIIProjectFile=self._get_gsas_proj_filename(),
                                 MuteGSASII=True,
                                 XMin=10000, XMax=40000,
                                 LatticeParameters=self._LATTICE_PARAM_TBL_NAME,
                                 RefineSigma=True, RefineGamma=True)
示例#47
0
    def test_plus_operator_sums_single_set_files(self):
        data = Load("TSC15352+15353.raw", OutputWorkspace=self.wsname)

        self.assertTrue(isinstance(data, MatrixWorkspace))
        self.assertEquals(149, data.getNumberHistograms())
        self.assertEquals(24974, data.blocksize())

        self.assertAlmostEqual(9.0, data.readX(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(46352.0, data.readY(2)[1], places=DIFF_PLACES)
        self.assertAlmostEqual(215.29514625276622, data.readE(2)[1], places=DIFF_PLACES)

        deleted_names = ["TSC15352", "TSC15353"]
        for name in deleted_names:
            self.assertTrue(name not in AnalysisDataService)
class TableWorkspaceDisplayDecoderTest(GuiTest):
    def setUp(self):
        self.ws = Load("SavedTableWorkspace.nxs", OutputWorkspace="ws")
        self.decoder = TableWorkspaceDisplayDecoder()

    def test_decoder_returns_view(self):
        self.assertEqual(self.decoder.decode(TABLEWORKSPACEDISPLAY_DICT).__class__, StatusBarView)

    def test_decoder_returns_custom_features(self):
        view = self.decoder.decode(TABLEWORKSPACEDISPLAY_DICT)
        self.assertEqual(self.ws.name(), view.presenter.model.ws.name())
        self.assertEqual(TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_y"], view.presenter.model.marked_columns.as_y)
        self.assertEqual(TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_x"], view.presenter.model.marked_columns.as_x)
        self.assertEqual(
            TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_y_err"][0]["column"],
            view.presenter.model.marked_columns.as_y_err[0].column)
        self.assertEqual(
            TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_y_err"][0]["relatedY"],
            view.presenter.model.marked_columns.as_y_err[0].related_y_column)
        self.assertEqual(
            TABLEWORKSPACEDISPLAY_DICT["markedColumns"]["as_y_err"][0]["labelIndex"],
            view.presenter.model.marked_columns.as_y_err[0].label_index)
        self.assertEqual(1, len(view.presenter.model.marked_columns.as_y_err))
    def PyExec(self):
        from mantid.simpleapi import Load, ConvertUnits, Rebin, DeleteWorkspace

        # Load file to workspace
        _tmpws = Load(Filename=self.getPropertyValue("Filename"))

        # Convert to units to DeltaE
        ei = self.getProperty("Ei").value
        _tmpws = ConvertUnits(InputWorkspace=_tmpws, Target="DeltaE", EMode="Direct", EFixed=ei)

        # Rebin to requested units
        bins = self.getProperty("BinParams").value
        _tmpws = Rebin(InputWorkspace=_tmpws, Params=bins)

        # Create the new output workspace
        _summed = WorkspaceFactory.create(_tmpws, NVectors=1)
        # Set the X values for the new workspace
        _summed.setX(0, _tmpws.readX(0))

        # Sum the rows to a single row. Two methods demonstrated:

        # ----- 1: Direct workspace access -----
        # Uses less memory as it avoids a copy of the data

        # readY returns read only array. dataY returns an array we can modify on the new workspace
        # note _summed at this point has all its y-values = 0
        sumy = _summed.dataY(0)  # initialise sumy with zeros
        for i in range(_tmpws.getNumberHistograms()):
            sumy += _tmpws.readY(i)

        # ----- 2: Extract to numpy and sum ----
        # Uses more memory as extract copies to data (uncomment to see working)
        # yin = __tmpsws.extractY()
        # npsum = numpy.sum(yin,axis=0) # Axis 0 = summing down the columns
        # and put the data to the workspace
        # _summed.setY(0, npsum)

        # Store reference outside of algorithm
        self.setProperty("OutputWorkspace", _summed)

        DeleteWorkspace(_tmpws)
示例#50
0
    def test_extra_properties_passed_to_loader(self):
        data = Load("CNCS_7860_event.nxs", OutputWorkspace=self.wsname, BankName="bank1", SingleBankPixelsOnly=False)

        self.assertTrue(isinstance(data, IEventWorkspace))
        self.assertEquals(1740, data.getNumberEvents())
示例#51
0
 def test_Load_call_with_all_keyword_args_executes_correctly(self):
     raw = Load(Filename='IRS21360.raw', SpectrumMax=1)
     self.assertEquals(1, raw.getNumberHistograms())
示例#52
0
 def test_Load_call_with_other_args_executes_correctly(self):
     try:
         raw = Load("IRS21360.raw", SpectrumMax=1)
     except RuntimeError:
         self.fail("Load with a filename and extra args should not raise an exception")
     self.assertEquals(1, raw.getNumberHistograms())
 def setUp(self):
     self.ws = Load("SavedTableWorkspace.nxs", OutputWorkspace="ws")
     self.decoder = TableWorkspaceDisplayDecoder()
示例#54
0
 def test_Load_call_with_just_filename_executes_correctly(self):
     try:
         raw = Load('IRS21360.raw')
     except RuntimeError:
         self.fail("Load with a filename should not raise an exception")
     self.assertEquals(116, raw.getNumberHistograms())
    print "t0={}, t(-1)={}".format(running_times[0], running_times[-1])
    if ts < running_times[0] or ts > running_times[-1]:
        return False
    running = True
    for i in range(len(running_times) - 1):
        print "ts={}, rt(i)={}, rt(i+1)={}".format(ts,  running_times[i], running_times[i+1])
        if (ts >= running_times[i]) and (ts < running_times[i+1]):
            running = running_values[i]
            print "found ",i, running
            break
    return running

# ----------------------------------------------------------------------------------------------------------------------


w = Load('/mnt/data1/source/github/mantidproject/mantid/builds/debug/ExternalData/Testing/Data/SystemTest/LARMOR/LARMOR00000063.nxs')
r = w.run()
run_start = dt.datetime.strptime(str(r.startTime()).strip(), ISO_TIMESTAMP_FORMAT)

dae_beam_current = r.getLogData('dae_beam_current')
# running log is series of boolean values indicating run status
running_log = w.run().getLogData('running')
running_times = []
for t in running_log.times:
    running_times.append(to_datetime_iso(t))

# create times as offset from run_start
uamps_times, uamps_values = dae_beam_current.times, dae_beam_current.value
delta_t, uamps_datetime = [], []
for t in uamps_times:
    t1, t2 = run_start, to_datetime_iso(t)
示例#56
0
def reduceOneKeepingEvents(nxsfile, angle, eiguess, eaxis, outfile, t0guess=0.):
    """reduce nxs from one angle of a single crystal scan, keeping events
    (only do tof->E conversion)

    nxsfile: input path
    angle: psi in degrees
    eiguess: Ei in meV
    eaxis: Emin, Emax, dE
    outfile: output path
    """
    from mantid.simpleapi import DgsReduction, SofQW3, SaveNexus, SaveNXSPE, LoadInstrument, Load, MoveInstrumentComponent, AddSampleLog
    outfile = os.path.abspath(outfile)
    print "* working on reducing %s to %s" % (nxsfile, outfile)
    # load workspace from input nexus file
    workspace = Load(nxsfile)

    # workspace name have to be unique
    unique_name = os.path.dirname(nxsfile).split('/')[-1]
    wsname = 'reduced-%s' % unique_name

    # Ei
    if eiguess == 0.:
        # If user does not supply Ei, we try to get it from the samplelog,
        # because mcvine-generated SEQUOIA data files are mantid-processed nexus file
        # with sample logs of Ei and t0.
        # If we don't have them from sample logs, we just set Ei and T0 to None
        run = workspace.getRun()
        UseIncidentEnergyGuess = False
        try:
            Ei = run.getLogData('mcvine-Ei').value
            UseIncidentEnergyGuess = True
        except:
            Ei = None
        try:
            T0 = run.getLogData('mcvine-t0').value
        except:
            T0 = None
    else:
        # user specified Ei, just use that
        Ei = eiguess
        T0 = t0guess
        UseIncidentEnergyGuess = True
    # keep events (need to then run RebinToWorkspace and ConvertToDistribution)
    Emin, Emax, dE = eaxis
    eaxis = '%s,%s,%s' % (Emin,dE, Emax)
    DgsReduction(
        SampleInputWorkspace = workspace,
        IncidentEnergyGuess = Ei,
        TimeZeroGuess = T0,
        UseIncidentEnergyGuess=UseIncidentEnergyGuess,
        OutputWorkspace=wsname,
        SofPhiEIsDistribution='0',
        EnergyTransferRange = eaxis,
        )

    AddSampleLog(Workspace=wsname,LogName="psi",LogText=str(angle),LogType="Number")
    SaveNexus(
        InputWorkspace=wsname,
        Filename = outfile,
        Title = 'reduced',
        )
    return
示例#57
0
class _AbstractGSASIIRefineFitPeaksTest(stresstesting.MantidStressTest):

    __metaclass__ = ABCMeta

    fitted_peaks_ws = None
    gamma = None
    input_ws = None
    rwp = None
    sigma = None
    lattice_params_table = None

    _LATTICE_PARAM_TBL_NAME = "LatticeParameters"
    _INPUT_WORKSPACE_FILENAME = "focused_bank1_ENGINX00256663.nxs"
    _PHASE_FILENAME_1 = "Fe-gamma.cif"
    _PHASE_FILENAME_2 = "Fe-alpha.cif"
    _INST_PARAM_FILENAME = "template_ENGINX_241391_236516_North_bank.prm"
    _TEMP_DIR = tempfile.gettempdir()
    _path_to_gsas = None

    @abstractmethod
    def _get_expected_rwp(self):
        pass

    @abstractmethod
    def _get_fit_params_reference_filename(self):
        pass

    @abstractmethod
    def _get_gsas_proj_filename(self):
        pass

    @abstractmethod
    def _get_refinement_method(self):
        pass

    def cleanup(self):
        mantid.mtd.clear()
        self.remove_all_gsas_files(gsas_filename_without_extension=self._get_gsas_proj_filename().split(".")[0])

    def excludeInPullRequests(self):
        return True

    def input_ws_path(self):
        return mantid.FileFinder.getFullPath(self._INPUT_WORKSPACE_FILENAME)

    def inst_param_file_path(self):
        return mantid.FileFinder.getFullPath(self._INST_PARAM_FILENAME)

    def path_to_gsas(self):
        if self._path_to_gsas is None:
            gsas_location = os.path.join(site.USER_SITE, "g2conda", "GSASII")
            if os.path.isdir(gsas_location):
                self._path_to_gsas = os.path.join(site.USER_SITE, "g2conda", "GSASII")
            else:
                self._path_to_gsas = ""

        return self._path_to_gsas

    def phase_file_paths(self):
        return mantid.FileFinder.getFullPath(self._PHASE_FILENAME_1) + "," + \
               mantid.FileFinder.getFullPath(self._PHASE_FILENAME_2)

    def remove_all_gsas_files(self, gsas_filename_without_extension):
        for filename in os.listdir(self._TEMP_DIR):
            if re.search(gsas_filename_without_extension, filename):
                os.remove(os.path.join(self._TEMP_DIR, filename))

    def runTest(self):
        self.input_ws = Load(Filename=self.input_ws_path(), OutputWorkspace="input_ws")

        gsas_path = self.path_to_gsas()
        if not gsas_path:
            self.fail("Could not find GSAS-II installation")

        self.fitted_peaks_ws, self.lattice_params_table, self.rwp, self.sigma, self.gamma = \
            GSASIIRefineFitPeaks(RefinementMethod=self._get_refinement_method(),
                                 InputWorkspace=self.input_ws,
                                 PhaseInfoFiles=self.phase_file_paths(),
                                 InstrumentFile=self.inst_param_file_path(),
                                 PathToGSASII=gsas_path,
                                 SaveGSASIIProjectFile=self._get_gsas_proj_filename(),
                                 MuteGSASII=True,
                                 XMin=10000, XMax=40000,
                                 LatticeParameters=self._LATTICE_PARAM_TBL_NAME,
                                 RefineSigma=True, RefineGamma=True)

    def skipTests(self):
        # Skip this test, as it's just a wrapper for the Rietveld and Pawley tests
        return True

    def validate(self):
        # TODO: Check fitted_peaks_ws has correct values once we have some data we're sure of
        self.assertEqual(self.input_ws.getNumberBins(), self.fitted_peaks_ws.getNumberBins())
        self.assertAlmostEqual(self.rwp, self._get_expected_rwp(), delta=1e-6)
        return self._LATTICE_PARAM_TBL_NAME, mantid.FileFinder.getFullPath(self._get_fit_params_reference_filename())