Exemplo n.º 1
0
 def _on_add_constraint(self, event):
     """
     Add another line for constraint
     """
     if not self.show_constraint.GetValue():
         msg = " Select Yes to add Constraint "
         wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
         return
     # check that a constraint is added
     # before allow to add another constraint
     for item in self.constraints_list:
         if item.model_cbox.GetString(0) == "":
             msg = " Select a model Name! "
             wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
             return
         if item.param_cbox.GetString(0) == "":
             msg = " Select a parameter Name! "
             wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
             return
         if item.constraint.GetValue().lstrip().rstrip() == "":
             model = item.param_cbox.GetClientData(
                 item.param_cbox.GetCurrentSelection())
             if model is not None:
                 msg = " Enter a constraint for %s.%s! " % (
                     model.name, item.param_cbox.GetString(0))
             else:
                 msg = " Enter a constraint"
             wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
             return
     # some model or parameters can be constrained
     self._show_constraint()
     self.FitInside()
Exemplo n.º 2
0
 def set_data(self, data_list=None):
     """
     receive a list of data to compute pr
     """
     if data_list is None:
         data_list = []
     if len(data_list) >= 1:
         if len(data_list) == 1:
             data = data_list[0]
         else:
             data_1d_list = []
             data_2d_list = []
             error_msg = ""
             # separate data into data1d and data2d list
             for data in data_list:
                 if data is not None:
                     if issubclass(data.__class__, Data1D):
                         data_1d_list.append(data)
                     else:
                         error_msg += " %s type %s \n" % (str(data.name),
                                                          str(data.__class__.__name__))
                         data_2d_list.append(data)
             if len(data_2d_list) > 0:
                 msg = "PrView does not support the following data types:\n"
                 msg += error_msg
             if len(data_1d_list) == 0:
                 wx.PostEvent(self.parent, StatusEvent(status=msg, info='error'))
                 return
             msg = "Prview does not allow multiple data!\n"
             msg += "Please select one.\n"
             if len(data_list) > 1:
                 from pr_widgets import DataDialog
                 dlg = DataDialog(data_list=data_1d_list, text=msg)
                 if dlg.ShowModal() == wx.ID_OK:
                     data = dlg.get_data()
                 else:
                     data = None
                 dlg.Destroy()
         if data is None:
             msg += "PrView receives no data. \n"
             wx.PostEvent(self.parent, StatusEvent(status=msg, info='error'))
             return
         if issubclass(data.__class__, Data1D):
             try:
                 wx.PostEvent(self.parent,
                              NewPlotEvent(action='remove',
                                           group_id=GROUP_ID_IQ_DATA,
                                           id=self.data_id))
                 self.data_id = data.id
                 self.control_panel._change_file(evt=None, data=data)
             except:
                 msg = "Prview Set_data: " + str(sys.exc_value)
                 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error"))
         else:
             msg = "Pr cannot be computed for data of "
             msg += "type %s" % (data_list[0].__class__.__name__)
             wx.PostEvent(self.parent, StatusEvent(status=msg, info='error'))
     else:
         msg = "Pr contain no data"
         wx.PostEvent(self.parent, StatusEvent(status=msg, info='warning'))
Exemplo n.º 3
0
 def checkValues(self, event):
     """
     Check the valitidity of zmin and zmax value
     zmax should be a float and zmin less than zmax
     """
     flag = True
     try:
         value = self.zmin_ctl.GetValue()
         self.zmin_ctl.SetBackgroundColour(wx.WHITE)
         self.zmin_ctl.Refresh()
     except:
         flag = False
         wx.PostEvent(self.parent, StatusEvent(status="Enter float value"))
         self.zmin_ctl.SetBackgroundColour("pink")
         self.zmin_ctl.Refresh()
     try:
         value = self.zmax_ctl.GetValue()
         if value and float(value) == 0.0:
             flag = False
             wx.PostEvent(
                 self.parent,
                 StatusEvent(status="Enter number greater than zero"))
             self.zmax_ctl.SetBackgroundColour("pink")
             self.zmax_ctl.Refresh()
         else:
             self.zmax_ctl.SetBackgroundColour(wx.WHITE)
             self.zmax_ctl.Refresh()
     except:
         flag = False
         wx.PostEvent(self.parent,
                      StatusEvent(status="Enter Integer value"))
         self.zmax_ctl.SetBackgroundColour("pink")
         self.zmax_ctl.Refresh()
     if flag:
         event.Skip(True)
Exemplo n.º 4
0
 def calculate(self, event):
     """
     Calculate the mass Density/molar Volume of the molecules
     """
     self.clear_outputs()
     try:
         #Check validity user inputs
         flag, msg = self.check_inputs()
         if self.base is not None and msg.lstrip().rstrip() != "":
             msg = "Density/Volume Calculator: %s" % str(msg)
             wx.PostEvent(self.base, StatusEvent(status=msg))
         if not flag:
             return
         #get ready to compute
         mol_formula = Formula(self.compound)
         molar_mass = float(mol_formula.molecular_mass) * AVOGADRO
         output = self._format_number(molar_mass / self.input)
         self.molar_mass_ctl.SetValue(str(self._format_number(molar_mass)))
         self.output_ctl.SetValue(str(output))
     except Exception as exc:
         if self.base is not None:
             msg = "Density/Volume Calculator: %s" % exc
             wx.PostEvent(self.base, StatusEvent(status=msg))
     if event is not None:
         event.Skip()
Exemplo n.º 5
0
    def _on_invert(self, evt):
        """
        Perform inversion

        :param silent: when True, there will be no output for the user

        """
        # Get the data from the form
        # Push it to the manager

        flag, alpha, dmax, nfunc, qmin, qmax, height, width = self._read_pars()
        has_bck = self.bck_chk.IsChecked()

        if flag:
            dataset = self.plot_data.GetValue()
            if dataset is None or len(dataset.strip()) == 0:
                message = "No data to invert. Select a data set before"
                message += " proceeding with P(r) inversion."
                wx.PostEvent(self._manager.parent, StatusEvent(status=message))
            else:
                self._manager.setup_plot_inversion(alpha=alpha,
                                                   nfunc=nfunc,
                                                   d_max=dmax,
                                                   q_min=qmin,
                                                   q_max=qmax,
                                                   bck=has_bck,
                                                   height=height,
                                                   width=width)
        else:
            message = "The P(r) form contains invalid values: "
            message += "please submit it again."
            wx.PostEvent(self.parent, StatusEvent(status=message))
Exemplo n.º 6
0
    def on_load_data(self, event):
        """
            Open a file dialog to allow the user to select a given file.
            The user is only allow to load file with extension .DAT or .dat.
            Display the slit size corresponding to the loaded data.
        """
        path = self.choose_data_file(location=self._default_save_location)

        if path is None:
            return
        self._default_save_location = path
        try:
            #Load data
            from load_thread import DataReader
            ## If a thread is already started, stop it
            if self.reader is not None and self.reader.isrunning():
                self.reader.stop()
            if self.parent.parent is not None:
                wx.PostEvent(self.parent.parent,
                             StatusEvent(status="Loading...", type="progress"))
            self.reader = DataReader(path=path,
                                     completefn=self.complete_loading,
                                     updatefn=self.load_update)
            self.reader.queue()
            self.load_update()
        except:
            if self.parent.parent is None:
                return
            msg = "Slit Length Calculator: %s" % (sys.exc_value)
            wx.PostEvent(self.parent.parent,
                         StatusEvent(status=msg, type='stop'))
            return
Exemplo n.º 7
0
    def set_data(self, data_list=None):
        """
        Load the data that's been selected

        :param data_list: The data to load in
        """
        if data_list is None:
            data_list = []
        if len(data_list) >= 1:
            msg = ""
            if len(data_list) == 1:
                data = data_list[0]
            else:
                data_1d_list = []
                data_2d_list = []
                err_msg = ""

                for data in data_list:
                    if data is not None:
                        if issubclass(data.__class__, Data1D):
                            data_1d_list.append(data)
                        else:
                            err_msg += "{} type {} \n".format(str(data.name),
                                str(data.__class__))
                            data_2d_list.append(data)
                if len(data_2d_list) > 0:
                    msg = "Corfunc doesn't support the following data types:\n"
                    msg += err_msg
                if len(data_1d_list) == 0:
                    msg += "No data recieved"
                    wx.PostEvent(self.parent, StatusEvent(status=msg,
                                                info='error'))
                    return
                elif len(data_list) > 1:
                    msg = "Corfunc does not allow multiple data\n"
                    msg += "Please select one.\n"
                    dlg = DataDialog(data_list=data_1d_list, text=msg)
                    if dlg.ShowModal() == wx.ID_OK:
                        data = dlg.get_data()
                    else:
                        data = None
                    dlg.Destroy()

            if data is None:
                msg += "Corfunc recieved no data\n"
                wx.PostEvent(self.parent, StatusEvent(status=msg,
                                            info='error'))
                return
            if issubclass(data.__class__, Data1D):
                try:
                    wx.PostEvent(self.parent, NewPlotEvent(action='remove',
                                                group_id=GROUP_ID_IQ_DATA,
                                                id=self.data_id))
                    self.data_id = data.id
                    self.corfunc_panel.set_data(data)
                except:
                    msg = "Corfunc set_data: " + str(sys.exc_value)
                    wx.PostEvent(self.parent, StatusEvent(status=msg,
                        info='error'))
Exemplo n.º 8
0
 def calculateSld(self, event):
     """
         Calculate the neutron scattering density length of a molecule
     """
     self.clear_outputs()
     try:
         #Check validity user inputs
         flag, msg = self.check_inputs()
         if self.base is not None and msg.lstrip().rstrip() != "":
             msg = "SLD Calculator: %s" % str(msg)
             wx.PostEvent(self.base, StatusEvent(status=msg))
         if not flag:
             return
         #get ready to compute
         self.sld_formula = formula(self.compound, density=self.density)
         (sld_real, sld_im, _), (_, absorp, incoh), \
                     length = neutron_scattering(compound=self.compound,
                                density=self.density,
                                wavelength=self.neutron_wavelength)
         if self.xray_source == "[A]":
             energy = xray_energy(self.xray_source_input)
             xray_real, xray_im = xray_sld_from_atoms(
                 self.sld_formula.atoms,
                 density=self.density,
                 energy=energy)
         elif self.xray_source == "[keV]":
             xray_real, xray_im = xray_sld_from_atoms(
                 self.sld_formula.atoms,
                 density=self.density,
                 energy=self.xray_source_input)
         elif self.xray_source == "Element":
             xray_real, xray_im = self.calculate_sld_helper(
                 element=self.xray_source_input,
                 density=self.density,
                 molecule_formula=self.sld_formula)
         # set neutron sld values
         val = format_number(sld_real * _SCALE)
         self.neutron_sld_real_ctl.SetValue(val)
         val = format_number(math.fabs(sld_im) * _SCALE)
         self.neutron_sld_im_ctl.SetValue(val)
         # Compute the Cu SLD
         self.xray_sld_real_ctl.SetValue(format_number(xray_real * _SCALE))
         val = format_number(math.fabs(xray_im) * _SCALE)
         self.xray_sld_im_ctl.SetValue(val)
         # set incoherence and absorption
         self.neutron_inc_ctl.SetValue(format_number(incoh))
         self.neutron_abs_ctl.SetValue(format_number(absorp))
         # Neutron length
         self.neutron_length_ctl.SetValue(format_number(length))
         # display wavelength
         #self.wavelength_ctl.SetValue(str(self.wavelength))
         #self.wavelength_ctl.SetValue(str(self.wavelength))
     except:
         if self.base is not None:
             msg = "SLD Calculator: %s" % (sys.exc_value)
             wx.PostEvent(self.base, StatusEvent(status=msg))
     if event is not None:
         event.Skip()
Exemplo n.º 9
0
    def _create_plot_pr(self, estimate=False):
        """
        Create and prepare invertor instance from
        a plottable data set.

        :param path: path of the file to read in

        """
        # Sanity check
        if self.current_plottable is None:
            msg = "Please load a valid data set before proceeding."
            wx.PostEvent(self.parent, StatusEvent(status=msg))
            return None

        # Get the data from the chosen data set and perform inversion
        pr = Invertor()
        pr.d_max = self.max_length
        pr.alpha = self.alpha
        pr.q_min = self.q_min
        pr.q_max = self.q_max
        pr.x = self.current_plottable.x
        pr.y = self.current_plottable.y
        pr.est_bck = self.est_bck
        pr.slit_height = self.slit_height
        pr.slit_width = self.slit_width
        pr.background = self.bck_val

        # Keep track of the plot window title to ensure that
        # we can overlay the plots
        pr.info["plot_group_id"] = self.current_plottable.group_id

        # Fill in errors if none were provided
        err = self.current_plottable.dy
        all_zeros = True
        if err is None:
            err = np.zeros(len(pr.y))
        else:
            for i in range(len(err)):
                if err[i] > 0:
                    all_zeros = False

        if all_zeros:
            scale = None
            min_err = 0.0
            for i in range(len(pr.y)):
                # Scale the error so that we can fit over several decades of Q
                if scale is None:
                    scale = 0.05 * math.sqrt(pr.y[i])
                    min_err = 0.01 * pr.y[i]
                err[i] = scale * math.sqrt(math.fabs(pr.y[i])) + min_err
            message = "The loaded file had no error bars, "
            message += "statistical errors are assumed."
            wx.PostEvent(self.parent, StatusEvent(status=message))

        pr.err = err

        return pr
Exemplo n.º 10
0
    def _set_constraint(self):
        """
        get values from the constraint textcrtl ,parses them into model name
        parameter name and parameters values.
        store them in a list self.params .when when params is not empty
        set_model uses it to reset the appropriate model
        and its appropriates parameters
        """
        for item in self.constraints_list:
            select0 = item.model_cbox.GetSelection()
            if select0 == wx.NOT_FOUND:
                continue
            model = item.model_cbox.GetClientData(select0)
            select1 = item.param_cbox.GetSelection()
            if select1 == wx.NOT_FOUND:
                continue
            param = item.param_cbox.GetString(select1)
            constraint = item.constraint.GetValue().lstrip().rstrip()
            if param.lstrip().rstrip() == "":
                param = None
                msg = " Constraint will be ignored!. missing parameters"
                msg += " in combobox to set constraint! "
                wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
            for id, value in self.constraint_dict.items():
                if model == value:
                    if constraint == "":
                        msg = " Constraint will be ignored!. missing value"
                        msg += " in textcrtl to set constraint! "
                        wx.PostEvent(self.parent.parent,
                                     StatusEvent(status=msg))
                        constraint = None
                    if str(param) in self.page_finder[id].get_param2fit():
                        msg = " Checking constraint for parameter: %s ", param
                        wx.PostEvent(self.parent.parent,
                                     StatusEvent(info="info", status=msg))
                    else:
                        model_name = item[0].GetLabel()
                        fitpage = self.page_finder[id].get_fit_tab_caption()
                        msg = "All constrainted parameters must be set "
                        msg += " adjustable: '%s.%s' " % (model_name, param)
                        msg += "is NOT checked in '%s'. " % fitpage
                        msg += " Please check it to fit or"
                        msg += " remove the line of the constraint."
                        wx.PostEvent(self.parent.parent,
                                     StatusEvent(info="error", status=msg))
                        return False

                    for fid in self.page_finder[id].keys():
                        # wrap in param/constraint in str() to remove unicode
                        self.page_finder[id].set_model_param(str(param),
                                                             str(constraint),
                                                             fid=fid)
                    break
        return True
Exemplo n.º 11
0
    def load_abs(self, path):
        """
        Load an IGOR .ABS reduced file

        :param path: file path

        :return: x, y, err vectors

        """
        # Read the data from the data file
        data_x = np.zeros(0)
        data_y = np.zeros(0)
        data_err = np.zeros(0)
        scale = None
        min_err = 0.0

        data_started = False
        if path is not None:
            input_f = open(path, 'r')
            buff = input_f.read()
            lines = buff.split('\n')
            for line in lines:
                if data_started:
                    try:
                        toks = line.split()
                        x = float(toks[0])
                        y = float(toks[1])
                        if len(toks) > 2:
                            err = float(toks[2])
                        else:
                            if scale is None:
                                scale = 0.05 * math.sqrt(y)
                                #scale = 0.05/math.sqrt(y)
                                min_err = 0.01 * y
                            err = scale * math.sqrt(y) + min_err
                            #err = 0

                        data_x = np.append(data_x, x)
                        data_y = np.append(data_y, y)
                        data_err = np.append(data_err, err)
                    except:
                        logger.error(sys.exc_value)
                elif line.find("The 6 columns") >= 0:
                    data_started = True

        if scale is not None:
            message = "The loaded file had no error bars, statistical errors are assumed."
            wx.PostEvent(self.parent, StatusEvent(status=message))
        else:
            wx.PostEvent(self.parent, StatusEvent(status=''))

        return data_x, data_y, data_err
Exemplo n.º 12
0
    def plot_data(self, data):
        """
        Data is ready to be displayed

        :param event: data event
        """
        if data.__class__.__name__ == 'Data2D':
            return
        plot_keys = list(self.plots.keys())
        if data.id in plot_keys:
            # Recover panel prop.s
            xlo, xhi = self.subplot.get_xlim()
            ylo, yhi = self.subplot.get_ylim()
            old_data = self.plots[data.id]
            if self._is_changed_legend_label:
                data.label = old_data.label
            if old_data.__class__.__name__ == 'Data1D':
                data.custom_color = old_data.custom_color
                data.symbol = old_data.symbol
                data.markersize = old_data.markersize
                data.zorder = len(plot_keys)
            # Replace data
            self.graph.replace(data)
            self.plots[data.id] = data
            ## Set the view scale for all plots
            try:
                self._onEVT_FUNC_PROPERTY()
            except Exception as exc:
                wx.PostEvent(
                    self.parent,
                    StatusEvent(status="Plotting Error: %s" % str(exc),
                                info="error"))
            if self.is_zoomed:
                # Recover the x,y limits
                self.subplot.set_xlim((xlo, xhi))
                self.subplot.set_ylim((ylo, yhi))
        else:
            self.plots[data.id] = data
            self.graph.add(self.plots[data.id])
            data.zorder = len(plot_keys)
            ## Set the view scale for all plots
            try:
                self._onEVT_FUNC_PROPERTY()
                if IS_MAC:
                    # MAC: forcing to plot 2D avg
                    self.canvas._onDrawIdle()
            except Exception as exc:
                wx.PostEvent(self.parent, StatusEvent(status=\
                    "Plotting Error: %s" % str(exc), info="error"))
            self.toolbar.update()
            self.is_zoomed = False
Exemplo n.º 13
0
    def _on_set_all_equal(self, event):
        """
        On set button
        """
        event.Skip()
        length = len(self.constraints_list)
        if length < 1:
            return
        param_list = []
        param_list_b = []
        selection = self.model_cbox_left.GetCurrentSelection()
        model_left = self.model_cbox_left.GetValue()
        model = self.model_cbox_left.GetClientData(selection)
        selection_b = self.model_cbox_right.GetCurrentSelection()
        model_right = self.model_cbox_right.GetValue()
        model_b = self.model_cbox_right.GetClientData(selection_b)
        for id, dic_model in self.constraint_dict.items():
            if model == dic_model:
                param_list = self.page_finder[id].get_param2fit()
            if model_b == dic_model:
                param_list_b = self.page_finder[id].get_param2fit()
            if len(param_list) > 0 and len(param_list_b) > 0:
                break
        num_cbox = 0
        has_param = False
        for param in param_list:
            num_cbox += 1
            if param in param_list_b:
                item = self.constraints_list[-1]
                item.model_cbox.SetStringSelection(model_left)
                self._on_select_model(None)
                item.param_cbox.Clear()
                item.param_cbox.Append(str(param), model)
                item.param_cbox.SetStringSelection(str(param))
                item.constraint.SetValue(str(model_right + "." + str(param)))
                has_param = True
                if num_cbox == (len(param_list) + 1):
                    break
                self._show_constraint()

        self.FitInside()
        if not has_param:
            msg = " There is no adjustable parameter (checked to fit)"
            msg += " either one of the models."
            wx.PostEvent(self.parent.parent,
                         StatusEvent(info="warning", status=msg))
        else:
            msg = " The constraints are added."
            wx.PostEvent(self.parent.parent,
                         StatusEvent(info="info", status=msg))
Exemplo n.º 14
0
 def _status_info(self, msg='', type="update"):
     """
     Status msg
     """
     if self.parent.parent.parent is not None:
         wx.PostEvent(self.parent.parent.parent,
                      StatusEvent(status=msg, type=type))
Exemplo n.º 15
0
    def _setSlicer(self, slicer):
        """
        Clear the previous slicer and create a new one.Post an internal
        event.

        :param slicer: slicer class to create

        """
        ## Clear current slicer
        if self.slicer is not None:
            self.slicer.clear()
        ## Create a new slicer
        self.slicer_z += 1
        self.slicer = slicer(self, self.subplot, zorder=self.slicer_z)
        self.subplot.set_ylim(self.data2D.ymin, self.data2D.ymax)
        self.subplot.set_xlim(self.data2D.xmin, self.data2D.xmax)
        ## Draw slicer
        self.update()
        self.slicer.update()
        msg = "Plotter2D._setSlicer  %s" % self.slicer.__class__.__name__
        wx.PostEvent(self.parent, StatusEvent(status=msg))
        # Post slicer event
        event = self._getEmptySlicerEvent()
        event.type = self.slicer.__class__.__name__
        event.obj_class = self.slicer.__class__
        event.params = self.slicer.get_params()
        wx.PostEvent(self, event)
