当前位置: 首页>>代码示例>>Python>>正文


Python api.FileFinder类代码示例

本文整理汇总了Python中mantid.api.FileFinder的典型用法代码示例。如果您正苦于以下问题:Python FileFinder类的具体用法?Python FileFinder怎么用?Python FileFinder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了FileFinder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: find_data

def find_data(file, instrument='', allow_multiple=False):
    """
        Finds a file path for the specified data set, which can either be:
            - a run number
            - an absolute path
            - a file name
        @param file: file name or part of a file name
        @param instrument: if supplied, FindNeXus will be tried as a last resort
    """
    # First, assume a file name
    file = str(file).strip()

    # If we allow multiple files, users may use ; as a separator,
    # which is incompatible with the FileFinder
    n_files = 1
    if allow_multiple:
        file=file.replace(';',',')
        toks = file.split(',')
        n_files = len(toks)

    instrument = str(instrument)
    file_path = FileFinder.getFullPath(file)
    if os.path.isfile(file_path):
        return file_path

    # Second, assume a run number and pass the instrument name as a hint
    try:
        # FileFinder doesn't like dashes...
        instrument=instrument.replace('-','')
        f = FileFinder.findRuns(instrument+file)
        if os.path.isfile(f[0]):
            if allow_multiple:
                # Mantid returns its own list object type, so make a real list out if it
                if len(f)==n_files:
                    return [i for i in f]
            else:
                return f[0]
    except:
        # FileFinder couldn't make sense of the the supplied information
        pass

    # Third, assume a run number, without instrument name to take care of list of full paths
    try:
        f = FileFinder.findRuns(file)
        if os.path.isfile(f[0]):
            if allow_multiple:
                # Mantid returns its own list object type, so make a real list out if it
                if len(f)==n_files:
                    return [i for i in f]
            else:
                return f[0]
    except:
        # FileFinder couldn't make sense of the the supplied information
        pass

    # If we didn't find anything, raise an exception
    Logger('find_data').error("\n\nCould not find a file for %s: check your reduction parameters\n\n" % str(file))
    raise RuntimeError("Could not find a file for %s" % str(file))
开发者ID:DanNixon,项目名称:mantid,代码行数:58,代码来源:find_data.py

示例2: test_that_find_runs_accepts_a_list_of_string_and_a_bool

 def test_that_find_runs_accepts_a_list_of_string_and_a_bool(self):
     try:
         runs = FileFinder.findRuns("CNCS7860", useExtsOnly=True)
         FileFinder.findRuns("CNCS7860", [".nxs", ".txt"], useExtsOnly=True)
     except Exception as e:
         if type(e).__name__ == "ArgumentError":
             self.assertFalse(True, "Expected findRuns to accept a list of strings and a bool as input."
                                    " {} error was raised with message {}".format(type(e).__name__, str(e)))
     else:
         # Confirm that it works as above
         self.assertTrue(len(runs) == 1)
         self.assertTrue(os.path.exists(runs[0]))
开发者ID:mantidproject,项目名称:mantid,代码行数:12,代码来源:FileFinderTest.py

示例3: __verifyRequiredFile

    def __verifyRequiredFile(self, filename):
        '''Return True if the specified file name is findable by Mantid.'''
        from mantid.api import FileFinder

        # simple way is just getFullPath which never uses archive search
        if os.path.exists(FileFinder.getFullPath(filename)):
            return True

        # try full findRuns which will use archive search if it is turned on
        try:
            candidates = FileFinder.findRuns(filename)
            for item in candidates:
                if os.path.exists(item):
                    return True
        except RuntimeError, e:
            return False
开发者ID:mantidproject,项目名称:systemtests,代码行数:16,代码来源:stresstesting.py

示例4: setUp

    def setUp(self):
        self._qapp = mock_widget.mockQapp()
        # Store an empty widget to parent all the views, and ensure they are deleted correctly
        self.obj = QtGui.QWidget()
        ConfigService['default.instrument'] = 'MUSR'

        setup_context_for_tests(self)
        self.context.instrument = 'MUSR'
        self.load_file_view = BrowseFileWidgetView(self.obj)
        self.load_run_view = LoadRunWidgetView(self.obj)
        self.load_file_model = BrowseFileWidgetModel(self.loaded_data, self.context)
        self.load_run_model = LoadRunWidgetModel(self.loaded_data, self.context)

        self.view = LoadWidgetView(parent=self.obj, load_file_view=self.load_file_view,
                                   load_run_view=self.load_run_view)
        self.presenter = LoadWidgetPresenter(self.view, LoadWidgetModel(self.loaded_data, self.context))
        self.presenter.set_load_file_widget(BrowseFileWidgetPresenter(self.load_file_view, self.load_file_model))
        self.presenter.set_load_run_widget(LoadRunWidgetPresenter(self.load_run_view, self.load_run_model))

        self.presenter.load_file_widget._view.warning_popup = mock.MagicMock()
        self.presenter.load_run_widget._view.warning_popup = mock.MagicMock()

        self.view.multiple_loading_check.setCheckState(1)
        self.presenter.handle_multiple_files_option_changed()

        self.runs = [15196, 15197]
        self.workspaces = [self.create_fake_workspace(1) for _ in self.runs]
        self.filenames = FileFinder.findRuns('MUSR00015196.nxs, MUSR00015197.nxs')
