當前位置: 首頁>>代碼示例>>Python>>正文


Python Logger.notice方法代碼示例

本文整理匯總了Python中mantid.kernel.Logger.notice方法的典型用法代碼示例。如果您正苦於以下問題:Python Logger.notice方法的具體用法?Python Logger.notice怎麽用?Python Logger.notice使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mantid.kernel.Logger的用法示例。


在下文中一共展示了Logger.notice方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_unicode_logger

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]
    def test_unicode_logger(self):
        logger = Logger("LoggerTest")
        self.assertTrue(isinstance(logger, Logger))
        for att in ['fatal', 'error', 'warning', 'notice', 'information', 'debug']:
            if not hasattr(logger, att):
                self.fail("Logger object does not have the required attribute '%s'" % att)

        logger.fatal('This is a test')
        logger.error('This is a test')
        logger.warning('This is a test')
        logger.notice('This is a test')
        logger.information('This is a test')
        logger.debug('This is a test')
開發者ID:mantidproject,項目名稱:mantid,代碼行數:15,代碼來源:LoggerTest.py

示例2: find_beam_centre

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]
    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,代碼行數:43,代碼來源:beam_centre_model.py

示例3: BeamCenterLogger

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]
class BeamCenterLogger(object):
    '''
    Logger during the beam centre operation. The logging will
    depend partially on the type of the first coordinate, ie [m, m] or [degree, m].
    It will also perform a correction for potential offsets like bench rotations.
    '''
    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

    def report_init(self, coord1, coord2):
        '''
        Report the initial setup
        @param coord1: the first coordinate
        @param coord2: the second coordinate
        '''
        if self.using_angle:
            initial_msg = "beta_start"
        else:
            initial_msg = "x_start"
        # We need to substract the offset from the coordinate, since we do not want to display the offset
        # which is on the data
        val1 = (coord1 - self.offset_coord1)*self.coord1_scale_factor
        val2 = (coord2 - self.offset_coord2)*self.coord2_scale_factor

        msg = initial_msg + ",ystart= %s    %s" % (str(val1), str(val2))
        self.logger.notice(msg)
        self.logger.notice("Starting centre finding routine ...")

    def report_status(self, iteration, coord1, coord2, resid1, resid2):  #pylint: disable=too-many-arguments
        '''
        Report the status of a beam finder iteration
        @param iteration: the number of the iteration
        @param coord1: the first coordinate
        @param coord2: the second coordinate
        @param resid1: the residual of the first coordinate
        @param resid2: the residual of the second coordinate
        '''
        msg = self.get_status_message(iteration, coord1, coord2, resid1, resid2)
        self.logger.notice(msg)

    def get_status_message(self, iteration, coord1, coord2, resid1, resid2):  #pylint: disable=too-many-arguments
        '''
        Report the status of a beam finder iteration
        @param iteration: the number of the iteration
        @param coord1: the first coordinate
        @param coord2: the second coordinate
        @param resid1: the residual of the first coordinate
        @param resid2: the residual of the second coordinate
        '''
        # We need to substract the offset from the coordinate, since we do not want to display the offset
        # which is on the data
        val1 = (coord1 - self.offset_coord1)* self.coord1_scale_factor
        val2 = (coord2 - self.offset_coord2)* self.coord2_scale_factor
        coord1str = str(val1).ljust(10)[0:9]
        coord2str = str(val2).ljust(10)[0:9]
        res1str = str(resid1).ljust(7)[0:6]
        res2str = str(resid2).ljust(7)[0:6]
        msg = "Itr %i: (%s,   %s)    SX=%s   SY=%s" %(iteration, coord1str, coord2str, res1str, res2str)
        return msg

    def report(self, msg):
        '''
        Report a general message
        @param msg: the message to report
        '''
        self.logger.notice(msg)

    def report_final(self, coord1, coord2):
        '''
        Report the final coordinates which are set in the reducer
        @param coord1: the first coordinate
        @param coord2: the second coordinate
        '''
        # We shouldn't need an offset correction at this point as a possible.
        # Also we need to multiply both entries with the same (1000) scaling,
        # Because the first coordinate should have been corrected before
        # being passed into this method. For reporting purposes we revert this
        # correction. Also we don't need to remove the offset, since it the input
        # already has it removed.
        general_scale = self.coord2_scale_factor
        val1 = (coord1)*general_scale
        val2 = (coord2)*general_scale
        msg = "Centre coordinates updated: [ %f,  %f ]" %(val1, val2)
        self.logger.notice(msg)