Exemplo n.º 16
0
    def on_click_browse(self, event):
        """
        Open a file dialog to allow the user to select a given file.
        Display the loaded data if available.
        """
        path = self.choose_data_file(location=self._default_save_location)
        if path is None:
            return
        if self.parent.parent is not None:
            wx.PostEvent(self.parent.parent, StatusEvent(status="Loading...",
                                        info="info", type="progress"))

        self.done = False
        self._default_save_location = path
        try:
            #Load data
            from load_thread import DataReader
            ## If a thread is already started, stop it
            if self.reader is not None and self.reader.isrunning():
                self.reader.stop()
            self.reader = DataReader(path=path,
                                    completefn=self.complete_loading,
                                    updatefn=None)
            self.reader.queue()
        except:
            msg = "Data Editor: %s" % (sys.exc_value)
            load_error(msg)
            return
        event.Skip()
Exemplo n.º 17
0
    def setup_plot_inversion(self,
                             alpha,
                             nfunc,
                             d_max,
                             q_min=None,
                             q_max=None,
                             bck=False,
                             height=0,
                             width=0):
        """
            Set up inversion from plotted data
        """
        self.alpha = alpha
        self.nfunc = nfunc
        self.max_length = d_max
        self.q_min = q_min
        self.q_max = q_max
        self.has_bck = bck
        self.slit_height = height
        self.slit_width = width

        try:
            pr = self._create_plot_pr()
            if not pr == None:
                self.pr = pr
                self.perform_inversion()
        except:
            wx.PostEvent(self.parent, StatusEvent(status=sys.exc_value))
Exemplo n.º 18
0
 def on_plot_results(self, event):
     self.frame.Show(True)
     result = event.result[0][0]
     filename = result.data.sas_data.filename
     current_time = datetime.datetime.now().strftime("%I:%M%p, %B %d, %Y")
     self.parent.SetTitle(self.window_name + " - " + filename + " - " +
                          current_time)
     if hasattr(result, 'convergence'):
         best, pop = result.convergence[:, 0], result.convergence[:, 1:]
         self._get_view(ConvergenceView).update(best, pop)
     else:
         self._del_view(ConvergenceView)
     if hasattr(result, 'uncertainty_state'):
         stats = var_stats(result.uncertainty_state.draw())
         msg = format_vars(stats)
         self._get_view(CorrelationView).update(result.uncertainty_state)
         self._get_view(UncertaintyView).update(
             (result.uncertainty_state, stats))
         self._get_view(TraceView).update(result.uncertainty_state)
         # TODO: stats should be stored in result rather than computed in bumps UncertaintyView
         wx.PostEvent(self.frame.parent, StatusEvent(status=msg,
                                                     info="info"))
     else:
         for view in (CorrelationView, UncertaintyView, TraceView):
             self._del_view(view)
Exemplo n.º 19
0
    def transform_complete(self, transforms=None):
        """
        Called from FourierThread when calculation has completed
        """
        self._transform_btn.SetLabel("Transform")
        if transforms is None:
            msg = "Error calculating Transform."
            if self.transform_type == 'hilbert':
                msg = "Not yet implemented"
            wx.PostEvent(self._manager.parent,
                         StatusEvent(status=msg, info="Error"))
            self._extract_btn.Disable()
            return

        self._transformed_data = transforms
        (transform1, transform3, idf) = transforms
        plot_x = transform1.x[transform1.x <= 200]
        plot_y = transform1.y[transform1.x <= 200]
        self._manager.show_data(Data1D(plot_x, plot_y), TRANSFORM_LABEL1)
        # No need to shorten gamma3 as it's only calculated up to x=200
        self._manager.show_data(transform3, TRANSFORM_LABEL3)

        plot_x = idf.x[idf.x <= 200]
        plot_y = idf.y[idf.x <= 200]
        self._manager.show_data(Data1D(plot_x, plot_y), IDF_LABEL)

        # Only enable extract params button if a fourier trans. has been done
        if self.transform_type == 'fourier':
            self._extract_btn.Enable()
        else:
            self._extract_btn.Disable()