开发者ID:mantidproject,项目名称:mantid,代码行数:28,代码来源:loadwidget_presenter_multiple_file_test.py

示例5: _run

    def _run(self):
        '''Defines the workflow for the test'''
        self.tolerance = 1e-3
        self.samples = [sample[:-4] for sample in self.samples]

        # Load files into Mantid
        for sample in self.samples:
            LoadNexus(sample, OutputWorkspace=sample)
        LoadNexus(FileFinder.getFullPath(self.resolution), OutputWorkspace=self.resolution)

        _, iqt_ws = TransformToIqt(SampleWorkspace=self.samples[0],
                                   ResolutionWorkspace=self.resolution,
                                   EnergyMin=self.e_min,
                                   EnergyMax=self.e_max,
                                   BinReductionFactor=self.num_bins,
                                   DryRun=False,
                                   NumberOfIterations=200)

        # Test IqtFit Sequential
        iqtfitSeq_ws, params, fit_group = IqtFitSequential(InputWorkspace=iqt_ws, Function=self.func,
                                                           StartX=self.startx, EndX=self.endx,
                                                           SpecMin=0, SpecMax=self.spec_max)

        self.result_names = [iqt_ws.name(),
                             iqtfitSeq_ws[0].name()]

        # Remove workspaces from Mantid
        for sample in self.samples:
            DeleteWorkspace(sample)
        DeleteWorkspace(params)
        DeleteWorkspace(fit_group)
        DeleteWorkspace(self.resolution)
开发者ID:samueljackson92,项目名称:mantid,代码行数:32,代码来源:ISISIndirectInelastic.py

示例6: getDataFileNames

    def getDataFileNames(self, runsetupdict, advsetupdict):
        """ Obtain the data file names (run names + SUFFIX)

        Return: list of files
        """

        runnumbers_str = str(runsetupdict["RunNumber"])
        if runnumbers_str.count(':') > 0:
            runnumbers_str = runnumbers_str.replace(':', '-')
        runnumbers_str = FileFinder.findRuns('{}{}'.format(self.instrument_name, runnumbers_str))
        runnumbers_str = [os.path.split(filename)[-1] for filename in runnumbers_str]

        # create an integer version
        runnumbers = []
        for filename in runnumbers_str:
            for extension in ['_event.nxs', '.nxs.h5']:
                filename = filename.replace(extension, '')
            runnumber = filename.split('_')[-1]
            runnumbers.append(int(runnumber))

        # put together the output
        datafilenames = []
        for (filename, runnumber) in zip(runnumbers_str, runnumbers):
            datafilenames.append((runnumber, filename))

        return datafilenames
开发者ID:mantidproject,项目名称:mantid,代码行数:26,代码来源:diffraction_reduction_script.py

示例7: find_sans_file

def find_sans_file(file_name):
    """
    Finds a SANS file.
    The file can be specified as:
    1. file.ext or  path1 path2 file.ext
    2. run number
    :param file_name: a file name or a run number.
    :return: the full path.
    """
    error_message = "Trying to find the SANS file {0}, but cannot find it. Make sure that "\
                    "the relevant paths are added and the correct instrument is selected."
    try:
        full_path = find_full_file_path(file_name)
        if not full_path and not file_name.endswith('.nxs'):
            full_path = find_full_file_path(file_name + '.nxs')
        if not full_path:
            # TODO: If we only provide a run number for example 98843 for LOQ measurments, but have LARMOR specified as the
            #       Mantid instrument, then the FileFinder will search itself to death. This is a general Mantid issue.
            #       One way to handle this graceful would be a timeout option.
            file_name_as_bytes = str.encode(file_name)
            assert(type(file_name_as_bytes) == bytes)
            runs = FileFinder.findRuns(file_name_as_bytes)
            if runs:
                full_path = runs[0]
    except RuntimeError:
        raise RuntimeError(error_message.format(file_name))

    if not full_path:
        raise RuntimeError(error_message.format(file_name))
    return full_path
开发者ID:samueljackson92,项目名称:mantid,代码行数:30,代码来源:file_information.py

示例8: _create_peaks_workspace

    def _create_peaks_workspace(self):
        """Create a dummy peaks workspace"""
        path = FileFinder.getFullPath("IDFs_for_UNIT_TESTING/MINITOPAZ_Definition.xml")
        inst = LoadEmptyInstrument(Filename=path)
        ws = CreatePeaksWorkspace(inst, 0)
        DeleteWorkspace(inst)
        SetUB(ws, 1, 1, 1, 90, 90, 90)

        # Add a bunch of random peaks that happen to fall on the
        # detetor bank defined in the IDF
        center_q = np.array([-5.1302,2.5651,3.71809])
        qs = []
        for i in np.arange(0, 1, 0.1):
            for j in np.arange(-0.5, 0, 0.1):
                q = center_q.copy()
                q[1] += j
                q[2] += i
                qs.append(q)

        # Add the peaks to the PeaksWorkspace with dummy values for intensity,
        # Sigma, and HKL
        for q in qs:
            peak = ws.createPeak(q)
            peak.setIntensity(100)
            peak.setSigmaIntensity(10)
            peak.setHKL(1, 1, 1)
            ws.addPeak(peak)

        return ws
开发者ID:DanNixon,项目名称:mantid,代码行数:29,代码来源:SaveReflectionsTest.py

示例9: _get_workspace

 def _get_workspace(self, file_name):
     full_file_name = FileFinder.findRuns(file_name)[0]
     load_name = "Load"
     load_options = {"Filename": full_file_name,
                     "OutputWorkspace": EMPTY_NAME}
     load_alg = create_unmanaged_algorithm(load_name, **load_options)
     load_alg.execute()
     return load_alg.getProperty("OutputWorkspace").value
开发者ID:mantidproject,项目名称:mantid,代码行数:8,代码来源:crop_helper_test.py

示例10: cleanup

 def cleanup(self):
     Files = ["TOPAZ_3132.hkl",
     "TOPAZ_3132FFT.hkl"]
     for file in Files:
         absfile = FileFinder.getFullPath(file)
         if os.path.exists(absfile):
             os.remove(absfile)
     return True
开发者ID:nimgould,项目名称:mantid,代码行数:8,代码来源:Diffraction_Workflow_Test.py

示例11: do_cleanup

def do_cleanup():
    Files = ["BioSANS_test_data_reduction.log",
             "BioSANS_test_data_Iq.xml",
             "BioSANS_test_data_Iq.txt",
             "BioSANS_test_data_Iqxy.dat"]
    for filename in Files:
        absfile = FileFinder.getFullPath(filename)
        if os.path.exists(absfile):
            os.remove(absfile)
    return True
开发者ID:DanNixon,项目名称:mantid,代码行数:10,代码来源:HFIREffAPIv2.py

示例12: do_cleanup

def do_cleanup():
    Files = ["PG3_9829.gsa",
    "PG3_9829.py",
    "PG3_9830.gsa",
    "PG3_9830.py"]
    for file in Files:
        absfile = FileFinder.getFullPath(file)
        if os.path.exists(absfile):
            os.remove(absfile)
    return True
开发者ID:mantidproject,项目名称:systemtests,代码行数:10,代码来源:SNSPowderRedux.py

示例13: test_browse_clicked_suceeds_if_table_in_ADS

    def test_browse_clicked_suceeds_if_table_in_ADS(self):
        filename = FileFinder.findRuns('MUSR00015196.nxs')[0]
        self.view.show_file_browser_and_return_selection = mock.MagicMock(return_value=[filename])
        self.model.check_dead_time_file_selection = mock.MagicMock(return_value=True)

        self.view.dead_time_browse_button.clicked.emit(True)

        self.assertEqual(self.view.dead_time_selector.currentIndex(), 2)
        self.view.warning_popup.assert_not_called()
        self.assertEqual(self.view.dead_time_file_selector.currentText(), 'MUSR00015196_deadTimes')
        self.gui_variable_observer.update.assert_called_once_with(self.gui_context.gui_variables_notifier, None)
开发者ID:mantidproject,项目名称:mantid,代码行数:11,代码来源:home_instrument_widget_test.py

示例14: runTest

    def runTest(self):
        UseCompatibilityMode()
        SANS2D()
        Set1D()
        Detector("rear-detector")
        MaskFile('MASKSANS2Doptions.091A')
        Gravity(True)

        csv_file = FileFinder.getFullPath('SANS2D_periodTests.csv')

        BatchReduce(csv_file, 'nxs', plotresults=False, saveAlgs={'SaveCanSAS1D': 'xml', 'SaveNexus': 'nxs'})
        os.remove(os.path.join(config['defaultsave.directory'], '5512p7_SANS2DBatch.xml'))
开发者ID:DanNixon,项目名称:mantid,代码行数:12,代码来源:SANS2DBatchTest_V2.py

示例15: runTest

    def runTest(self):
        UseCompatibilityMode()
        SANS2D()
        Set1D()
        Detector("rear-detector")
        MaskFile('MASKSANS2Doptions.091A')
        Gravity(True)

        csv_file = FileFinder.getFullPath('SANS2D_multiPeriodTests.csv')

        BatchReduce(csv_file, 'nxs', saveAlgs={})
        self.reduced = '5512_SANS2DBatch'
开发者ID:DanNixon,项目名称:mantid,代码行数:12,代码来源:SANS2DMultiPeriod_V2.py


注:本文中的mantid.api.FileFinder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。