• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python kernel.Logger类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: PluginLoader

class PluginLoader(object):

    extension = ".py"

    def __init__(self, filepath):
        if not _os.path.isfile(filepath):
            raise ValueError("PluginLoader expects a single filename. '%s' does not point to an existing file" % filepath)
        if not filepath.endswith(self.extension):
            raise ValueError("PluginLoader expects a filename ending with .py. '%s' does not have a .py extension" % filepath)
        self._filepath = filepath
        self._logger = Logger("PluginLoader")

    def run(self):
        """
            Try and load the module we are pointing at and return
            the module object.

            Any ImportErrors raised are not caught and are passed
            on to the caller
        """
        pathname = self._filepath
        name = _os.path.basename(pathname) # Including extension
        name = _os.path.splitext(name)[0]
        self._logger.debug("Loading python plugin %s" % pathname)
        return _imp.load_source(name, pathname)
开发者ID:liyulun,项目名称:mantid,代码行数:25,代码来源:plugins.py


示例2: SaveIqAscii

def SaveIqAscii(reducer=None, process=''):
    """ Old command for backward compatibility """
    output_dir = os.path.expanduser('~')
    msg = "SaveIqAscii is not longer used:\n  "
    msg += "Please use 'SaveIq' instead\n  "
    msg += "Your output files are currently in %s" % output_dir
    Logger.get("CommandInterface").warning(msg)
    ReductionSingleton().reduction_properties["OutputDirectory"] = output_dir
    ReductionSingleton().reduction_properties["ProcessInfo"] = str(process)
开发者ID:trnielsen,项目名称:mantid,代码行数:9,代码来源:hfir_command_interface.py