開發者ID:liyulun,項目名稱:mantid,代碼行數:101,代碼來源:centre_finder.py

示例4: CentreFinder

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]

#.........這裏部分代碼省略.........
                                                                         relative_displacement = True)

    # Create a workspace with a quadrant value in it
    def _create_quadrant(self, setup, reduced_ws, quadrant, r_min, r_max, suffix):
        out_ws = quadrant+suffix
        # Need to create a copy because we're going to mask 3/4 out and that's a one-way trip
        CloneWorkspace(InputWorkspace=reduced_ws,OutputWorkspace= out_ws)

        objxml = SANSUtility.QuadrantXML([0, 0, 0.0], r_min, r_max, quadrant)
        # Mask out everything outside the quadrant of interest
        MaskDetectorsInShape(Workspace=out_ws,ShapeXML= objxml)

        setup.to_Q.execute(setup, out_ws)
        #Q1D(output,rawcount_ws,output,q_bins,AccountForGravity=GRAVITY)

    # Create 4 quadrants for the centre finding algorithm and return their names
    def _group_into_quadrants(self, setup, input_value, suffix=''):
        r_min = setup.CENT_FIND_RMIN
        r_max = setup.CENT_FIND_RMAX

        for q in self.QUADS:
            self._create_quadrant(setup, input_value, q, r_min, r_max, suffix)

    def _calculate_residue(self):
        """
            Calculate the sum squared difference between pairs of workspaces named Left, Right, Up
            and Down. This assumes that a workspace with one spectrum for each of the quadrants
            @return: difference left to right, difference up down
        """
        residueX = 0
        if self.find_direction == FindDirectionEnum.ALL or self.find_direction == FindDirectionEnum.LEFT_RIGHT:
            yvalsAX = mtd['Left'].readY(0)
            yvalsBX = mtd['Right'].readY(0)
            qvalsAX = mtd['Left'].readX(0)
            qvalsBX = mtd['Right'].readX(0)
            qrangeX = [len(yvalsAX), len(yvalsBX)]
            nvalsX = min(qrangeX)
            id1X = "LR1"
            id2X = "LR2"
            residueX = self._residual_calculation_for_single_direction(yvalsA = yvalsAX,
                                                                       yvalsB = yvalsBX,
                                                                       qvalsA = qvalsAX,
                                                                       qvalsB = qvalsBX,
                                                                       qrange = qrangeX,
                                                                       nvals = nvalsX,
                                                                       id1 = id1X,
                                                                       id2 = id2X)

        residueY = 0
        if self.find_direction == FindDirectionEnum.ALL or self.find_direction == FindDirectionEnum.UP_DOWN:
            yvalsAY = mtd['Up'].readY(0)
            yvalsBY = mtd['Down'].readY(0)
            qvalsAY = mtd['Up'].readX(0)
            qvalsBY = mtd['Down'].readX(0)
            qrangeY = [len(yvalsAY), len(yvalsBY)]
            nvalsY = min(qrangeY)
            id1Y = "UD1"
            id2Y = "UD2"
            residueY = self._residual_calculation_for_single_direction(yvalsA = yvalsAY,
                                                                       yvalsB = yvalsBY,
                                                                       qvalsA = qvalsAY,
                                                                       qvalsB = qvalsBY,
                                                                       qrange = qrangeY,
                                                                       nvals = nvalsY,
                                                                       id1 = id1Y,
                                                                       id2 = id2Y)
        return residueX, residueY

    def _residual_calculation_for_single_direction(self, yvalsA, yvalsB, qvalsA, qvalsB, qrange, nvals, id1, id2):
        dummy_1 = qrange
        residue = 0
        indexB = 0
        for indexA in range(0, nvals):
            if qvalsA[indexA] < qvalsB[indexB]:
                self.logger.notice(id1 + " " +str(indexA)+" "+str(indexB))
                continue
            elif qvalsA[indexA] > qvalsB[indexB]:
                while qvalsA[indexA] > qvalsB[indexB]:
                    self.logger(id2 + " " +str(indexA)+" "+str(indexB))
                    indexB += 1
            if indexA > nvals - 1 or indexB > nvals - 1:
                break
            residue += pow(yvalsA[indexA] - yvalsB[indexB], 2)
            indexB += 1
        return residue

    def _get_cylinder_direction(self, workspace):
        '''
        Get the direction that the masking clyinder needs to point at. This should be the normal
        of the tilted detector bench. The original normal is along the beam axis as defined in
        the instrument definition file.
        @param workspace: the workspace with the tilted detector bench
        @returns the required direction of the cylinder axis
        '''
        ws = mtd[workspace]
        instrument = ws.getInstrument()
        quat = instrument.getComponentByName(self.detector).getRotation()
        cylinder_direction = instrument.getReferenceFrame().vecPointingAlongBeam()
        quat.rotate(cylinder_direction)
        return cylinder_direction.X(), cylinder_direction.Y(), cylinder_direction.Z()
開發者ID:liyulun,項目名稱:mantid,代碼行數:104,代碼來源:centre_finder.py

示例5: ErrorReporterPresenter

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]
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,代碼行數:88,代碼來源:error_report_presenter.py

示例6: issueWarning

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]
            continue
        except SkipReduction, reason:
            #this means that a load step failed, the warning and the fact that the results aren't there is enough for the user
            issueWarning(str(reason)+ ', skipping reduction')
            continue
        except ValueError, reason:
            issueWarning('Cannot load file :'+str(reason))
            #when we are all up to Python 2.5 replace the duplicated code below with one finally:
            delete_workspaces(raw_workspaces)
            raise

        delete_workspaces(raw_workspaces)


        if verbose:
            sanslog.notice(createColetteScript(run, format, reduced, centreit, plotresults, filename))
        # Rename the final workspace
        final_name = run['output_as']
        if final_name == '':
            final_name = reduced

        #convert the names from the default one, to the agreement
        names = [final_name]
        if combineDet == 'rear':
            names = [final_name+'_rear']
            RenameWorkspace(InputWorkspace=reduced,OutputWorkspace= final_name+'_rear')
        elif combineDet == 'front':
            names = [final_name+'_front']
            RenameWorkspace(InputWorkspace=reduced,OutputWorkspace= final_name+'_front')
        elif combineDet == 'both':
            names = [final_name+'_front', final_name+'_rear']
開發者ID:mkoennecke,項目名稱:mantid,代碼行數:33,代碼來源:SANSBatchMode.py

示例7: PyExec

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]
    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,代碼行數:103,代碼來源:SANSBeamCentreFinder.py

示例8: SANSBeamCentreFinder

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]
class SANSBeamCentreFinder(DataProcessorAlgorithm):
    def category(self):
        return 'SANS\\BeamCentreFinder'

    def summary(self):
        return 'Finds the position of the beam centre'

    def PyInit(self):
        # ----------
        # INPUT
        # ----------
        # Workspace which is to be cropped
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        self.declareProperty(MatrixWorkspaceProperty("SampleScatterWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The sample scatter data')

        self.declareProperty(MatrixWorkspaceProperty("SampleScatterMonitorWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The sample scatter monitor data')

        self.declareProperty(MatrixWorkspaceProperty("SampleTransmissionWorkspace", '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The sample transmission data')

        self.declareProperty(MatrixWorkspaceProperty("SampleDirectWorkspace", '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The sample direct data')

        self.declareProperty(MatrixWorkspaceProperty("CanScatterWorkspace", '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The can scatter data')

        self.declareProperty(MatrixWorkspaceProperty("CanScatterMonitorWorkspace", '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The can scatter monitor data')

        self.declareProperty(MatrixWorkspaceProperty("CanTransmissionWorkspace", '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The can transmission data')

        self.declareProperty(MatrixWorkspaceProperty("CanDirectWorkspace", '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The can direct data')

        # The component, i.e. HAB or LAB
        allowed_detectors = StringListValidator([DetectorType.to_string(DetectorType.LAB),
                                                 DetectorType.to_string(DetectorType.HAB)])
        self.declareProperty("Component", DetectorType.to_string(DetectorType.LAB),
                             validator=allowed_detectors, direction=Direction.Input,
                             doc="The component of the instrument which is to be reduced.")

        self.declareProperty("Iterations", 10, direction=Direction.Input, doc="The maximum number of iterations.")

        self.declareProperty("RMin", 0.6, direction=Direction.Input, doc="The inner radius of the quartile mask")

        self.declareProperty('RMax', 0.28, direction=Direction.Input, doc="The outer radius of the quartile mask")

        self.declareProperty('Position1Start', 0.0, direction=Direction.Input, doc="The search start position1")

        self.declareProperty('Position2Start', 0.0, direction=Direction.Input, doc="The search start position2")

        self.declareProperty('Tolerance', 0.0001251, direction=Direction.Input, doc="The search tolerance")

        self.declareProperty('Direction', FindDirectionEnum.to_string(FindDirectionEnum.All), direction=Direction.Input,
                             doc="The search direction is an enumerable which can be either All, LeftRight or UpDown")

        self.declareProperty('Verbose', False, direction=Direction.Input,
                             doc="Whether to keep workspaces from each iteration in ADS.")

        # ----------
        # Output
        # ----------
        # Workspace which is to be cropped

        self.declareProperty('Centre1', 0.0, direction=Direction.Output,
                             doc="The centre position found in the first dimension")
        self.declareProperty('Centre2', 0.0, direction=Direction.Output,
                             doc="The centre position found in the second dimension")

    def PyExec(self):
        state = self._get_state()
        state_serialized = state.property_manager
        self.logger = Logger("CentreFinder")
        self.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()
#.........這裏部分代碼省略.........
開發者ID:mantidproject,項目名稱:mantid,代碼行數:103,代碼來源:SANSBeamCentreFinder.py

示例9: ErrorReporterPresenter

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]
class ErrorReporterPresenter(object):
    SENDING_ERROR_MESSAGE = 'There was an error when sending the report.\nPlease contact [email protected] directly'

    def __init__(self, view, exit_code, application='mantidplot'):
        self.error_log = Logger("error")
        self._view = view
        self._exit_code = exit_code
        self._application = application
        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)
        self.error_log.notice("Sending recovery file to address: {}".format(url))
        files = {'file': open('{}'.format(recovery_archive), 'rb')}
        try:
            # timeout after 20 seconds to match the C++ error reporter timeout
            response = requests.post(url, files=files, timeout=20)
        except Exception as e:
            self.error_log.error(
                "Failed to send recovery data. Could not establish connection to URL: {}.\n\nFull trace:\n\n{}".format(
                    url, e))
            return

        # if this is reached, the connection was successful and some response was received
        if response.status_code == 201:
            self.error_log.notice("Uploaded recovery file to server. HTTP response {}".format(response.status_code))
        elif response.status_code == 413:
            self.error_log.notice(
                "Data was too large, and was not accepted by the 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(
            self._application, 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', self.SENDING_ERROR_MESSAGE,
                                           '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):
#.........這裏部分代碼省略.........
開發者ID:mantidproject,項目名稱:mantid,代碼行數:103,代碼來源:error_report_presenter.py

示例10: BeamCentrePresenter

# 需要導入模塊: from mantid.kernel import Logger [as 別名]
# 或者: from mantid.kernel.Logger import notice [as 別名]

#.........這裏部分代碼省略.........
        if self._beam_centre_model.update_lab:
            self._beam_centre_model.lab_pos_1 = result['pos1']
            self._beam_centre_model.lab_pos_2 = result['pos2']
            self._view.lab_pos_1 = self._beam_centre_model.lab_pos_1 * self._beam_centre_model.scale_1
            self._view.lab_pos_2 = self._beam_centre_model.lab_pos_2 * self._beam_centre_model.scale_2
        if self._beam_centre_model.update_hab:
            self._beam_centre_model.hab_pos_1 = result['pos1']
            self._beam_centre_model.hab_pos_2 = result['pos2']
            self._view.hab_pos_1 = self._beam_centre_model.hab_pos_1 * self._beam_centre_model.scale_1
            self._view.hab_pos_2 = self._beam_centre_model.hab_pos_2 * self._beam_centre_model.scale_2

    def on_processing_error_centre_finder(self, error):
        self._logger.warning("There has been an error. See more: {}".format(error))
        self._view.set_run_button_to_normal()

    def on_processing_error(self, error):
        self._view.set_run_button_to_normal()

    def on_run_clicked(self):
        # Get the state information for the first row.
        state = self._parent_presenter.get_state_for_row(0)

        if not state:
            self._logger.information("You can only calculate the beam centre if a user file has been loaded and there"
                                     "valid sample scatter entry has been provided in the selected row.")
            return

        # Disable the button
        self._view.set_run_button_to_processing()

        #Update model
        self._update_beam_model_from_view()

        # Run the task
        listener = BeamCentrePresenter.CentreFinderListener(self)
        state_copy = copy.copy(state)

        self._work_handler.process(listener, self._beam_centre_model.find_beam_centre, 0, state_copy)

    def _update_beam_model_from_view(self):
        self._beam_centre_model.r_min = self._view.r_min
        self._beam_centre_model.r_max = self._view.r_max
        self._beam_centre_model.max_iterations = self._view.max_iterations
        self._beam_centre_model.tolerance = self._view.tolerance
        self._beam_centre_model.left_right = self._view.left_right
        self._beam_centre_model.verbose = self._view.verbose
        self._beam_centre_model.COM = self._view.COM
        self._beam_centre_model.up_down = self._view.up_down
        self._beam_centre_model.lab_pos_1 = self._view.lab_pos_1 / self._beam_centre_model.scale_1
        self._beam_centre_model.lab_pos_2 = self._view.lab_pos_2 / self._beam_centre_model.scale_2
        self._beam_centre_model.hab_pos_1 = self._view.hab_pos_1 / self._beam_centre_model.scale_1
        self._beam_centre_model.hab_pos_2 = self._view.hab_pos_2 / self._beam_centre_model.scale_2
        self._beam_centre_model.q_min = self._view.q_min
        self._beam_centre_model.q_max = self._view.q_max
        self._beam_centre_model.component = self._view.component
        self._beam_centre_model.update_hab = self._view.update_hab
        self._beam_centre_model.update_lab = self._view.update_lab

    def update_centre_positions(self, state_model):
        lab_pos_1 = getattr(state_model, 'lab_pos_1')
        lab_pos_2 = getattr(state_model, 'lab_pos_2')

        hab_pos_1 = getattr(state_model, 'hab_pos_1') if getattr(state_model, 'hab_pos_1') else lab_pos_1
        hab_pos_2 = getattr(state_model, 'hab_pos_2') if getattr(state_model, 'hab_pos_2') else lab_pos_2

        self._view.lab_pos_1 = lab_pos_1
        self._view.lab_pos_2 = lab_pos_2

        self._view.hab_pos_1 = hab_pos_1
        self._view.hab_pos_2 = hab_pos_2

    def set_on_state_model(self, attribute_name, state_model):
        attribute = getattr(self._view, attribute_name)
        if attribute or isinstance(attribute, bool):
            setattr(state_model, attribute_name, attribute)

    def set_on_view(self, attribute_name, state_model):
        attribute = getattr(state_model, attribute_name)
        if attribute or isinstance(attribute, bool):  # We need to be careful here. We don't want to set empty strings, or None, but we want to set boolean values. # noqa
            setattr(self._view, attribute_name, attribute)

    def _validate_radius_values(self):
        min_value = getattr(self._view, "r_min_line_edit").text()
        max_value = getattr(self._view, "r_max_line_edit").text()

        try:
            min_value = float(min_value)
            max_value = float(max_value)
        except ValueError:
            # one of the values is empty
            pass
        else:
            if min_value >= max_value:
                if self._view.run_button.isEnabled():
                    # Only post to logger once per disabling
                    self._logger.notice("Minimum radius is larger than maximum radius. "
                                        "Cannot find beam centre with current settings.")
                    self._view.run_button.setEnabled(False)
            else:
                self._view.run_button.setEnabled(True)
開發者ID:mantidproject,項目名稱:mantid,代碼行數:104,代碼來源:beam_centre_presenter.py


注:本文中的mantid.kernel.Logger.notice方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。