Exemplo n.º 20
0
    def setup_file_inversion(self,
                             alpha,
                             nfunc,
                             d_max,
                             data,
                             path=None,
                             q_min=None,
                             q_max=None,
                             bck=False,
                             height=0,
                             width=0):
        """
            Set up inversion
        """
        self.alpha = alpha
        self.nfunc = nfunc
        self.max_length = d_max
        self.q_min = q_min
        self.q_max = q_max
        self.est_bck = bck
        self.slit_height = height
        self.slit_width = width

        try:
            pr = self._create_file_pr(data)
            if pr is not None:
                self.pr = pr
                self.perform_inversion()
        except:
            wx.PostEvent(self.parent, StatusEvent(status=sys.exc_value))
Exemplo n.º 21
0
    def on_apply(self, path):
        """
        This method is a misnomer - it is not bound to the apply button
        event.  Instead the apply button event goes to check_name which
        then calls this method if the name of the new file is acceptable.

        :TODO this should be bound to the apply button.  The first line
        should call the check_name method which itself should be in another
        module separated from the the GUI modules.
        """
        self.name_tcl.SetBackgroundColour('white')
        try:
            label = self.get_textnames()
            fname = path
            name1 = label[0]
            name2 = label[1]
            self.write_string(fname, name1, name2)
            success = show_model_output(self, fname)
            if success:
                self.parent.update_custom_combo()
            msg = self._notes
            info = 'Info'
            color = 'blue'
        except:
            msg = "Easy Sum/Multipy Plugin: Error occurred..."
            info = 'Error'
            color = 'red'
        self._msg_box.SetLabel(msg)
        self._msg_box.SetForegroundColour(color)
        if self.parent.parent is not None:
            from sas.sasgui.guiframe.events import StatusEvent
            wx.PostEvent(self.parent.parent, StatusEvent(status=msg,
                                                         info=info))
Exemplo n.º 22
0
    def on_set(self, event):
        """
        Set image as data
        """
        event.Skip()
        # Check the textctrl values
        for item_list in self.xy_ctrls:
            for item in item_list:
                if not self._check_ctrls(item, True):
                    return
        if not self._check_z_ctrl(self.z_ctrl, True):
            return
        try:
            image = self.image
            xmin = float(self.xy_ctrls[0][0].GetValue())
            xmax = float(self.xy_ctrls[0][1].GetValue())
            ymin = float(self.xy_ctrls[1][0].GetValue())
            ymax = float(self.xy_ctrls[1][1].GetValue())
            zscale = float(self.z_ctrl.GetValue())
            self.convert_image(image, xmin, xmax, ymin, ymax, zscale)
        except:
            err_msg = "Error occurred while converting Image to Data."
            if self.base is not None:
                wx.PostEvent(self.base,
                             StatusEvent(status=err_msg, info="error"))
            else:
                print(err_msg)

        self.OnClose(event)
Exemplo n.º 23
0
    def estimate_plot_inversion(self,
                                alpha,
                                nfunc,
                                d_max,
                                q_min=None,
                                q_max=None,
                                est_bck=False,
                                bck_val=0,
                                height=0,
                                width=0):
        """
            Estimate parameters from plotted data
        """
        self.alpha = alpha
        self.nfunc = nfunc
        self.max_length = d_max
        self.q_min = q_min
        self.q_max = q_max
        self.est_bck = est_bck
        self.bck_val = bck_val
        self.slit_height = height
        self.slit_width = width

        try:
            pr = self._create_plot_pr()
            if pr is not None:
                self.pr = pr
                self.perform_estimate()
        except:
            wx.PostEvent(self.parent, StatusEvent(status=sys.exc_value))