示例3: 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.get('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:trnielsen,项目名称:mantid,代码行数:56,代码来源:find_data.py


示例4: __init__

 def __init__(self, name="", facility=""):
     self.instrument_name = name
     self.facility_name = facility
     self._observers = []
     self._output_directory = os.path.expanduser('~')
     if HAS_MANTID:
         config = ConfigService.Instance()
         try:
             head, tail = os.path.split(config.getUserFilename())
             if os.path.isdir(head):
                 self._output_directory = head
         except:
             Logger.get("scripter").debug("Could not get user filename")
开发者ID:trnielsen,项目名称:mantid,代码行数:13,代码来源:scripter.py


示例5: test_logger_creation_does_not_raise_an_error

 def test_logger_creation_does_not_raise_an_error(self):
     logger = Logger.get("LoggerTest")
     self.assertTrue(isinstance(logger, Logger))
     attrs = ['fatal', 'error','warning','notice', 'information', 'debug']
     for att in attrs:
         if not hasattr(logger, att):
             self.fail("Logger object does not have the required attribute '%s'" % att)
开发者ID:trnielsen,项目名称:mantid,代码行数:7,代码来源:LoggerTest.py


示例6: __init__

 def __init__(self, filepath):
     if not _os.path.isfile(filepath):
         raise ValueError("PluginLoader expects a single filename. '%s' does not point to an existing file" % filepath)
     if not filepath.endswith(self.extension):
         raise ValueError("PluginLoader expects a filename ending with .py. '%s' does not have a .py extension" % filepath)
     self._filepath = filepath
     self._logger = Logger.get("PluginLoader")
开发者ID:trnielsen,项目名称:mantid,代码行数:7,代码来源:plugins.py


示例7: __init__

 def __init__(self, parent_presenter, WorkHandler, BeamCentreModel, SANSCentreFinder):
     super(BeamCentrePresenter, self).__init__()
     self._view = None
     self._parent_presenter = parent_presenter
     self._work_handler = WorkHandler()
     self._logger = Logger("SANS")
     self._beam_centre_model = BeamCentreModel(SANSCentreFinder)
开发者ID:samueljackson92,项目名称:mantid,代码行数:7,代码来源:beam_centre_presenter.py


示例8: find_beam_centre

    def find_beam_centre(self, state):
        """
        This is called from the GUI and runs the find beam centre algorithm given a state model and a beam_centre_model object.

        :param state: A SANS state object
        :param beam_centre_model: An instance of the BeamCentreModel class.
        :returns: The centre position found.
        """
        centre_finder = self.SANSCentreFinder()
        find_direction = None
        if self.up_down and self.left_right:
            find_direction = FindDirectionEnum.All
        elif self.up_down:
            find_direction = FindDirectionEnum.Up_Down
        elif self.left_right:
            find_direction = FindDirectionEnum.Left_Right
        else:
            logger = Logger("CentreFinder")
            logger.notice("Have chosen no find direction exiting early")
            return {"pos1": self.lab_pos_1, "pos2": self.lab_pos_2}

        if self.COM:
            centre = centre_finder(state, r_min=self.r_min, r_max=self.r_max,
                                   max_iter=self.max_iterations,
                                   x_start=self.lab_pos_1, y_start=self.lab_pos_2,
                                   tolerance=self.tolerance,
                                   find_direction=find_direction, reduction_method=False, component=self.component)

            centre = centre_finder(state, r_min=self.r_min, r_max=self.r_max,
                                   max_iter=self.max_iterations,
                                   x_start=centre['pos1'], y_start=centre['pos2'],
                                   tolerance=self.tolerance,
                                   find_direction=find_direction, reduction_method=True,
                                   verbose=self.verbose, component=self.component)
        else:
            centre = centre_finder(state, r_min=self.r_min, r_max=self.r_max,
                                   max_iter=self.max_iterations, x_start=self.lab_pos_1,
                                   y_start=self.lab_pos_2, tolerance=self.tolerance,
                                   find_direction=find_direction, reduction_method=True,
                                   verbose=self.verbose, component=self.component)
        return centre
开发者ID:mantidproject,项目名称:mantid,代码行数:41,代码来源:beam_centre_model.py


示例9: __init__

 def __init__(self, data_file, workspace_name=None):
     self.errors = []
     if HAS_MANTID:
         try:
             if workspace_name is None:
                 self.data_ws = "__raw_data_file"
             else:
                 self.data_ws = str(workspace_name)
             api.HFIRLoad(Filename=str(data_file), OutputWorkspace=self.data_ws)
             ws = AnalysisDataService.retrieve(self.data_ws)
             x = ws.dataX(0)
             self.wavelength = (x[0]+x[1])/2.0
             self.wavelength_spread = x[1]-x[0]
             self.sample_detector_distance = ws.getRun().getProperty("sample_detector_distance").value
             self.sample_thickness = ws.getRun().getProperty("sample-thickness").value
             self.beam_diameter = ws.getRun().getProperty("beam-diameter").value
             
             Logger.get("hfir_data_proxy").information("Loaded data file: %s" % data_file)
         except:
             Logger.get("hfir_data_proxy").error("Error loading data file:\n%s" % sys.exc_value)
             self.errors.append("Error loading data file:\n%s" % sys.exc_value)
开发者ID:trnielsen,项目名称:mantid,代码行数:21,代码来源:hfir_data_proxy.py


示例10: pre_process

 def pre_process(self):
     """
         Reduction steps that are meant to be executed only once per set
         of data files. After this is executed, all files will go through
         the list of reduction steps.
     """
     Logger.get("Reducer").information("Setting up reduction options")
     if self.setup_algorithm is not None:
         alg = AlgorithmManager.create(self.setup_algorithm)
         alg.initialize()
         props = [p.name for p in alg.getProperties()]
         for key in self.reduction_properties.keys():
             if key in props:
                 try:
                     alg.setProperty(key, self.reduction_properties[key])
                 except:
                     msg = "Error setting %s=%s" % (key, str(self.reduction_properties[key]))
                     msg += "\n  %s" % sys.exc_value
                     Logger.get("Reducer").error(msg)
             else:
                 Logger.get("Reducer").warning("Setup algorithm has no %s property" % key)
         
         if "ReductionProperties" in props:
             alg.setPropertyValue("ReductionProperties",
                                  self.get_reduction_table_name())
         alg.execute()
开发者ID:trnielsen,项目名称:mantid,代码行数:26,代码来源:reducer.py


示例11: __init__

    def __init__(self, reducer, coord1_scale_factor, coord2_scale_factor):
        super(BeamCenterLogger, self).__init__()
        self.logger = Logger("CentreFinder")
        self.using_angle = False
        if is_workspace_which_requires_angle(reducer):
            self.coord1_scale_factor = 1.
            self.using_angle = True
            # Find the bench rotation. Only supply the bench rotation if it is really needed. If we supply an offset
            # through a bench rotation we need to take into account that the directionality of the angles is not
            # the same as in Mantid. We need to reverse the sign of the bench rotation to get the correct rotation.
            self.offset_coord1 = -1*get_bench_rotation(reducer)
        else:
            self.coord1_scale_factor = coord1_scale_factor
            self.offset_coord1 = 0.0

        self.coord2_scale_factor = coord2_scale_factor
        self.offset_coord2 = 0.0
开发者ID:liyulun,项目名称:mantid,代码行数:17,代码来源:centre_finder.py


示例12: CentreFinder

class CentreFinder(object):
    """
        Aids estimating the effective centre of the particle beam by calculating Q in four
        quadrants and using the asymmetry to calculate the direction to the beam centre. A
        better estimate for the beam centre position can hence be calculated iteratively
    """
    QUADS = ['Left', 'Right', 'Up', 'Down']
    def __init__(self, guess_centre, sign_policy, find_direction = FindDirectionEnum.ALL):
        """
            Takes a loaded reducer (sample information etc.) and the initial guess of the centre
            position that are required for all later iterations
            @param guess_centre: the starting position that the trial x and y are relative to
            @param sign_policy: sets the sign for the move operation.
            @param find_direction: Find beam centre for directions, ie if all or only up/down
                                   or only left right
        """
        self.logger = Logger("CentreFinder")
        self._last_pos = guess_centre
        self.detector = None
        self.coord1_scale_factor = 1.0
        self.coord2_scale_factor = 1.0
        self.find_direction = find_direction
        self.sign_coord1 = -1.
        self.sign_coord2 = -1.
        if sign_policy is not None and len(sign_policy) == 2:
            self.sign_coord1 = sign_policy[0]
            self.sign_coord2 = sign_policy[1]

    def SeekCentre(self, setup, trial):
        """
            Does four calculations of Q to estimate a better centre location than the one passed
            to it
            @param setup: the reduction chain object that contains information about the reduction
            @param trial: the coordinates of the location to test as a list in the form [x, y]
            @return: the asymmetry in the calculated Q in the x and y directions
        """
        self.detector = setup.instrument.cur_detector().name()

        # populate the x and y scale factor values at this point for the text box
        self.coord1_scale_factor = setup.instrument.beam_centre_scale_factor1
        self.coord2_scale_factor = setup.instrument.beam_centre_scale_factor2

         # We are looking only at the differnce between the old position and the trial.
        self.move(setup, trial[0]-self._last_pos[0], trial[1]-self._last_pos[1])

        #phi masking will remove areas of the detector that we need
        setup.mask.mask_phi = False

        setup.pre_process()
        setup.output_wksp = 'centre'
        steps = setup._conv_Q
        steps = steps[0:len(steps)-1]
        setup._reduce(init=False, post=False, steps=steps)

        self._group_into_quadrants(setup, 'centre', suffix='_tmp')

        if setup.get_can():
            #reduce the can here
            setup.reduce_can('centre_can', run_Q=False)

            self._group_into_quadrants(setup, 'centre_can', suffix='_can')
            Minus(LHSWorkspace='Left_tmp',RHSWorkspace= 'Left_can',OutputWorkspace= 'Left_tmp')
            Minus(LHSWorkspace='Right_tmp',RHSWorkspace= 'Right_can',OutputWorkspace= 'Right_tmp')
            Minus(LHSWorkspace='Up_tmp',RHSWorkspace= 'Up_can',OutputWorkspace= 'Up_tmp')
            Minus(LHSWorkspace='Down_tmp',RHSWorkspace= 'Down_can',OutputWorkspace= 'Down_tmp')
            DeleteWorkspace(Workspace='Left_can')
            DeleteWorkspace(Workspace='Right_can')
            DeleteWorkspace(Workspace='Up_can')
            DeleteWorkspace(Workspace='Down_can')
            DeleteWorkspace(Workspace='centre_can')

        DeleteWorkspace(Workspace='centre')
        self._last_pos = trial

        # prepare the workspaces for "publication", after they have their
        # standard names calculations will be done on them and they will be plotted
        for out_wksp in self.QUADS:
            in_wksp = out_wksp+'_tmp'
            ReplaceSpecialValues(InputWorkspace=in_wksp,OutputWorkspace=in_wksp,NaNValue=0,InfinityValue=0)
            rem_nans = StripEndNans()
            rem_nans.execute(setup, in_wksp)

            RenameWorkspace(InputWorkspace=in_wksp,OutputWorkspace= out_wksp)

        return self._calculate_residue()

    def move(self, setup, x, y):
        """
            Move the selected detector in both the can and sample workspaces, remembering the
            that ISIS SANS team see the detector from the other side
            @param setup: the reduction chain object that contains information about the reduction
            @param x: the distance to move in the x (-x) direction in metres
            @param y: the distance to move in the y (-y) direction in metres
        """
        # Displacing the beam by +5 is equivalent to displacing the isntrument by -5. Hence we change
        # the sign here. LARMOR does this correction in the instrument itself, while for the others
        # we don't
        x = self.sign_coord1*x
        y = self.sign_coord2*y

#.........这里部分代码省略.........
开发者ID:liyulun,项目名称:mantid,代码行数:101,代码来源:centre_finder.py


示例13: __init__

 def __init__(self, parent_presenter):
     super(SettingsDiagnosticPresenter, self).__init__()
     self._view = None
     self._parent_presenter = parent_presenter
     # Logger
     self.gui_logger = Logger("SANS GUI LOGGER")
开发者ID:samueljackson92,项目名称:mantid,代码行数:6,代码来源:settings_diagnostic_presenter.py


示例14: MaskingTablePresenter

class MaskingTablePresenter(object):
    DISPLAY_WORKSPACE_NAME = "__sans_mask_display_dummy_workspace"

    class ConcreteMaskingTableListener(MaskingTable.MaskingTableListener):
        def __init__(self, presenter):
            super(MaskingTablePresenter.ConcreteMaskingTableListener, self).__init__()
            self._presenter = presenter

        def on_row_changed(self):
            self._presenter.on_row_changed()

        def on_update_rows(self):
            self._presenter.on_update_rows()

        def on_display(self):
            self._presenter.on_display()

    class DisplayMaskListener(WorkHandler.WorkListener):
        def __init__(self, presenter):
            super(MaskingTablePresenter.DisplayMaskListener, self).__init__()
            self._presenter = presenter

        def on_processing_finished(self, result):
            self._presenter.on_processing_finished_masking_display(result)

        def on_processing_error(self, error):
            self._presenter.on_processing_error_masking_display(error)

    def __init__(self, parent_presenter):
        super(MaskingTablePresenter, self).__init__()
        self._view = None
        self._parent_presenter = parent_presenter
        self._work_handler = WorkHandler()
        self._logger = Logger("SANS")

    def on_row_changed(self):
        row_index = self._view.get_current_row()
        state = self.get_state(row_index, file_lookup=False)
        if state:
            self.display_masking_information(state)

    def on_display(self):
        # Get the state information for the selected row.
        # Disable the button
        self._view.set_display_mask_button_to_processing()

        try:
            row_index = self._view.get_current_row()
            state = self.get_state(row_index)
        except Exception as e:
            self.on_processing_error_masking_display(e)
            raise Exception(str(e))  # propagate errors for run_tab_presenter to deal with
        else:
            if not state:
                self._logger.information("You can only show a masked workspace if a user file has been loaded and there"
                                         "valid sample scatter entry has been provided in the selected row.")
                return

            # Run the task
            listener = MaskingTablePresenter.DisplayMaskListener(self)
            state_copy = copy.copy(state)
            self._work_handler.process(listener, load_and_mask_workspace, 0, state_copy, self.DISPLAY_WORKSPACE_NAME)

    def on_processing_finished_masking_display(self, result):
        # Enable button
        self._view.set_display_mask_button_to_normal()

        # Display masked workspace
        self._display(result)

    def on_processing_error_masking_display(self, error):
        self._logger.warning("There has been an error. See more: {}".format(error))
        # Enable button
        self._view.set_display_mask_button_to_normal()

    def on_processing_error(self, error):
        pass

    def on_update_rows(self):
        """
        Update the row selection in the combobox
        """
        current_row_index = self._view.get_current_row()
        valid_row_indices = self._parent_presenter.get_row_indices()

        new_row_index = -1
        if current_row_index in valid_row_indices:
            new_row_index = current_row_index
        elif len(valid_row_indices) > 0:
            new_row_index = valid_row_indices[0]

        self._view.update_rows(valid_row_indices)

        if new_row_index != -1:
            self.set_row(new_row_index)
            self.on_row_changed()

    def set_row(self, index):
        self._view.set_row(index)

#.........这里部分代码省略.........
开发者ID:samueljackson92,项目名称:mantid,代码行数:101,代码来源:masking_table_presenter.py


示例15: __init__

 def __init__(self, parent_presenter):
     super(MaskingTablePresenter, self).__init__()
     self._view = None
     self._parent_presenter = parent_presenter
     self._work_handler = WorkHandler()
     self._logger = Logger("SANS")
开发者ID:samueljackson92,项目名称:mantid,代码行数:6,代码来源:masking_table_presenter.py


示例16: ErrorReporterPresenter

class ErrorReporterPresenter(object):
    def __init__(self, view, exit_code):
        self.error_log = Logger("error")
        self._view = view
        self._exit_code = exit_code
        self._view.set_report_callback(self.error_handler)

    def do_not_share(self, continue_working=True):
        self.error_log.notice("No information shared")
        self._handle_exit(continue_working)
        return -1

    def share_non_identifiable_information(self, continue_working):
        uptime = UsageService.getUpTime()
        status = self._send_report_to_server(share_identifiable=False, uptime=uptime)
        self.error_log.notice("Sent non-identifiable information")
        self._handle_exit(continue_working)
        return status

    def share_all_information(self, continue_working, name, email, text_box):
        uptime = UsageService.getUpTime()
        try:
            recovery_archive, file_hash = zip_recovery_directory()
        except Exception as exc:
            self.error_log.information("Error creating recovery archive: {}. No recovery information will be sent")
            recovery_archive, file_hash = None, ""
        status = self._send_report_to_server(share_identifiable=True, uptime=uptime, name=name, email=email, file_hash=file_hash,
                                             text_box=text_box)
        self.error_log.notice("Sent full information")
        if status == 201 and recovery_archive:
            self._upload_recovery_file(recovery_archive=recovery_archive)
            try:
                os.remove(recovery_archive)
            except OSError as exc:
                self.error_log.information("Unable to remove zipped recovery information: {}".format(str(exc)))

        self._handle_exit(continue_working)
        return status

    def error_handler(self, continue_working, share, name, email, text_box):
        if share == 0:
            status = self.share_all_information(continue_working, name, email, text_box)
        elif share == 1:
            status = self.share_non_identifiable_information(continue_working)
        elif share == 2:
            status = self.do_not_share(continue_working)
        else:
            self.error_log.error("Unrecognised signal in errorreporter exiting")
            self._handle_exit(continue_working)
            status = -2

        return status

    def _handle_exit(self, continue_working):
        if not continue_working:
            self.error_log.error("Terminated by user.")
            self._view.quit()
        else:
            self.error_log.error("Continue working.")

    def _upload_recovery_file(self, recovery_archive):
        url = ConfigService['errorreports.rooturl']
        url = '{}/api/recovery'.format(url)
        files = {'file': open('{}'.format(recovery_archive), 'rb')}
        response = requests.post(url, files=files)
        if response.status_code == 201:
            self.error_log.notice("Uploaded recovery file to server. HTTP response {}".format(response.status_code))
        else:
            self.error_log.error("Failed to send recovery data HTTP response {}".format(response.status_code))

    def _send_report_to_server(self, share_identifiable=False, name='', email='', file_hash='', uptime='', text_box=''):
        errorReporter = ErrorReporter(
            "mantidplot", uptime, self._exit_code, share_identifiable, str(name), str(email), str(text_box),
            str(file_hash))
        status = errorReporter.sendErrorReport()

        if status != 201:
            self._view.display_message_box('Error contacting server', 'There was an error when sending the report.'
                                                                      'Please contact [email protected] directly',
                                           'http request returned with status {}'.format(status))
            self.error_log.error("Failed to send error report http request returned status {}".format(status))

        return status

    def show_view(self):
        self._view.show()
开发者ID:samueljackson92,项目名称:mantid,代码行数:86,代码来源:error_report_presenter.py


示例17: __init__

 def __init__(self, view, exit_code):
     self.error_log = Logger("error")
     self._view = view
     self._exit_code = exit_code
     self._view.set_report_callback(self.error_handler)
开发者ID:samueljackson92,项目名称:mantid,代码行数:5,代码来源:error_report_presenter.py


示例18: reload

from mantid import *
import numpy as np
import os, csv, math
from mantid.kernel import Logger

import BilbyCustomFunctions_Reduction
reload (BilbyCustomFunctions_Reduction)

ansto_logger = Logger("AnstoDataReduction")

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# INPUT - mandatory from a USER - START
###########################################################################################
red_settings = FileFinder.getFullPath('settings_csv_5779.csv')

#mantid_reduction_input_latex_shp.csv
#settings_csv_peptides

# INPUT - index of a line with reduction parameters
index_reduction_settings = ["2"] # INDEX OF THE LINE WITH REDUCTION SETTINGS
    
if len(index_reduction_settings) > 1: # must be single choice
    raise ValueError('Please check your choice of reduction settigns; only single value is allowed')    

# ID to evaluate - INPUT, in any combination of 'a-b' or ',c', or empty line; empty line means evaluate all files listed in csv
index_files_to_reduce = "98"  # as per csv_files_to_reduce_list file - LINES' INDEXES FOR FILES TO BE REDUCED

# Data file with numbers 
path_tube_shift_correction = FileFinder.getFullPath('shift_assembled.csv')

###########################################################################################
开发者ID:mantidproject,项目名称:scriptrepository,代码行数:31,代码来源:reducer_generic_final.py


示例19: PyExec

    def PyExec(self):
        state = self._get_state()
        state_serialized = state.property_manager
        logger = Logger("CentreFinder")
        logger.notice("Starting centre finder routine...")
        progress = self._get_progress()
        self.scale_1 = 1000
        self.scale_2 = 1000
        verbose = self.getProperty('Verbose').value
        x_start = self.getProperty("Position1Start").value
        y_start = self.getProperty("Position2Start").value

        sample_scatter = self._get_cloned_workspace("SampleScatterWorkspace")
        sample_scatter_monitor = self._get_cloned_workspace("SampleScatterMonitorWorkspace")
        sample_transmission = self._get_cloned_workspace("SampleTransmissionWorkspace")
        sample_direct = self._get_cloned_workspace("SampleDirectWorkspace")

        instrument = sample_scatter.getInstrument()
        if instrument.getName() == 'LARMOR':
            self.scale_1 = 1.0

        can_scatter = self._get_cloned_workspace("CanScatterWorkspace")
        can_scatter_monitor = self._get_cloned_workspace("CanScatterMonitorWorkspace")
        can_transmission = self._get_cloned_workspace("CanTransmissionWorkspace")
        can_direct = self._get_cloned_workspace("CanDirectWorkspace")

        component = self.getProperty("Component").value
        tolerance = self.getProperty("Tolerance").value
        max_iterations = self.getProperty("Iterations").value

        r_min = self.getProperty("RMin").value
        r_max = self.getProperty("RMax").value

        instrument_file = get_instrument_paths_for_sans_file(state.data.sample_scatter)
        position_1_step = get_named_elements_from_ipf_file(
            instrument_file[1], ["centre-finder-step-size"], float)['centre-finder-step-size']
        try:
            position_2_step = get_named_elements_from_ipf_file(
                instrument_file[1], ["centre-finder-step-size2"], float)['centre-finder-step-size2']
        except:
            position_2_step = position_1_step

        find_direction = self.getProperty("Direction").value
        if find_direction == FindDirectionEnum.to_string(FindDirectionEnum.Left_Right):
            position_2_step = 0.0
        elif find_direction == FindDirectionEnum.to_string(FindDirectionEnum.Up_Down):
            position_1_step = 0.0
        centre1 = x_start
        centre2 = y_start
        residueLR = []
        residueTB = []
        centre_1_hold = x_start
        centre_2_hold = y_start
        for j in range(0, max_iterations + 1):
            if(j != 0):
                centre1 += position_1_step
                centre2 += position_2_step

            progress.report("Reducing ... Pos1 " + str(centre1) + " Pos2 " + str(centre2))
            sample_quartiles = self._run_quartile_reduction(sample_scatter, sample_transmission, sample_direct,
                                                            "Sample", sample_scatter_monitor, component,
                                                            state_serialized, centre1, centre2, r_min, r_max)

            if can_scatter:
                can_quartiles = self._run_quartile_reduction(can_scatter, can_transmission, can_direct, "Can",
                                                             can_scatter_monitor, component, state_serialized, centre1,
                                                             centre2, r_min, r_max)
                for key in sample_quartiles:
                    sample_quartiles[key] = perform_can_subtraction(sample_quartiles[key], can_quartiles[key], self)

            if mantidplot:
                output_workspaces = self._publish_to_ADS(sample_quartiles)
                if verbose:
                    self._rename_and_group_workspaces(j, output_workspaces)

            residueLR.append(self._calculate_residuals(sample_quartiles[MaskingQuadrant.Left],
                                                       sample_quartiles[MaskingQuadrant.Right]))
            residueTB.append(self._calculate_residuals(sample_quartiles[MaskingQuadrant.Top],
                                                       sample_quartiles[MaskingQuadrant.Bottom]))
            if(j == 0):
                logger.notice("Itr {0}: ( {1}, {2} )  SX={3:.5g}  SY={4:.5g}".
                              format(j, self.scale_1 * centre1, self.scale_2 * centre2, residueLR[j], residueTB[j]))
                if mantidplot:
                    self._plot_quartiles(output_workspaces, state.data.sample_scatter)

            else:
                # have we stepped across the y-axis that goes through the beam center?
                if residueLR[j] > residueLR[j-1]:
                    # yes with stepped across the middle, reverse direction and half the step size
                    position_1_step = - position_1_step / 2
                if residueTB[j] > residueTB[j-1]:
                    position_2_step = - position_2_step / 2

                logger.notice("Itr {0}: ( {1}, {2} )  SX={3:.5g}  SY={4:.5g}".
                              format(j, self.scale_1 * centre1, self.scale_2 * centre2, residueLR[j], residueTB[j]))

                if (residueLR[j]+residueTB[j]) < (residueLR[j-1]+residueTB[j-1]) or state.compatibility.use_compatibility_mode:
                    centre_1_hold = centre1
                    centre_2_hold = centre2

#.........这里部分代码省略.........
开发者ID:samueljackson92,项目名称:mantid,代码行数:101,代码来源:SANSBeamCentreFinder.py


示例20: SettingsDiagnosticPresenter

class SettingsDiagnosticPresenter(object):
    class ConcreteSettingsDiagnosticTabListener(SettingsDiagnosticTab.SettingsDiagnosticTabListener):
        def __init__(self, presenter):
            super(SettingsDiagnosticPresenter.ConcreteSettingsDiagnosticTabListener, self).__init__()
            self._presenter = presenter

        def on_row_changed(self):
            self._presenter.on_row_changed()

        def on_update_rows(self):
            self._presenter.on_update_rows()

        def on_collapse(self):
            self._presenter.on_collapse()

        def on_expand(self):
            self._presenter.on_expand()

        def on_save_state_to_file(self):
            self._presenter.on_save_state()

    def __init__(self, parent_presenter):
        super(SettingsDiagnosticPresenter, self).__init__()
        self._view = None
        self._parent_presenter = parent_presenter
        # Logger
        self.gui_logger = Logger("SANS GUI LOGGER")

    def on_collapse(self):
        self._view.collapse()

    def on_expand(self):
        self._view.expand()

    def on_row_changed(self):
        try:
            row_index = self._view.get_current_row()
            state = self.get_state(row_index)
            if state:
                self.display_state_diagnostic_tree(state)
        except RuntimeError as e:
            self.gui_logger.error(str(e))
            self._parent_presenter.display_warning_box('Warning', 'Unable to find files.', str(e))

    def on_update_rows(self):
        """
        Update the row selection in the combobox
        """
        current_row_index = self._view.get_current_row()
        valid_row_indices = self._parent_presenter.get_row_indices()

        new_row_index = -1
        if current_row_index in valid_row_indices:
            new_row_index = current_row_index
        elif len(valid_row_indices) > 0:
            new_row_index = valid_row_indices[0]

        self._view.update_rows(valid_row_indices)

        if new_row_index != -1:
            self.set_row(new_row_index)
            self.on_row_changed()

    def set_row(self, index):
        self._view.set_row(index)

    def set_view(self, view):
        if view:
            self._view = view

            # Set up row selection listener
            listener = SettingsDiagnosticPresenter.ConcreteSettingsDiagnosticTabListener(self)
            self._view.add_listener(listener)

            # Set the default gui
            self._set_default_gui()

    def _set_default_gui(self):
        self._view.update_rows([])
        self.display_state_diagnostic_tree(state=None)

    def get_state(self, index):
        return self._parent_presenter.get_state_for_row(index)

    def display_state_diagnostic_tree(self, state):
        # Convert to dict before passing the state to the view
        if state is not None:
            state = state.property_manager
        self._view.set_tree(state)

    def on_save_state(self):
        # Get the save location
        save_location = self._view.get_save_location()
        # Check if it exists
        path_dir = os.path.dirname(save_location)
        if not path_dir:
            self.gui_logger.warning("The provided save location for the SANS state does not seem to exist. "
                                    "Please provide a validate path")
            return

#.........这里部分代码省略.........
开发者ID:samueljackson92,项目名称:mantid,代码行数:101,代码来源:settings_diagnostic_presenter.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python logger.debug函数代码示例发布时间:2022-05-27
下一篇:
Python kernel.ConfigService类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap