Exemple #1
0
    def format_exception(self, e) -> List[dict]:
        from markdown import markdown

        if e.__cause__ is not None:
            result = self.format_exception(e.__cause__)
            result[-1]["tail"] = traceback._cause_message
        elif e.__context__ is not None and not e.__suppress_context__:
            result = self.format_exception(e.__context__)
            result[-1]["tail"] = traceback._context_message
        else:
            result = []

        result.append(
            dict(
                frames=self.format_stack(e.__traceback__),
                exception=dict(
                    type=type(e).__name__,
                    message=traceback._some_str(e),
                ),
                tail="",
                didyoumean=didyoumean_suggestions(e),
                friendly=markdown(friendly_message(e, double_newline=True)),
            )
        )
        return result
Exemple #2
0
    def GetExpectedTracebackMessage(self, actual_exception):
        # Getting the type of the "actual exception" because its type might be different than self.exception_type
        reraised_exception_name = type(actual_exception).__name__
        exception_message = self.GetExpectedExceptionMessage()

        if self.expected_traceback_message is not None:
            exception_message = self.expected_traceback_message
        else:
            exception_message = reraised_exception_name + ": " + exception_message + "\n"

        # HACK [muenz]: the 'traceback' module does this, so in order to be able to compare strings we need this workaround
        # notice that if the exception "leaks" the Python console handles the unicode symbols properly
        exception_message = traceback._some_str(exception_message)
        assert type(exception_message) == bytes

        return exception_message
Exemple #3
0
    def GetExpectedTracebackMessage(self,
                                    actual_exception,
                                    use_utf_8_encoding=True):
        # Getting the type of the "actual exception" because its type might be different than self.exception_type
        reraised_exception_name = type(actual_exception).__name__
        exception_message = self.GetExpectedExceptionMessage()

        if self.expected_traceback_message is not None:
            exception_message = self.expected_traceback_message
        else:
            exception_message = (reraised_exception_name + ": " +
                                 exception_message + "\n")

        # HACK [muenz]: the 'traceback' module does this, so in order to be able to compare strings we
        # need this workaround notice that if the exception "leaks" the Python console handles the
        # unicode symbols properly
        if use_utf_8_encoding:
            exception_message = exception_message.encode("utf-8")
        else:
            exception_message = traceback._some_str(exception_message)
        assert isinstance(exception_message, bytes)

        return exception_message
Exemple #4
0
    def get_expected_traceback_message(self, actual_exception):
        # Getting the type of the "actual exception" because its type might be
        # different than self.exception_type
        reraised_exception_name = type(actual_exception).__name__
        if six.PY3 and reraised_exception_name.startswith('Reraised'):
            reraised_exception_name = 'zerotk.reraiseit._reraiseit.' + \
                reraised_exception_name
        exception_message = self.get_expected_exception_message()

        if self.expected_traceback_message is not None:
            exception_message = self.expected_traceback_message
        else:
            exception_message = reraised_exception_name + ": " + \
                exception_message + "\n"

        # HACK [muenz]: the 'traceback' module does this, so in order to be
        # able to compare strings we need this workaround notice that if the
        # exception "leaks" the Python console handles the unicode symbols
        # properly
        exception_message = traceback._some_str(exception_message)
        assert type(exception_message) == MESSAGE_TYPE

        return exception_message