Exemplo n.º 24
0
    def compute_extrapolation(self, event=None):
        """
        Compute and plot the extrapolated data.
        Called when Extrapolate button is pressed.
        """
        if not self._validate_inputs:
            msg = "Invalid Q range entered."
            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
            return

        warning_msg = ""
        if self.background < 0:
            warning_msg += "Negative background value entered."
        if any((self._data.y - self.background) < 0):
            if warning_msg != "":
                warning_msg += "\n"
            warning_msg += "Background value results in negative Intensity values."
        if warning_msg != "":
            self._background_input.SetBackgroundColour('yellow')
            wx.PostEvent(self._manager.parent,
                         StatusEvent(status=warning_msg, info='warning'))
        else:
            self._background_input.SetBackgroundColour(wx.WHITE)
        self._background_input.Refresh()

        self._calculator.set_data(self._data)
        self._calculator.lowerq = self.qmin
        self._calculator.upperq = self.qmax
        self._calculator.background = self.background

        try:
            params, self._extrapolated_data = self._calculator.compute_extrapolation(
            )
        except Exception as e:
            msg = "Error extrapolating data:\n"
            msg += str(e)
            wx.PostEvent(self._manager.parent,
                         StatusEvent(status=msg, info="error"))
            self._transform_btn.Disable()
            return
        self._manager.show_data(self._extrapolated_data,
                                IQ_EXTRAPOLATED_DATA_LABEL)
        # Update state of the GUI
        self._transform_btn.Enable()
        self._extract_btn.Disable()
        self.set_extracted_params(reset=True)
        self.set_extrapolation_params(params)
Exemplo n.º 25
0
 def starting_fit(self):
     """
     """
     wx.PostEvent(
         self.parent,
         StatusEvent(status="Starting the Fit...",
                     info="info",
                     type="progress"))
Exemplo n.º 26
0
 def load_update(self, message="", info="warning"):
     """
     print update on the status bar
     """
     if message != "":
         wx.PostEvent(
             self.parent,
             StatusEvent(status=message, info=info, type="progress"))
Exemplo n.º 27
0
 def load_complete(self, output, message="", info="warning"):
     """
      post message to status bar and return list of data
     """
     wx.PostEvent(self.parent,
                  StatusEvent(status=message, info=info, type="stop"))
     if output is not None:
         self.parent.add_data(data_list=output)
Exemplo n.º 28
0
    def load_columns(self, path="sphere_60_q0_2.txt"):
        """
        Load 2- or 3- column ascii
        """
        # Read the data from the data file
        data_x = np.zeros(0)
        data_y = np.zeros(0)
        data_err = np.zeros(0)
        scale = None
        min_err = 0.0
        if path is not None:
            input_f = open(path, 'r')
            buff = input_f.read()
            lines = buff.split('\n')
            for line in lines:
                try:
                    toks = line.split()
                    x = float(toks[0])
                    y = float(toks[1])
                    if len(toks) > 2:
                        err = float(toks[2])
                    else:
                        if scale is None:
                            scale = 0.05 * math.sqrt(y)
                            #scale = 0.05/math.sqrt(y)
                            min_err = 0.01 * y
                        err = scale * math.sqrt(y) + min_err
                        #err = 0

                    data_x = np.append(data_x, x)
                    data_y = np.append(data_y, y)
                    data_err = np.append(data_err, err)
                except:
                    logger.error(sys.exc_value)

        if scale is not None:
            message = "The loaded file had no error bars, statistical errors are assumed."
            wx.PostEvent(self.parent, StatusEvent(status=message))
        else:
            wx.PostEvent(self.parent, StatusEvent(status=''))

        return data_x, data_y, data_err
Exemplo n.º 29
0
 def load_update(self):
     """
     print update on the status bar
     """
     if self.parent.parent is None:
         return
     if self.reader.isrunning():
         type = "progress"
     else:
         type = "stop"
     wx.PostEvent(self.parent.parent, StatusEvent(status="", type=type))
Exemplo n.º 30
0
 def on_close(self, event=None):
     for ctrl in self._to_validate:
         ctrl.SetBackgroundColour(wx.WHITE)
         if ctrl.GetValue() == '': continue
         if not check_float(ctrl):
             msg = "{} must be a valid float".format(ctrl.GetName().replace(
                 "_", " "))
             wx.PostEvent(self.parent.manager.parent.manager.parent,
                          StatusEvent(status=msg, info='error'))
             return False
     for vector_in in self._vectors:
         is_valid, invalid_ctrl = vector_in.Validate()
         if not is_valid:
             msg = "{} must be a valid float".format(
                 invalid_ctrl.GetName().replace("_", " "))
             wx.PostEvent(self.parent.manager.parent.manager.parent,
                          StatusEvent(status=msg, info='error'))
             return False
         setattr(self.metadata, vector_in.GetName(), vector_in.GetValue())
     return True