Exemple #5
0
    def format_exception(self, e) -> List[dict]:
        if e.__cause__ is not None:
            result = self.format_exception(e.__cause__)
            result[-1]["tail"] = traceback._cause_message
        elif e.__context__ is not None and not e.__suppress_context__:
            result = self.format_exception(e.__context__)
            result[-1]["tail"] = traceback._context_message
        else:
            result = []

        result.append(
            dict(
                frames=self.format_stack(e.__traceback__),
                exception=dict(
                    type=type(e).__name__,
                    message=traceback._some_str(e),
                ),
                tail="",
                didyoumean=didyoumean_suggestions(e),
                friendly=markdown(
                    friendly_generic(e) + "\n\n" + friendly_runtime_cause(e)),
            ))
        return result
 def __init__(self, parent, output_dir, use_cuts, elements, x_units,
              line_zero, line_scale, systematic_error):
     '''Inits widget.
     
     Args:
         parent: A MeasurementTabWidget.
         output_dir: A string representing directory in which the depth files 
                     are located.
         use_cuts: A string list representing Cut files.
         elements: A list of Element objects that are used in depth profile.
         x_units: Units to be used for x-axis of depth profile.
         line_zero: A boolean representing if vertical line is drawn at zero.
         line_scale: A boolean representing if horizontal line is drawn at 
                     the defined depth scale.
         systematic_error: A double representing systematic error.
     '''
     try:
         super().__init__()
         self.parent = parent
         self.icon_manager = parent.icon_manager
         self.measurement = parent.measurement
         self.output_dir = output_dir
         self.elements = elements
         self.x_units = x_units
         self.__use_cuts = use_cuts;
         self.__line_zero = line_zero
         self.__line_scale = line_scale
         self.__systerr = systematic_error
         self.ui = uic.loadUi(os.path.join("ui_files",
                                           "ui_depth_profile.ui"),
                              self)
         
         # Make the directory for depth files
         if not os.path.exists(self.output_dir):
             os.makedirs(self.output_dir)
         output_files = os.path.join(self.output_dir, 'depth')
         dp = DepthFiles(self.__use_cuts, output_files)
         dp.create_depth_files()
         
         # Check for RBS selections.
         rbs_list = {}
         for cut in self.__use_cuts:
             filename = os.path.basename(cut)
             split = filename.split('.')
             element = Element(split[1])
             if is_rbs(cut):
                 # This should work for regular cut and split.
                 key = "{0}.{1}.{2}".format(split[1], split[2], split[3])
                 scatter_element = get_scatter_element(cut)
                 rbs_list[key] = scatter_element
                 index = 0
                 found_scatter = False
                 for elm in elements:  # Makeshift
                     if elm == element:
                         found_scatter = True
                         break
                     index += 1
                 # When loading project, the scatter element is already 
                 # replaced. This is essentially done only when creating 
                 # a new Depth Profile graph.
                 if found_scatter:
                     elements[index] = scatter_element
         
         self.measurement.generate_tof_in()
         settings = self.measurement.measurement_settings.\
                         get_measurement_settings()
         ds = settings.depth_profile_settings
         depth_scale_from = ds.depths_for_concentration_from
         depth_scale_to = ds.depths_for_concentration_to
         self.matplotlib = MatplotlibDepthProfileWidget(self,
                                    self.output_dir,
                                    self.elements,
                                    rbs_list,
                                    (depth_scale_from, depth_scale_to),
                                    self.x_units,
                                    True,  # legend
                                    self.__line_zero,
                                    self.__line_scale,
                                    self.__systerr)
     except:
         import traceback
         msg = "Could not create Depth Profile graph. "
         err_file = sys.exc_info()[2].tb_frame.f_code.co_filename
         str_err = ", ".join([sys.exc_info()[0].__name__ + ": " + \
                       traceback._some_str(sys.exc_info()[1]),
                       err_file,
                       str(sys.exc_info()[2].tb_lineno)])
         msg += str_err
         logging.getLogger(self.measurement.measurement_name).error(msg)
         if hasattr(self, "matplotlib"):
             self.matplotlib.delete()
Exemple #7
0
 def update_event(self, inp=-1):
     self.set_output_val(0, traceback._some_str(self.input(0)))
Exemple #8
0
def tof_list(cut_file, directory, save_output=False):
    '''ToF_list 
    
    Arstila's tof_list executables interface for Python.
    
    Args:
        cut_file: A string representing cut file to be ran through tof_list.
        directory: A string representing measurement's energy spectrum directory.
        save_output: A boolean representing whether tof_list output is saved.
        
    Returns:
        Returns cut file as list transformed through Arstila's tof_list program.
    '''
    bin_dir = join(realpath(curdir), "external", "Potku-bin")
    tof_list_array = []
    if not cut_file:
        return []
    stdout = None
    try:
        if platform.system() == 'Windows':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            command = (str(join(bin_dir, "tof_list.exe")),
                       cut_file)
            stdout = subprocess.check_output(command,
                                             cwd=bin_dir,
                                             shell=True,
                                             startupinfo=startupinfo)
        else:
            command = "{0} {1}".format(join(".", "tof_list"), cut_file, bin_dir)
            p = subprocess.Popen(command.split(' ', 1), cwd=bin_dir,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            stdout, unused_stderr = p.communicate()
        
        lines = stdout.decode().strip().replace("\r", "").split("\n")
        for line in lines:
            if not line:  # Can still result in empty lines at the end, skip.
                continue
            line_split = re.split("\s+", line.strip())
            tupled = (float(line_split[0]),
                      float(line_split[1]),
                      float(line_split[2]),
                      int(line_split[3]),
                      float(line_split[4]),
                      line_split[5],
                      float(line_split[6]),
                      int(line_split[7]))
            tof_list_array.append(tupled)
        if save_output:
            if not directory:
                directory = join(realpath(curdir), "energy_spectrum_output")
            if not exists(directory):
                makedirs(directory)
            unused_dir, file = split(cut_file)
            directory_es_file = join(directory,
                                     "{0}.tof_list".format(splitext(file)[0]))
            numpy_array = numpy.array(tof_list_array,
                                         dtype=[('float1', float),
                                                ('float2', float),
                                                ('float3', float),
                                                ('int1', int),
                                                ('float4', float),
                                                ('string', numpy.str_, 3),
                                                ('float5', float),
                                                ('int2', int)])
            numpy.savetxt(directory_es_file, numpy_array,
                          delimiter=" ",
                          fmt="%5.1f %5.1f %10.5f %3d %8.4f %s %6.3f %d")  
    except:
        import traceback
        msg = "Error in tof_list: "
        err_file = sys.exc_info()[2].tb_frame.f_code.co_filename
        str_err = ", ".join([sys.exc_info()[0].__name__ + ": " + \
                      traceback._some_str(sys.exc_info()[1]),
                      err_file,
                      str(sys.exc_info()[2].tb_lineno)])
        msg += str_err
        print(msg)
    finally:
        return tof_list_array
Exemple #9
0
    def generate_tof_in(self):
        """Generate tof.in file for external programs.
        
        Generates tof.in file for measurement to be used in external programs 
        (tof_list, erd_depth).
        """
        tof_in_directory = os.path.join(os.path.realpath(os.path.curdir), "external", "Potku-bin")
        tof_in_file = os.path.join(tof_in_directory, "tof.in")

        # Get settings
        use_settings = self.measurement_settings.get_measurement_settings()
        global_settings = self.project.global_settings

        # Measurement settings
        str_beam = "Beam: {0}\n".format(use_settings.measuring_unit_settings.element)
        str_energy = "Energy: {0}\n".format(use_settings.measuring_unit_settings.energy)
        str_detector = "Detector angle: {0}\n".format(use_settings.measuring_unit_settings.detector_angle)
        str_target = "Target angle: {0}\n".format(use_settings.measuring_unit_settings.target_angle)
        str_toflen = "Toflen: {0}\n".format(use_settings.measuring_unit_settings.time_of_flight_length)
        str_carbon = "Carbon foil thickness: {0}\n".format(use_settings.measuring_unit_settings.carbon_foil_thickness)
        str_density = "Target density: {0}\n".format(use_settings.measuring_unit_settings.target_density)

        # Depth Profile settings
        str_depthnumber = "Number of depth steps: {0}\n".format(
            use_settings.depth_profile_settings.number_of_depth_steps
        )
        str_depthstop = "Depth step for stopping: {0}\n".format(
            use_settings.depth_profile_settings.depth_step_for_stopping
        )
        str_depthout = "Depth step for output: {0}\n".format(use_settings.depth_profile_settings.depth_step_for_output)
        str_depthscale = "Depths for concentration scaling: {0} {1}\n".format(
            use_settings.depth_profile_settings.depths_for_concentration_from,
            use_settings.depth_profile_settings.depths_for_concentration_to,
        )

        # Cross section
        flag_cross = global_settings.get_cross_sections()
        str_cross = "Cross section: {0}\n".format(flag_cross)
        # Cross Sections: 1=Rutherford, 2=L'Ecuyer, 3=Andersen

        str_num_iterations = "Number of iterations: {0}\n".format(global_settings.get_num_iterations())

        # Efficiency directory
        eff_directory = global_settings.get_efficiency_directory()
        str_eff_dir = "Efficiency directory: {0}".format(eff_directory)

        # Combine strings
        measurement = str_beam + str_energy + str_detector + str_target + str_toflen + str_carbon + str_density
        calibration = "TOF calibration: {0} {1}\n".format(
            use_settings.calibration_settings.slope, use_settings.calibration_settings.offset
        )
        anglecalibration = "Angle calibration: {0} {1}\n".format(
            use_settings.calibration_settings.angleslope, use_settings.calibration_settings.angleoffset
        )
        depthprofile = str_depthnumber + str_depthstop + str_depthout + str_depthscale

        tof_in = (
            measurement + calibration + anglecalibration + depthprofile + str_cross + str_num_iterations + str_eff_dir
        )

        # Get md5 of file and new settings
        md5 = hashlib.md5()
        md5.update(tof_in.encode("utf8"))
        digest = md5.digest()
        digest_file = None
        if os.path.isfile(tof_in_file):
            f = open(tof_in_file, "r")
            digest_file = md5_for_file(f)
            f.close()

        # If different back up old tof.in and generate a new one.
        if digest_file != digest:
            # Try to back up old file.
            try:
                new_file = "{0}_{1}.bak".format(tof_in_file, time.strftime("%Y-%m-%d_%H.%M.%S"))
                shutil.copyfile(tof_in_file, new_file)
                back_up_msg = "Backed up old tof.in file to {0}".format(os.path.realpath(new_file))
                logging.getLogger(self.measurement_name).info(back_up_msg)
            except:
                import traceback

                err_file = sys.exc_info()[2].tb_frame.f_code.co_filename
                str_err = ", ".join(
                    [
                        sys.exc_info()[0].__name__ + ": " + traceback._some_str(sys.exc_info()[1]),
                        err_file,
                        str(sys.exc_info()[2].tb_lineno),
                    ]
                )
                error_msg = "Unexpected error when generating tof.in: {0}".format(str_err)
                logging.getLogger(self.measurement_name).error(error_msg)
            # Write new settings to the file.
            with open(tof_in_file, "wt+") as fp:
                fp.write(tof_in)
            str_logmsg = "Generated tof.in with params> {0}".format(tof_in.replace("\n", "; "))
            logging.getLogger(self.measurement_name).info(str_logmsg)
    def __init__(self, parent, reference_cut_file, checked_cuts, partition_count, y_scale):
        """Inits widget.
        
        Args:
            parent: MeasurementTabWidget
            reference_cut_file: String representing reference cut file.
            checked_cuts: String list representing cut files.
            partition_count: Integer representing how many splits cut files 
                             are divided to.
            y_scale: Integer flag representing how Y axis is scaled.
        """
        try:
            super().__init__()
            self.parent = parent
            self.icon_manager = parent.icon_manager
            self.measurement = self.parent.measurement
            self.reference_cut_file = reference_cut_file
            self.checked_cuts = checked_cuts
            self.partition_count = partition_count
            self.y_scale = y_scale
            # TODO: Use Null with GUI ProgresBar.
            if self.measurement.statusbar:
                self.progress_bar = QtGui.QProgressBar()
                self.measurement.statusbar.addWidget(self.progress_bar, 1)
                self.progress_bar.show()
                QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents)
                # Mac requires event processing to show progress bar and its
                # process.
            else:
                self.progress_bar = None

            self.ui = uic.loadUi(os.path.join("ui_files", "ui_element_losses.ui"), self)
            title = "{0} - Reference cut: {1}".format(self.ui.windowTitle(), os.path.basename(self.reference_cut_file))
            self.ui.setWindowTitle(title)
            # Calculate elemental losses
            self.losses = ElementLosses(
                self.measurement.directory_cuts,
                self.measurement.directory_elemloss,
                self.reference_cut_file,
                self.checked_cuts,
                self.partition_count,
                progress_bar=self.progress_bar,
            )
            self.split_counts = self.losses.count_element_cuts()

            # Check for RBS selections.
            rbs_list = {}
            for cut in self.checked_cuts:
                filename = os.path.basename(cut)
                split = filename.split(".")
                if is_rbs(cut):
                    # This should work for regular cut and split.
                    key = "{0}.{1}.{2}".format(split[1], split[2], split[3])
                    rbs_list[key] = get_scatter_element(cut)

            # Connect buttons
            self.ui.splitSaveButton.clicked.connect(self.__save_splits)

            self.matplotlib = MatplotlibElementLossesWidget(
                self, self.split_counts, legend=True, y_scale=y_scale, rbs_list=rbs_list
            )
        except:
            import traceback

            msg = "Could not create Elemental Losses graph. "
            err_file = sys.exc_info()[2].tb_frame.f_code.co_filename
            str_err = ", ".join(
                [
                    sys.exc_info()[0].__name__ + ": " + traceback._some_str(sys.exc_info()[1]),
                    err_file,
                    str(sys.exc_info()[2].tb_lineno),
                ]
            )
            msg += str_err
            logging.getLogger(self.measurement.measurement_name).error(msg)
            if hasattr(self, "matplotlib"):
                self.matplotlib.delete()
        finally:
            if self.progress_bar:
                self.measurement.statusbar.removeWidget(self.progress_bar)
                self.progress_bar.hide()
 def __init__(self, parent, use_cuts, width):
     '''Inits widget.
     
     Args:
         parent: A MeasurementTabWidget.
         use_cuts: A string list representing Cut files.
         width: A float representing Energy Spectrum histogram's bin width.
     '''
     try:
         super().__init__()
         self.parent = parent
         self.icon_manager = parent.icon_manager
         self.measurement = self.parent.measurement
         self.use_cuts = use_cuts
         self.width = width
         if self.measurement.statusbar:
             self.progress_bar = QtGui.QProgressBar()
             self.measurement.statusbar.addWidget(self.progress_bar, 1) 
             self.progress_bar.show()
             QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents)
             # Mac requires event processing to show progress bar and its 
             # process.
         else:
             self.progress_bar = None
         self.ui = uic.loadUi(os.path.join("ui_files",
                                           "ui_energy_spectrum.ui"),
                              self)
         title = "{0} - Bin Width: {1}".format(self.ui.windowTitle(), width)
         self.ui.setWindowTitle(title)
         
         # Generate new tof.in file for external programs
         self.measurement.generate_tof_in()
         # Do energy spectrum stuff on this
         self.energy_spectrum = EnergySpectrum(self.measurement,
                                               use_cuts,
                                               width,
                                               progress_bar=self.progress_bar)
         self.energy_spectrum_data = self.energy_spectrum.calculate_spectrum()
         
         # Check for RBS selections.
         rbs_list = {}
         for cut in self.use_cuts:
             filename = os.path.basename(cut)
             split = filename.split('.')
             if is_rbs(cut):
                 # This should work for regular cut and split.
                 key = "{0}.{1}.{2}".format(split[1], split[2], split[3])
                 rbs_list[key] = get_scatter_element(cut)
         
         # Graph in matplotlib widget and add to window
         self.matplotlib = MatplotlibEnergySpectrumWidget(
                                              self,
                                              self.energy_spectrum_data,
                                              rbs_list)
     except:
         import traceback
         msg = "Could not create Energy Spectrum graph. "
         err_file = sys.exc_info()[2].tb_frame.f_code.co_filename
         str_err = ", ".join([sys.exc_info()[0].__name__ + ": " + \
                       traceback._some_str(sys.exc_info()[1]),
                       err_file,
                       str(sys.exc_info()[2].tb_lineno)])
         msg += str_err
         logging.getLogger(self.measurement.measurement_name).error(msg)
         if hasattr(self, "matplotlib"):
             self.matplotlib.delete()
     finally:
         if self.progress_bar:
             self.measurement.statusbar.removeWidget(self.progress_bar)
             self.progress_bar.hide()