예제 #1
0
    def _update_view(self):
        """
        view update called by home(), back() and forward()
        :return:
        """
        NavigationToolbar2QT._update_view(self)

        self._myParent.evt_view_updated()
예제 #2
0
class UISDDManager(*uic.loadUiType(ui_path)):

    def __init__(self,
                 xia_list=[],
                 *args, **kwargs):

        super().__init__(*args, **kwargs)
        self.setupUi(self)
        self.addCanvas()

        self.xia_list = xia_list
        self.xia_parser = xiaparser.xiaparser()
        self.xia_graphs_names = []
        self.xia_graphs_labels = []
        self.xia_handles = []



        self.xia = self.xia_list[0]
        self.xia_channels = [int(mca.split('mca')[1]) for mca in self.xia.read_attrs]
        self.xia_tog_channels = []

        self.xia.mca_max_energy.subscribe(self.update_xia_params)
        self.xia.real_time.subscribe(self.update_xia_params)
        self.xia.real_time_rb.subscribe(self.update_xia_params)
        self.edit_xia_acq_time.returnPressed.connect(self.update_xia_acqtime_pv)
        self.edit_xia_energy_range.returnPressed.connect(self.update_xia_energyrange_pv)
        self.push_gain_matching.clicked.connect(self.run_gain_matching)

        self.push_run_xia_measurement.clicked.connect(self.update_xia_rois)
        self.push_run_xia_measurement.clicked.connect(self.start_xia_spectra)
        if self.xia.connected:
            max_en = self.xia.mca_max_energy.value
            energies = np.linspace(0, max_en, 2048)
    
            self.roi_colors = []
            for mult in range(4):
                self.roi_colors.append((.4 + (.2 * mult), 0, 0))
                self.roi_colors.append((0, .4 + (.2 * mult), 0))
                self.roi_colors.append((0, 0, .4 + (.2 * mult)))
    
            for roi in range(12):
                low = getattr(self.xia, "mca1.roi{}".format(roi)).low.value
                high = getattr(self.xia, "mca1.roi{}".format(roi)).high.value
                if low > 0:
                    getattr(self, 'edit_roi_from_{}'.format(roi)).setText('{:.0f}'.format(
                        np.floor(energies[getattr(self.xia, "mca1.roi{}".format(roi)).low.value] * 1000)))
                else:
                    getattr(self, 'edit_roi_from_{}'.format(roi)).setText('{:.0f}'.format(low))
                if high > 0:
                    getattr(self, 'edit_roi_to_{}'.format(roi)).setText('{:.0f}'.format(
                        np.floor(energies[getattr(self.xia, "mca1.roi{}".format(roi)).high.value] * 1000)))
                else:
                    getattr(self, 'edit_roi_to_{}'.format(roi)).setText('{:.0f}'.format(high))
    
                label = getattr(self.xia, "mca1.roi{}".format(roi)).label.value
                getattr(self, 'edit_roi_name_{}'.format(roi)).setText(label)
    
                getattr(self, 'edit_roi_from_{}'.format(roi)).returnPressed.connect(self.update_xia_rois)
                getattr(self, 'edit_roi_to_{}'.format(roi)).returnPressed.connect(self.update_xia_rois)
                getattr(self, 'edit_roi_name_{}'.format(roi)).returnPressed.connect(self.update_xia_rois)
    
    
            for channel in self.xia_channels:
                getattr(self, "checkBox_gm_ch{}".format(channel)).setEnabled(True)
                getattr(self.xia, "mca{}".format(channel)).array.subscribe(self.update_xia_graph)
                getattr(self, "checkBox_gm_ch{}".format(channel)).toggled.connect(self.toggle_xia_checkbox)
            self.push_checkall_xia.clicked.connect(self.toggle_xia_all)
    
            if hasattr(self.xia, 'input_trigger'):
                if self.xia.input_trigger is not None:
                    self.xia.input_trigger.unit_sel.put(1)  # ms, not us

    def addCanvas(self):
        self.figure_gain_matching = Figure()
        self.figure_gain_matching.set_facecolor(color='#FcF9F6')
        self.canvas_gain_matching = FigureCanvas(self.figure_gain_matching)
        self.figure_gain_matching.add_subplot(111)
        self.toolbar_gain_matching = NavigationToolbar(self.canvas_gain_matching, self, coordinates=True)
        self.plot_gain_matching.addWidget(self.toolbar_gain_matching)
        self.plot_gain_matching.addWidget(self.canvas_gain_matching)
        self.canvas_gain_matching.draw_idle()

        self.figure_xia_all_graphs = Figure()
        self.figure_xia_all_graphs.set_facecolor(color='#FcF9F6')
        self.canvas_xia_all_graphs = FigureCanvas(self.figure_xia_all_graphs)
        self.figure_xia_all_graphs.ax = self.figure_xia_all_graphs.add_subplot(111)
        self.toolbar_xia_all_graphs = NavigationToolbar(self.canvas_xia_all_graphs, self, coordinates=True)
        self.plot_xia_all_graphs.addWidget(self.toolbar_xia_all_graphs)
        self.plot_xia_all_graphs.addWidget(self.canvas_xia_all_graphs)
        self.canvas_xia_all_graphs.draw_idle()
        self.cursor_xia_all_graphs = Cursor(self.figure_xia_all_graphs.ax, useblit=True, color='green', linewidth=0.75)
        self.figure_xia_all_graphs.ax.clear()

    def toggle_xia_checkbox(self, value):
        if value:
            self.xia_tog_channels.append(self.sender().text())
        elif self.sender().text() in self.xia_tog_channels:
            self.xia_tog_channels.remove(self.sender().text())
        self.erase_xia_graph()
        for chan in self.xia_tog_channels:
            self.update_xia_graph(getattr(self.xia, 'mca{}.array.value'.format(chan)),
                                  obj=getattr(self.xia, 'mca{}.array'.format(chan)))

    def toggle_xia_all(self):
        if len(self.xia_tog_channels) != len(self.xia.read_attrs):
            for index, mca in enumerate(self.xia.read_attrs):
                if getattr(self, 'checkBox_gm_ch{}'.format(index + 1)).isEnabled():
                    getattr(self, 'checkBox_gm_ch{}'.format(index + 1)).setChecked(True)
        else:
            for index, mca in enumerate(self.xia.read_attrs):
                if getattr(self, 'checkBox_gm_ch{}'.format(index + 1)).isEnabled():
                    getattr(self, 'checkBox_gm_ch{}'.format(index + 1)).setChecked(False)

    def update_xia_params(self, value, **kwargs):
        if kwargs['obj'].name == 'xia1_real_time':
            self.edit_xia_acq_time.setText('{:.2f}'.format(round(value, 2)))
        elif kwargs['obj'].name == 'xia1_real_time_rb':
            self.label_acq_time_rbv.setText('{:.2f}'.format(round(value, 2)))
        elif kwargs['obj'].name == 'xia1_mca_max_energy':
            self.edit_xia_energy_range.setText('{:.0f}'.format(value * 1000))

    def erase_xia_graph(self):
        self.figure_xia_all_graphs.ax.clear()

        for roi in range(12):
            if hasattr(self.figure_xia_all_graphs.ax, 'roi{}l'.format(roi)):
                exec('del self.figure_xia_all_graphs.ax.roi{}l,\
                    self.figure_xia_all_graphs.ax.roi{}h'.format(roi, roi))

        self.toolbar_xia_all_graphs._views.clear()
        self.toolbar_xia_all_graphs._positions.clear()
        self.toolbar_xia_all_graphs._update_view()
        self.xia_graphs_names.clear()
        self.xia_graphs_labels.clear()
        self.xia_handles.clear()
        self.canvas_xia_all_graphs.draw_idle()

    def start_xia_spectra(self):
        if self.xia.collect_mode.value != 0:
            self.xia.collect_mode.put(0)
            ttime.sleep(2)
        self.xia.erase_start.put(1)

    def update_xia_rois(self):
        energies = np.linspace(0, float(self.edit_xia_energy_range.text()) / 1000, 2048)

        for roi in range(12):
            if float(getattr(self, 'edit_roi_from_{}'.format(roi)).text()) < 0 or float(
                    getattr(self, 'edit_roi_to_{}'.format(roi)).text()) < 0:
                exec('start{} = -1'.format(roi))
                exec('end{} = -1'.format(roi))
            else:
                indexes_array = np.where(
                    (energies >= float(getattr(self, 'edit_roi_from_{}'.format(roi)).text()) / 1000) & (
                    energies <= float(getattr(self, 'edit_roi_to_{}'.format(roi)).text()) / 1000) == True)[0]
                if len(indexes_array):
                    exec('start{} = indexes_array.min()'.format(roi))
                    exec('end{} = indexes_array.max()'.format(roi))
                else:
                    exec('start{} = -1'.format(roi))
                    exec('end{} = -1'.format(roi))
            exec('roi{}x = [float(self.edit_roi_from_{}.text()), float(self.edit_roi_to_{}.text())]'.format(roi, roi,
                                                                                                            roi))
            exec('label{} = self.edit_roi_name_{}.text()'.format(roi, roi))

        for channel in self.xia_channels:
            for roi in range(12):
                getattr(self.xia, "mca{}.roi{}".format(channel, roi)).low.put(eval('start{}'.format(roi)))
                getattr(self.xia, "mca{}.roi{}".format(channel, roi)).high.put(eval('end{}'.format(roi)))
                getattr(self.xia, "mca{}.roi{}".format(channel, roi)).label.put(eval('label{}'.format(roi)))

        for roi in range(12):
            if not hasattr(self.figure_xia_all_graphs.ax, 'roi{}l'.format(roi)):
                exec(
                    'self.figure_xia_all_graphs.ax.roi{}l = self.figure_xia_all_graphs.ax.axvline(x=roi{}x[0], color=self.roi_colors[roi])'.format(
                        roi, roi))
                exec(
                    'self.figure_xia_all_graphs.ax.roi{}h = self.figure_xia_all_graphs.ax.axvline(x=roi{}x[1], color=self.roi_colors[roi])'.format(
                        roi, roi))

            else:
                exec('self.figure_xia_all_graphs.ax.roi{}l.set_xdata([roi{}x[0], roi{}x[0]])'.format(roi, roi, roi))
                exec('self.figure_xia_all_graphs.ax.roi{}h.set_xdata([roi{}x[1], roi{}x[1]])'.format(roi, roi, roi))

        self.figure_xia_all_graphs.ax.grid(True)
        self.canvas_xia_all_graphs.draw_idle()

    def update_xia_acqtime_pv(self):
        self.xia.real_time.put(float(self.edit_xia_acq_time.text()))

    def update_xia_energyrange_pv(self):
        self.xia.mca_max_energy.put(float(self.edit_xia_energy_range.text()) / 1000)

    def update_xia_graph(self, value, **kwargs):
        curr_name = kwargs['obj'].name
        curr_index = -1
        if len(self.figure_xia_all_graphs.ax.lines):
            if float(self.edit_xia_energy_range.text()) != self.figure_xia_all_graphs.ax.lines[0].get_xdata()[-1]:
                self.figure_xia_all_graphs.ax.clear()
                for roi in range(12):
                    if hasattr(self.figure_xia_all_graphs.ax, 'roi{}l'.format(roi)):
                        exec('del self.figure_xia_all_graphs.ax.roi{}l,\
                            self.figure_xia_all_graphs.ax.roi{}h'.format(roi, roi))

                self.toolbar_xia_all_graphs._views.clear()
                self.toolbar_xia_all_graphs._positions.clear()
                self.toolbar_xia_all_graphs._update_view()
                self.xia_graphs_names.clear()
                self.xia_graphs_labels.clear()
                self.canvas_xia_all_graphs.draw_idle()

        if curr_name in self.xia_graphs_names:
            for index, name in enumerate(self.xia_graphs_names):
                if curr_name == name:
                    curr_index = index
                    line = self.figure_xia_all_graphs.ax.lines[curr_index]
                    line.set_ydata(value)
                    break

        else:
            ch_number = curr_name.split('_')[1].split('mca')[1]
            if ch_number in self.xia_tog_channels:
                self.xia_graphs_names.append(curr_name)
                label = 'Chan {}'.format(ch_number)
                self.xia_graphs_labels.append(label)
                handles, = self.figure_xia_all_graphs.ax.plot(
                    np.linspace(0, float(self.edit_xia_energy_range.text()), 2048), value, label=label)
                self.xia_handles.append(handles)
                self.figure_xia_all_graphs.ax.legend(self.xia_handles, self.xia_graphs_labels)

            if len(self.figure_xia_all_graphs.ax.lines) == len(self.xia_tog_channels) != 0:
                for roi in range(12):
                    exec('roi{}x = [float(self.edit_roi_from_{}.text()), float(self.edit_roi_to_{}.text())]'.format(roi,
                                                                                                                    roi,
                                                                                                                    roi))

                for roi in range(12):
                    if not hasattr(self.figure_xia_all_graphs.ax, 'roi{}l'.format(roi)):
                        exec(
                            'self.figure_xia_all_graphs.ax.roi{}l = self.figure_xia_all_graphs.ax.axvline(x=roi{}x[0], color=self.roi_colors[roi])'.format(
                                roi, roi))
                        exec(
                            'self.figure_xia_all_graphs.ax.roi{}h = self.figure_xia_all_graphs.ax.axvline(x=roi{}x[1], color=self.roi_colors[roi])'.format(
                                roi, roi))

                self.figure_xia_all_graphs.ax.grid(True)

        self.figure_xia_all_graphs.ax.relim()
        self.figure_xia_all_graphs.ax.autoscale(True, True, True)
        y_interval = self.figure_xia_all_graphs.ax.get_yaxis().get_data_interval()
        if len(y_interval):
            if y_interval[0] != 0 or y_interval[1] != 0:
                self.figure_xia_all_graphs.ax.set_ylim([y_interval[0] - (y_interval[1] - y_interval[0]) * 0.05,
                                                        y_interval[1] + (y_interval[1] - y_interval[0]) * 0.05])
        self.canvas_xia_all_graphs.draw_idle()

    def run_gain_matching(self):
        ax = self.figure_gain_matching.add_subplot(111)
        gain_adjust = [0.001] * len(self.xia_channels)  # , 0.001, 0.001, 0.001]
        diff = [0] * len(self.xia_channels)  # , 0, 0, 0]
        diff_old = [0] * len(self.xia_channels)  # , 0, 0, 0]

        # Run number of iterations defined in the text edit edit_gain_matching_iterations:
        for i in range(int(self.edit_gain_matching_iterations.text())):
            self.xia.collect_mode.put('MCA spectra')
            ttime.sleep(0.25)
            self.xia.mode.put('Real time')
            ttime.sleep(0.25)
            self.xia.real_time.put('1')
            self.xia.capt_start_stop.put(1)
            ttime.sleep(0.05)
            self.xia.erase_start.put(1)
            ttime.sleep(2)
            ax.clear()
            self.toolbar_gain_matching._views.clear()
            self.toolbar_gain_matching._positions.clear()
            self.toolbar_gain_matching._update_view()

            # For each channel:
            for chann in self.xia_channels:
                # If checkbox of current channel is checked:
                if getattr(self, "checkBox_gm_ch{}".format(chann)).checkState() > 0:

                    # Get current channel pre-amp gain:
                    curr_ch_gain = getattr(self.xia, "pre_amp_gain{}".format(chann))

                    coeff = self.xia_parser.gain_matching(self.xia, self.edit_center_gain_matching.text(),
                                                          self.edit_range_gain_matching.text(), chann, ax)
                    # coeff[0] = Intensity
                    # coeff[1] = Fitted mean
                    # coeff[2] = Sigma

                    diff[chann - 1] = float(self.edit_gain_matching_target.text()) - float(coeff[1] * 1000)

                    if i != 0:
                        sign = (diff[chann - 1] * diff_old[chann - 1]) / math.fabs(
                            diff[chann - 1] * diff_old[chann - 1])
                        if int(sign) == -1:
                            gain_adjust[chann - 1] /= 2
                    print('Chan ' + str(chann) + ': ' + str(diff[chann - 1]) + '\n')

                    # Update current channel pre-amp gain:
                    curr_ch_gain.put(curr_ch_gain.value - diff[chann - 1] * gain_adjust[chann - 1])
                    diff_old[chann - 1] = diff[chann - 1]

                    self.canvas_gain_matching.draw_idle()
예제 #3
0
class UIRun(*uic.loadUiType(ui_path)):
    def __init__(self,
                 plan_funcs,
                 db,
                 shutters,
                 adc_list,
                 enc_list,
                 xia,
                 html_log_func,
                 parent_gui,
                 *args, **kwargs):

        super().__init__(*args, **kwargs)
        self.setupUi(self)
        self.addCanvas()

        self.plan_funcs = plan_funcs
        self.plan_funcs_names = [plan.__name__ for plan in plan_funcs]
        self.db = db
        if self.db is None:
            self.run_start.setEnabled(False)

        self.shutters = shutters
        self.adc_list = adc_list
        self.enc_list = enc_list
        self.xia = xia
        self.html_log_func = html_log_func
        self.parent_gui = parent_gui

        self.filepaths = []
        self.xia_parser = xiaparser.xiaparser()

        self.run_type.addItems(self.plan_funcs_names)
        self.run_start.clicked.connect(self.run_scan)

        self.pushButton_scantype_help.clicked.connect(self.show_scan_help)

        self.run_type.currentIndexChanged.connect(self.populateParams)

        # List with uids of scans created in the "run" mode:
        self.run_mode_uids = []

        self.params1 = []
        self.params2 = []
        self.params3 = []
        if len(self.plan_funcs) != 0:
            self.populateParams(0)

    def addCanvas(self):
        self.figure = Figure()
        self.figure.set_facecolor(color='#FcF9F6')
        self.canvas = FigureCanvas(self.figure)
        self.figure.ax = self.figure.add_subplot(111)
        self.toolbar = NavigationToolbar(self.canvas, self, coordinates=True)
        self.toolbar.setMaximumHeight(25)
        self.plots.addWidget(self.toolbar)
        self.plots.addWidget(self.canvas)
        self.figure.ax.grid(alpha = 0.4)
        self.canvas.draw_idle()

    def run_scan(self):
        if self.run_type.currentText() == 'get_offsets':
            for shutter in [self.shutters[shutter] for shutter in self.shutters if
                            self.shutters[shutter].shutter_type == 'PH' and
                                            self.shutters[shutter].state.read()['{}_state'.format(shutter)][
                                                'value'] != 1]:
                shutter.close()
                while shutter.state.read()['{}_state'.format(shutter.name)]['value'] != 1:
                    QtWidgets.QApplication.processEvents()
                    ttime.sleep(0.1)

        else:
            for shutter in [self.shutters[shutter] for shutter in self.shutters if
                            self.shutters[shutter].shutter_type != 'SP']:
                if shutter.state.value:
                    ret = self.questionMessage('Shutter closed',
                                               'Would you like to run the scan with the shutter closed?')
                    if not ret:
                        print('Aborted!')
                        return False
                    break

        # Send sampling time to the pizzaboxes:
        value = int(round(float(self.analog_samp_time) / self.adc_list[0].sample_rate.value * 100000))

        for adc in self.adc_list:
            adc.averaging_points.put(str(value))

        for enc in self.enc_list:
            enc.filter_dt.put(float(self.enc_samp_time) * 100000)

        if self.xia.input_trigger is not None:
            self.xia.input_trigger.unit_sel.put(1)  # ms, not us
            self.xia.input_trigger.period_sp.put(int(self.xia_samp_time))

        self.comment = self.params2[0].text()
        if (self.comment):
            timenow = datetime.datetime.now()
            print('\nStarting scan at {}'.format(timenow.strftime("%H:%M:%S")))
            start_scan_timer=timer()
            
            # Get parameters from the widgets and organize them in a dictionary (run_params)
            run_params = {}
            for i in range(len(self.params1)):
                if (self.param_types[i] == int):
                    run_params[self.params3[i].text().split('=')[0]] = self.params2[i].value()
                elif (self.param_types[i] == float):
                    run_params[self.params3[i].text().split('=')[0]] = self.params2[i].value()
                elif (self.param_types[i] == bool):
                    run_params[self.params3[i].text().split('=')[0]] = bool(self.params2[i].checkState())
                elif (self.param_types[i] == str):
                    run_params[self.params3[i].text().split('=')[0]] = self.params2[i].text()

            # Erase last graph
            self.figure.ax.clear()
            self.toolbar._views.clear()
            self.toolbar._positions.clear()
            self.toolbar._update_view()
            self.canvas.draw_idle()
            self.figure.ax.grid(alpha = 0.4)
            
            # Run the scan using the dict created before
            self.run_mode_uids = []
            self.parent_gui.run_mode = 'run'
            for uid in self.plan_funcs[self.run_type.currentIndex()](**run_params, ax=self.figure.ax):
                self.run_mode_uids.append(uid)

            timenow = datetime.datetime.now()    
            print('Scan complete at {}'.format(timenow.strftime("%H:%M:%S")))
            stop_scan_timer=timer()  
            print('Scan duration {}'.format(stop_scan_timer-start_scan_timer))

        else:
            print('\nPlease, type the name of the scan in the field "name"\nTry again')

    def show_scan_help(self):
        title = self.run_type.currentText()
        message = self.plan_funcs[self.run_type.currentIndex()].__doc__
        QtWidgets.QMessageBox.question(self,
                                       'Help! - {}'.format(title),
                                       message,
                                       QtWidgets.QMessageBox.Ok)

    def create_log_scan(self, uid, figure):
        self.canvas.draw_idle()
        if self.html_log_func is not None:
            self.html_log_func(uid, figure)

    def populateParams(self, index):
        for i in range(len(self.params1)):
            self.gridLayout_13.removeWidget(self.params1[i])
            self.gridLayout_13.removeWidget(self.params2[i])
            self.gridLayout_13.removeWidget(self.params3[i])
            self.params1[i].deleteLater()
            self.params2[i].deleteLater()
            self.params3[i].deleteLater()
        self.params1 = []
        self.params2 = []
        self.params3 = []
        self.param_types = []
        plan_func = self.plan_funcs[index]
        signature = inspect.signature(plan_func)
        for i in range(0, len(signature.parameters)):
            default = re.sub(r':.*?=', '=', str(signature.parameters[list(signature.parameters)[i]]))
            if default == str(signature.parameters[list(signature.parameters)[i]]):
                default = re.sub(r':.*', '', str(signature.parameters[list(signature.parameters)[i]]))
            self.addParamControl(list(signature.parameters)[i], default,
                                 signature.parameters[list(signature.parameters)[i]].annotation,
                                 grid=self.gridLayout_13, params=[self.params1, self.params2, self.params3])
            self.param_types.append(signature.parameters[list(signature.parameters)[i]].annotation)

    def addParamControl(self, name, default, annotation, grid, params):
        rows = int((grid.count()) / 3)
        param1 = QtWidgets.QLabel(str(rows + 1))

        param2 = None
        def_val = ''
        if default.find('=') != -1:
            def_val = re.sub(r'.*=', '', default)
        if annotation == int:
            param2 = QtWidgets.QSpinBox()
            param2.setMaximum(100000)
            param2.setMinimum(-100000)
            def_val = int(def_val)
            param2.setValue(def_val)
        elif annotation == float:
            param2 = QtWidgets.QDoubleSpinBox()
            param2.setMaximum(100000)
            param2.setMinimum(-100000)
            def_val = float(def_val)
            param2.setValue(def_val)
        elif annotation == bool:
            param2 = QtWidgets.QCheckBox()
            if def_val == 'True':
                def_val = True
            else:
                def_val = False
            param2.setCheckState(def_val)
            param2.setTristate(False)
        elif annotation == str:
            param2 = QtWidgets.QLineEdit()
            def_val = str(def_val)
            param2.setText(def_val)

        if param2 is not None:
            param3 = QtWidgets.QLabel(default)
            grid.addWidget(param1, rows, 0, QtCore.Qt.AlignTop)
            grid.addWidget(param2, rows, 1, QtCore.Qt.AlignTop)
            grid.addWidget(param3, rows, 2, QtCore.Qt.AlignTop)
            params[0].append(param1)
            params[1].append(param2)
            params[2].append(param3)

    def questionMessage(self, title, question):
        reply = QtWidgets.QMessageBox.question(self, title,
                                               question,
                                               QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        if reply == QtWidgets.QMessageBox.Yes:
            return True
        elif reply == QtWidgets.QMessageBox.No:
            return False
        else:
            return False

    def setAnalogSampTime(self, text):
        self.analog_samp_time = text

    def setEncSampTime(self, text):
        self.enc_samp_time = text

    def setXiaSampTime(self, text):
        self.xia_samp_time = text

    def plot_scan(self, data):
        if self.parent_gui.run_mode == 'run':
            self.figure.ax.clear()
            self.figure.ax.grid(alpha = 0.4)
            self.toolbar._views.clear()
            self.toolbar._positions.clear()
            self.toolbar._update_view()

            df = data['processing_ret']['data']
            #df = pd.DataFrame.from_dict(json.loads(data['processing_ret']['data']))
            df = df.sort_values('energy')
            self.df = df

            division = df['i0']/df['it']
            division[division < 0] = 1
            self.figure.ax.plot(df['energy'], np.log(division))
            self.canvas.draw_idle()

            self.create_log_scan(data['uid'], self.figure)
예제 #4
0
class UIProcessing(*uic.loadUiType(ui_path)):
    def __init__(self, hhm, db, det_dict, sender, *args, **kwargs):

        super().__init__(*args, **kwargs)
        self.setupUi(self)
        self.addCanvas()

        self.hhm = hhm
        self.db = db
        self.det_dict = det_dict
        self.gen_parser = xasdata.XASdataGeneric(self.hhm.enc.pulses_per_deg,
                                                 self.db)
        self.sender = sender

        self.settings = QSettings('ISS Beamline', 'XLive')
        self.edit_E0_2.setText(
            self.settings.value('e0_processing',
                                defaultValue='11470',
                                type=str))
        self.edit_E0_2.textChanged.connect(self.save_e0_processing_value)
        self.user_dir = self.settings.value(
            'user_dir', defaultValue='/GPFS/xf08id/User Data/', type=str)

        # Initialize 'processing' tab
        self.push_select_file.clicked.connect(self.selectFile)
        self.push_bin_save.clicked.connect(self.bin_single_data)
        self.push_calibrate.clicked.connect(self.calibrate_offset)
        self.push_replot_file.clicked.connect(self.replot_data)
        self.push_reset_data.clicked.connect(self.reset_data_plots)
        self.cid = self.canvas_old_scans_2.mpl_connect('button_press_event',
                                                       self.getX)
        self.edge_found = -1
        # Disable buttons
        self.push_bin_save.setDisabled(True)
        self.push_replot_file.setDisabled(True)
        self.active_threads = 0
        self.total_threads = 0
        self.progressBar_processing.setValue(int(np.round(0)))
        self.plotting_list = []
        self.last_num = ''
        self.last_den = ''
        self.last_num_text = 'i0'
        self.last_den_text = 'it'
        self.bin_data_sets = []
        self.interp_data_sets = []
        self.handles_interp = []
        self.handles_bin = []

    def addCanvas(self):
        self.figure_old_scans = Figure()
        self.figure_old_scans.set_facecolor(color='#FcF9F6')
        self.canvas_old_scans = FigureCanvas(self.figure_old_scans)
        self.figure_old_scans.ax = self.figure_old_scans.add_subplot(111)
        self.toolbar_old_scans = NavigationToolbar(self.canvas_old_scans,
                                                   self,
                                                   coordinates=True)
        self.plot_old_scans.addWidget(self.toolbar_old_scans)
        self.plot_old_scans.addWidget(self.canvas_old_scans)
        self.canvas_old_scans.draw_idle()

        self.figure_old_scans_2 = Figure()
        self.figure_old_scans_2.set_facecolor(color='#FcF9F6')
        self.canvas_old_scans_2 = FigureCanvas(self.figure_old_scans_2)
        self.figure_old_scans_2.ax = self.figure_old_scans_2.add_subplot(111)
        self.figure_old_scans_2.ax2 = self.figure_old_scans_2.ax.twinx()
        self.toolbar_old_scans_2 = NavigationToolbar(self.canvas_old_scans_2,
                                                     self,
                                                     coordinates=True)
        self.plot_old_scans_2.addWidget(self.toolbar_old_scans_2)
        self.plot_old_scans_2.addWidget(self.canvas_old_scans_2)
        self.canvas_old_scans_2.draw_idle()

        self.figure_old_scans_3 = Figure()
        self.figure_old_scans_3.set_facecolor(color='#FcF9F6')
        self.canvas_old_scans_3 = FigureCanvas(self.figure_old_scans_3)
        self.figure_old_scans_3.ax = self.figure_old_scans_3.add_subplot(111)
        self.figure_old_scans_3.ax2 = self.figure_old_scans_3.ax.twinx()
        self.toolbar_old_scans_3 = NavigationToolbar(self.canvas_old_scans_3,
                                                     self,
                                                     coordinates=True)
        self.plot_old_scans_3.addWidget(self.toolbar_old_scans_3)
        self.plot_old_scans_3.addWidget(self.canvas_old_scans_3)
        self.canvas_old_scans_3.draw_idle()

    def getX(self, event):
        if event.button == 3:
            ret = self.questionMessage(
                'Setting Edge',
                'Would like to set the edge to {:.0f}?'.format(event.xdata))
            if ret:
                self.edit_E0_2.setText(str(int(np.round(event.xdata))))

    def set_new_angle_offset(self, value):
        try:
            self.hhm.angle_offset.put(float(value))
        except Exception as exc:
            if type(exc) == ophyd_utils.errors.LimitError:
                print('[New offset] {}. No reason to be desperate, though.'.
                      format(exc))
            else:
                print('[New offset] Something went wrong, not the limit: {}'.
                      format(exc))
            return 1
        return 0

    def save_e0_processing_value(self, string):
        self.settings.setValue('e0_processing', string)

    def selectFile(self):
        if self.checkBox_process_bin.checkState() > 0:
            self.selected_filename_bin = QtWidgets.QFileDialog.getOpenFileNames(
                directory=self.user_dir, filter='*.txt', parent=self)[0]
        else:
            self.selected_filename_bin = [
                QtWidgets.QFileDialog.getOpenFileName(directory=self.user_dir,
                                                      filter='*.txt',
                                                      parent=self)[0]
            ]
        if len(self.selected_filename_bin[0]):
            self.handles_interp = []
            self.handles_bin = []
            self.interp_data_sets = []
            self.bin_data_sets = []
            self.uids = []
            if len(self.selected_filename_bin) > 1:
                filenames = []
                self.user_dir = self.selected_filename_bin[0].rsplit('/', 1)[0]
                for name in self.selected_filename_bin:
                    filenames.append(name.rsplit('/', 1)[1])
                    self.uids.append(
                        self.gen_parser.read_header(name).split('UID: ')
                        [1].split('\n')[0])
                filenames = ', '.join(filenames)
                self.push_bin_save.setEnabled(False)
            elif len(self.selected_filename_bin) == 1:
                filenames = self.selected_filename_bin[0]
                self.user_dir = filenames.rsplit('/', 1)[0]
                self.uids.append(
                    self.gen_parser.read_header(filenames).split('UID: ')
                    [1].split('\n')[0])
                self.push_bin_save.setEnabled(True)

            print(self.uids)
            self.settings.setValue('user_dir', self.user_dir)
            self.label_24.setText(filenames)
            self.send_data_request()

    def update_listWidgets(self):
        index = [
            index for index, item in enumerate([
                self.listWidget_numerator.item(index)
                for index in range(self.listWidget_numerator.count())
            ]) if item.text() == self.last_num_text
        ]
        if len(index):
            self.listWidget_numerator.setCurrentRow(index[0])
        else:
            self.listWidget_numerator.setCurrentRow(0)

        index = [
            index for index, item in enumerate([
                self.listWidget_denominator.item(index)
                for index in range(self.listWidget_denominator.count())
            ]) if item.text() == self.last_den_text
        ]
        if len(index):
            self.listWidget_denominator.setCurrentRow(index[0])
        else:
            self.listWidget_denominator.setCurrentRow(0)

    def create_lists(self, list_num, list_den):
        self.listWidget_numerator.clear()
        self.listWidget_denominator.clear()
        self.listWidget_numerator.insertItems(0, list_num)
        self.listWidget_denominator.insertItems(0, list_den)

    def bin_single_data(self):
        for index, uid in enumerate(self.uids):
            self.send_bin_request(uid,
                                  filepath=self.selected_filename_bin[index])

    def send_bin_request(self, uid, filepath):
        e0 = int(self.edit_E0_2.text())
        edge_start = int(self.edit_edge_start.text())
        edge_end = int(self.edit_edge_end.text())
        preedge_spacing = float(self.edit_preedge_spacing.text())
        xanes_spacing = float(self.edit_xanes_spacing.text())
        exafs_spacing = float(self.edit_exafs_spacing.text())
        req = {
            'uid': uid,
            'requester': socket.gethostname(),
            'type': 'spectroscopy',
            'processing_info': {
                'type': 'bin',
                'filepath': filepath,  #self.selected_filename_bin[index],
                'e0': e0,
                'edge_start': edge_start,
                'edge_end': edge_end,
                'preedge_spacing': preedge_spacing,
                'xanes_spacing': xanes_spacing,
                'exafs_spacing': exafs_spacing,
            }
        }
        self.sender.send_string(json.dumps(req))

    def send_data_request(self):
        index = 1
        self.old_scans_control = 1
        self.old_scans_2_control = 1
        self.old_scans_3_control = 1

        self.figure_old_scans.ax.clear()
        self.toolbar_old_scans._views.clear()
        self.toolbar_old_scans._positions.clear()
        self.toolbar_old_scans._update_view()
        self.canvas_old_scans.draw_idle()

        self.figure_old_scans_2.ax.clear()
        self.figure_old_scans_2.ax2.clear()
        self.toolbar_old_scans_2._views.clear()
        self.toolbar_old_scans_2._positions.clear()
        self.toolbar_old_scans_2._update_view()
        self.canvas_old_scans_2.draw_idle()

        self.figure_old_scans_3.ax.clear()
        self.figure_old_scans_3.ax2.clear()
        self.toolbar_old_scans_3._views.clear()
        self.toolbar_old_scans_3._positions.clear()
        self.toolbar_old_scans_3._update_view()
        self.canvas_old_scans_3.draw_idle()

        # print('[Launching Threads]')
        if self.listWidget_numerator.currentRow() is not -1:
            self.last_num = self.listWidget_numerator.currentRow()
            self.last_num_text = self.listWidget_numerator.currentItem().text()
        if self.listWidget_denominator.currentRow() is not -1:
            self.last_den = self.listWidget_denominator.currentRow()
            self.last_den_text = self.listWidget_denominator.currentItem(
            ).text()
        self.listWidget_numerator.setCurrentRow(-1)
        self.listWidget_denominator.setCurrentRow(-1)

        for index, uid in enumerate(self.uids):
            req = {
                'uid': uid,
                'requester': socket.gethostname(),
                'type': 'spectroscopy',
                'processing_info': {
                    'type': 'request_interpolated_data',
                    'filepath': self.selected_filename_bin[index],
                }
            }
            self.sender.send_string(json.dumps(req))

            if self.checkBox_process_bin.checkState() > 0:
                self.send_bin_request(uid, self.selected_filename_bin[index])

    def save_bin(self):
        filename = self.curr_filename_save
        self.gen_parser.data_manager.export_dat(filename)
        print('[Save File] File Saved! [{}]'.format(filename[:-3] + 'dat'))

    def calibrate_offset(self):
        ret = self.questionMessage(
            'Confirmation', 'Are you sure you would like to calibrate it?')
        if not ret:
            print('[E0 Calibration] Aborted!')
            return False

        new_value = str(
            self.hhm.angle_offset.value -
            (xray.energy2encoder(float(self.edit_E0_2.text(
            )), self.hhm.pulses_per_deg) - xray.energy2encoder(
                float(self.edit_ECal.text()), self.hhm.pulses_per_deg)) /
            self.hhm.pulses_per_deg)
        if self.set_new_angle_offset(new_value):
            return
        print('[E0 Calibration] New value: {}\n[E0 Calibration] Completed!'.
              format(new_value))

    def update_k_view(self, df):
        e0 = int(self.edit_E0_2.text())
        edge_start = int(self.edit_edge_start.text())
        edge_end = int(self.edit_edge_end.text())
        preedge_spacing = float(self.edit_preedge_spacing.text())
        xanes_spacing = float(self.edit_xanes_spacing.text())
        exafs_spacing = float(self.edit_exafs_spacing.text())
        k_power = float(self.edit_y_power.text())

        energy_string = 'energy'

        result_orig = df[self.listWidget_numerator.currentItem().text()] / \
                      df[self.listWidget_denominator.currentItem().text()]

        if self.checkBox_log.checkState() > 0:
            result_orig = np.log(result_orig)

        k_data = self.gen_parser.data_manager.get_k_data(
            e0, edge_end, exafs_spacing, df, df[energy_string], result_orig,
            k_power)

        self.figure_old_scans.ax.plot(k_data[0], k_data[1])
        self.figure_old_scans.ax.set_xlabel('k')
        self.figure_old_scans.ax.set_ylabel(r'$\kappa$ * k ^ {}'.format(
            k_power))  # 'ϰ * k ^ {}'.format(k_power))
        self.figure_old_scans.ax.grid(True)

        self.figure_old_scans.ax.legend(handles=self.handles_bin)
        self.figure_old_scans.tight_layout()
        self.canvas_old_scans.draw_idle()

    def replot_data(self):
        self.replot(self.bin_data_sets, self.handles_bin,
                    self.figure_old_scans_3, self.toolbar_old_scans_3)
        self.replot(self.interp_data_sets, self.handles_interp,
                    self.figure_old_scans_2, self.toolbar_old_scans_2)
        self.replot_y()

    def replot_y(self):
        self.figure_old_scans.ax.clear()
        self.figure_old_scans.canvas.draw_idle()
        self.toolbar_old_scans._views.clear()
        self.toolbar_old_scans._positions.clear()
        self.toolbar_old_scans._update_view()

        for data in self.bin_data_sets:
            df = data['processing_ret']['data']
            self.update_k_view(df)

    def replot(self, list_data_set, handles, figure, toolbar):
        figure.ax.clear()
        if hasattr(figure, 'ax2'):
            figure.ax2.clear()
        figure.canvas.draw_idle()
        toolbar._views.clear()
        toolbar._positions.clear()
        toolbar._update_view()

        if self.listWidget_numerator.currentRow() is not -1:
            self.last_num = self.listWidget_numerator.currentRow()
            self.last_num_text = self.listWidget_numerator.currentItem().text()
        if self.listWidget_denominator.currentRow() is not -1:
            self.last_den = self.listWidget_denominator.currentRow()
            self.last_den_text = self.listWidget_denominator.currentItem(
            ).text()

        for data in list_data_set:
            df = data['processing_ret']['data']
            df = df.sort_values('energy')
            result = df[self.last_num_text] / df[self.last_den_text]
            ylabel = '{} / {}'.format(self.last_num_text, self.last_den_text)

            self.bin_offset = 0
            if self.checkBox_log.checkState() > 0:
                ylabel = 'log({})'.format(ylabel)
                warnings.filterwarnings('error')
                try:
                    result_log = np.log(result)
                except Warning as wrn:
                    self.bin_offset = 0.1 + np.abs(result.min())
                    print(
                        '{}: Added an offset of {} so that we can plot the graphs properly (only for data visualization)'
                        .format(wrn, self.bin_offset))
                    result_log = np.log(result + self.bin_offset)
                    # self.checkBox_log.setChecked(False)
                warnings.filterwarnings('default')
                result = result_log

            if self.checkBox_neg.checkState() > 0:
                result = -result

            figure.ax.plot(df['energy'].iloc[:len(result)], result)
            figure.ax.set_ylabel(ylabel)
            figure.ax.set_xlabel('energy')
            figure.tight_layout()

        figure.ax.legend(handles=handles)
        figure.tight_layout()

        figure.canvas.draw_idle()

    def plot_data(self, data):
        df = data['processing_ret']['data']
        #df = pd.DataFrame.from_dict(json.loads(data['processing_ret']['data']))
        df = df.sort_values('energy')
        self.df = df
        self.bin_data_sets.append(data)
        self.create_lists(df.keys(), df.keys())
        self.update_listWidgets()
        self.push_replot_file.setEnabled(True)

        division = df[self.last_num_text] / df[self.last_den_text]

        if self.checkBox_log.checkState() > 0:
            division[division < 0] = 1
            division = np.log(division)

        if self.checkBox_neg.checkState() > 0:
            division = -division

        self.figure_old_scans_3.ax.plot(df['energy'], division)

        last_trace = self.figure_old_scans_3.ax.get_lines()[
            len(self.figure_old_scans_3.ax.get_lines()) - 1]
        patch = mpatches.Patch(
            color=last_trace.get_color(),
            label=data['processing_ret']['metadata']['name'])
        self.handles_bin.append(patch)

        self.figure_old_scans_3.ax.legend(handles=self.handles_bin)
        self.figure_old_scans_3.tight_layout()
        self.canvas_old_scans_3.draw_idle()

        self.update_k_view(df)

    def plot_interp_data(self, data):
        df = data['processing_ret']['data']
        #df = pd.DataFrame.from_dict(json.loads(data['processing_ret']['data']))
        df = df.sort_values('energy')
        self.df = df
        self.interp_data_sets.append(data)
        self.create_lists(df.keys(), df.keys())
        self.update_listWidgets()
        self.push_replot_file.setEnabled(True)

        division = df[self.last_num_text] / df[self.last_den_text]

        if self.checkBox_log.checkState() > 0:
            division[division < 0] = 1
            division = np.log(division)

        if self.checkBox_neg.checkState() > 0:
            division = -division

        self.figure_old_scans_2.ax.plot(df['energy'], division)

        last_trace = self.figure_old_scans_2.ax.get_lines()[
            len(self.figure_old_scans_2.ax.get_lines()) - 1]
        patch = mpatches.Patch(
            color=last_trace.get_color(),
            label=data['processing_ret']['metadata']['name'])
        self.handles_interp.append(patch)

        self.figure_old_scans_2.ax.legend(handles=self.handles_interp)
        self.figure_old_scans_2.tight_layout()
        self.canvas_old_scans_2.draw_idle()

    def erase_plots(self):
        self.figure_old_scans.ax.clear()
        self.toolbar_old_scans._views.clear()
        self.toolbar_old_scans._positions.clear()
        self.toolbar_old_scans._update_view()
        self.canvas_old_scans.draw_idle()

        self.figure_old_scans_2.ax.clear()
        self.figure_old_scans_2.ax2.clear()
        self.toolbar_old_scans_2._views.clear()
        self.toolbar_old_scans_2._positions.clear()
        self.toolbar_old_scans_2._update_view()
        self.canvas_old_scans_2.draw_idle()

        self.figure_old_scans_3.ax.clear()
        self.figure_old_scans_3.ax2.clear()
        self.toolbar_old_scans_3._views.clear()
        self.toolbar_old_scans_3._positions.clear()
        self.toolbar_old_scans_3._update_view()
        self.canvas_old_scans_3.draw_idle()

    def reset_data_plots(self):
        self.push_replot_file.setEnabled(False)
        self.listWidget_numerator.clear()
        self.listWidget_denominator.clear()
        self.bin_data_sets = []
        self.interp_data_sets = []
        self.handles_interp = []
        self.handles_bin = []
        self.df = pd.DataFrame([])
        self.erase_plots()

    def questionMessage(self, title, question):
        reply = QtWidgets.QMessageBox.question(
            self, title, question,
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        if reply == QtWidgets.QMessageBox.Yes:
            return True
        elif reply == QtWidgets.QMessageBox.No:
            return False
        else:
            return False
예제 #5
0
class UITrajectoryManager(*uic.loadUiType(ui_path)):
    trajectoriesChanged = QtCore.pyqtSignal()

    def __init__(self,
                 hhm=None,
                 run_prep_traj=None,
                 *args, **kwargs):

        super().__init__(*args, **kwargs)
        self.setupUi(self)
        self.addCanvas()

        self.element = 'Scandium (21)'
        self.e0 = '4492'
        self.edge = 'K'

        self.widget_energy_selector = isstools.widgets.widget_energy_selector.UIEnergySelector()
        self.layout_energy_selector_trajectory.addWidget(self.widget_energy_selector)
        #communication between the Energy Selector widget and Trajectory Manager
        self.widget_energy_selector.edit_E0.textChanged.connect(self.update_E0)
        self.widget_energy_selector.comboBox_edge.currentTextChanged.connect(self.update_edge)
        self.widget_energy_selector.comboBox_element.currentTextChanged.connect(self.update_element)

        self.run_prep_traj = run_prep_traj
        self.hhm = hhm
        self.hhm.angle_offset.subscribe(self.update_angle_offset)
        self.traj_manager = trajectory_manager(hhm)
        self.comboBox_slot_to_load_trajectory.addItems(['1', '2', '3', '4', '5', '6', '7', '8'])
        self.comboBox_slot_to_init_trajectory.addItems(['1', '2', '3', '4', '5', '6', '7', '8'])
        self.comboBox_slot_to_init_trajectory.setCurrentIndex(self.traj_manager.current_lut() - 1)
        try:
            pass
        #    self.trajectories = self.traj_manager.read_info(silent=True)
        #    self.trajectories = collections.OrderedDict(sorted(self.trajectories.items()))
        except OSError as err:
            print('Error loading:', err)

        self.traj_creator = trajectory(self.hhm)
        self.trajectory_path = self.hhm.traj_filepath#'/GPFS/xf08id/trajectory/'
        self.push_build_trajectory.clicked.connect(self.build_trajectory)
        self.push_save_trajectory.clicked.connect(self.save_trajectory)
        self.push_update_offset.clicked.connect(self.update_offset)
        self.push_select_traj_file.clicked.connect(self.get_traj_names)
        self.push_load_trajectory.clicked.connect(self.load_trajectory)
        self.push_init_trajectory.clicked.connect(self.init_trajectory)
        self.push_read_traj_info.clicked.connect(self.read_trajectory_info)
        self.push_prepare_trajectory.clicked.connect(self.run_prep_traj)
        self.push_plot_traj.clicked.connect(self.plot_traj_file)
        self.push_plot_traj.setDisabled(True)
        self.push_save_trajectory.setDisabled(True)
        self.checkBox_traj_single_dir.stateChanged.connect(self.update_repetitions_spinbox)
        self.checkBox_traj_single_dir.stateChanged.connect(self.checkBox_traj_revert.setEnabled)

    def addCanvas(self):
        self.figure_single_trajectory = Figure()
        self.figure_single_trajectory.set_facecolor(color='#FcF9F6')
        self.canvas_single_trajectory = FigureCanvas(self.figure_single_trajectory)
        self.figure_single_trajectory.ax = self.figure_single_trajectory.add_subplot(111)
        self.figure_single_trajectory.ax2 = self.figure_single_trajectory.ax.twinx()
        self.toolbar_single_trajectory = NavigationToolbar(self.canvas_single_trajectory, self, coordinates=True)

        self.plot_single_trajectory.addWidget(self.toolbar_single_trajectory)
        self.plot_single_trajectory.addWidget(self.canvas_single_trajectory)
        self.canvas_single_trajectory.draw_idle()

        self.figure_full_trajectory = Figure()
        self.figure_full_trajectory.set_facecolor(color='#FcF9F6')
        self.canvas_full_trajectory = FigureCanvas(self.figure_full_trajectory)
        self.figure_full_trajectory.add_subplot(111)
        self.figure_full_trajectory.ax = self.figure_full_trajectory.add_subplot(111)
        self.toolbar_full_trajectory = NavigationToolbar(self.canvas_full_trajectory, self,coordinates=True)

        self.plot_full_trajectory.addWidget(self.toolbar_full_trajectory)
        self.plot_full_trajectory.addWidget(self.canvas_full_trajectory)
        self.canvas_full_trajectory.draw_idle()

    def update_angle_offset(self, pvname = None, value=None, char_value=None, **kwargs):
        self.label_angle_offset.setText('{0:.8f}'.format(value))

    def build_trajectory(self):
        E0 = float(self.e0)
        preedge_lo = int(self.edit_preedge_lo.text())
        preedge_hi = int(self.edit_preedge_hi.text())
        edge_hi = int(self.edit_edge_hi.text())

        postedge_k = float(self.edit_postedge_hi.text())
        postedge_hi = xray.k2e(postedge_k,
                               E0) - E0  # (1000 * ((postedge_k ** 2) + (16.2009 ** 2) * E0/1000) / (16.2009 ** 2)) - E0

        velocity_preedge = int(self.edit_velocity_preedge.text())
        velocity_edge = int(self.edit_velocity_edge.text())
        velocity_postedge = int(self.edit_velocity_postedge.text())

        preedge_stitch_lo = int(self.edit_preedge_stitch_lo.text())
        preedge_stitch_hi = int(self.edit_preedge_stitch_hi.text())
        edge_stitch_lo = int(self.edit_edge_stitch_lo.text())
        edge_stitch_hi = int(self.edit_edge_stitch_hi.text())
        postedge_stitch_lo = int(self.edit_postedge_stitch_lo.text())
        postedge_stitch_hi = int(self.edit_postedge_stitch_hi.text())

        padding_preedge = float(self.edit_padding_preedge.text())
        padding_postedge = float(self.edit_padding_postedge.text())

        sine_duration = float(self.edit_sine_total_duration.text())

        traj_type = self.tabWidget_2.tabText(self.tabWidget_2.currentIndex())
        if traj_type == 'Double Sine':
            dsine_preedge_duration = float(self.edit_ds_pree_duration.text())
            dsine_postedge_duration = float(self.edit_ds_poste_duration.text())
        else:
            dsine_preedge_duration = float(self.edit_ds2_pree_duration.text())
            dsine_postedge_duration = float(self.edit_ds2_poste_duration.text())

        vel_edge = float(self.edit_vel_edge.text())
        #Define element and edge
        self.traj_creator.elem = f'{self.element}'
        self.traj_creator.edge = f'{self.edge}'
        self.traj_creator.e0 = f'{self.e0}'

        # Create and interpolate trajectory
        self.traj_creator.define(edge_energy=E0, offsets=([preedge_lo, preedge_hi, edge_hi, postedge_hi]),
                                 velocities=([velocity_preedge, velocity_edge, velocity_postedge]), \
                                 stitching=([preedge_stitch_lo, preedge_stitch_hi, edge_stitch_lo, edge_stitch_hi,
                                             postedge_stitch_lo, postedge_stitch_hi]), \
                                 servocycle=16000, padding_lo=padding_preedge, padding_hi=padding_postedge,
                                 sine_duration=sine_duration,
                                 dsine_preedge_duration=dsine_preedge_duration,
                                 dsine_postedge_duration=dsine_postedge_duration, trajectory_type=traj_type,
                                 vel_edge=vel_edge)
        self.traj_creator.interpolate()

        # Revert trajectory if checkbox checked
        if self.checkBox_traj_revert.isChecked() and self.checkBox_traj_revert.isEnabled():
            self.traj_creator.revert()

        # Plot single trajectory motion
        self.figure_single_trajectory.ax.clear()
        self.figure_single_trajectory.ax2.clear()
        self.toolbar_single_trajectory._views.clear()
        self.toolbar_single_trajectory._positions.clear()
        self.toolbar_single_trajectory._update_view()
        self.figure_single_trajectory.ax.plot(self.traj_creator.time, self.traj_creator.energy, 'ro')
        self.figure_single_trajectory.ax.plot(self.traj_creator.time_grid, self.traj_creator.energy_grid, 'b')
        self.figure_single_trajectory.ax.set_xlabel('Time (s)')
        self.figure_single_trajectory.ax.set_ylabel('Energy (eV)')
        self.figure_single_trajectory.ax2.plot(self.traj_creator.time_grid[0:-1], self.traj_creator.energy_grid_der,
                                               'r')
        self.figure_single_trajectory.ax2.set_ylabel('Velocity (eV/s)')
        self.canvas_single_trajectory.draw_idle()

        # Tile trajectory
        self.figure_full_trajectory.ax.clear()
        self.toolbar_full_trajectory._views.clear()
        self.toolbar_full_trajectory._positions.clear()
        self.toolbar_full_trajectory._update_view()
        self.canvas_full_trajectory.draw_idle()
        self.traj_creator.tile(reps=self.spinBox_tiling_repetitions.value(),
                               single_direction=self.checkBox_traj_single_dir.isChecked())

        # Convert to encoder counts
        self.traj_creator.e2encoder(float(self.label_angle_offset.text()))

        # Draw
        self.figure_full_trajectory.ax.plot(self.traj_creator.encoder_grid, 'b')
        self.figure_full_trajectory.ax.set_xlabel('Servo event / 1/16000 s')
        self.figure_full_trajectory.ax.set_ylabel('Encoder count')
        self.canvas_full_trajectory.draw_idle()

        self.push_save_trajectory.setEnabled(True)

    def save_trajectory(self):
        filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save trajectory...', self.trajectory_path, '*.txt',
                                                         options=QtWidgets.QFileDialog.DontConfirmOverwrite)[0]
        if filename[-4:] == '.txt':
            filename = filename[:-4]
        if filename[filename.find(self.e0):] == self.e0:
            filename = filename[:filename.find(self.e0) - 1]
        filename += '-{}'.format(self.e0)
        print(filename)
        if len(filename):
            fileName, fileExtension = os.path.splitext(filename)
            if fileExtension is not '.txt':
                filename = fileName + '.txt'
            print(filename)
            if (os.path.isfile(filename)):
                ret = self.questionMessage('Save trajectory...', '{} already exists. Do you want to replace it?'.format(
                    filename.rsplit('/', 1)[1]))
                if not ret:
                    print('Aborted!')
                    return
            np.savetxt(filename,
                       self.traj_creator.energy_grid, fmt='%.6f',
                       header = f'element: {self.traj_creator.elem}, edge: {self.traj_creator.edge}, E0: {self.traj_creator.e0}')
            call(['chmod', '666', filename])
            self.trajectory_path = filename[:filename.rfind('/')] + '/'
            self.label_current_trajectory.setText(filename.rsplit('/', 1)[1])
            self.push_plot_traj.setEnabled(True)
            print('Trajectory saved! [{}]'.format(filename))

    def plot_traj_file(self):
        self.traj_creator.load_trajectory_file(self.trajectory_path + self.label_current_trajectory.text(),
                                               float(self.label_angle_offset.text()), is_energy=True)

        self.figure_single_trajectory.ax.clear()
        self.figure_single_trajectory.ax2.clear()
        self.toolbar_single_trajectory._views.clear()
        self.toolbar_single_trajectory._positions.clear()
        self.toolbar_single_trajectory._update_view()
        self.figure_full_trajectory.ax.clear()
        self.toolbar_full_trajectory._views.clear()
        self.toolbar_full_trajectory._positions.clear()
        self.toolbar_full_trajectory._update_view()
        self.canvas_single_trajectory.draw_idle()
        self.canvas_full_trajectory.draw_idle()

        self.figure_full_trajectory.ax.plot(np.arange(0, len(self.traj_creator.energy_grid_loaded) / 16000, 1 / 16000),
                                            self.traj_creator.energy_grid_loaded, 'b')
        self.figure_full_trajectory.ax.set_xlabel('Time /s')
        self.figure_full_trajectory.ax.set_ylabel('Energy /eV')
        self.figure_full_trajectory.ax.set_title(self.label_current_trajectory.text())
        self.canvas_full_trajectory.draw_idle()
        print('Trajectory Load: Done')

        self.push_save_trajectory.setDisabled(True)

    def load_trajectory(self):
        self.traj_manager.load(orig_file_name=self.label_current_trajectory.text(),
                               new_file_path=self.comboBox_slot_to_load_trajectory.currentText(),
                               is_energy=True, offset=float(self.label_angle_offset.text()))
        self.trajectoriesChanged.emit()

    def init_trajectory(self):
        self.traj_manager.init(int(self.comboBox_slot_to_init_trajectory.currentText()))

    def read_trajectory_info(self):
        self.traj_manager.read_info()

    def update_offset(self):
        dlg = UpdateAngleOffset.UpdateAngleOffset(self.label_angle_offset.text(), parent=self)
        if dlg.exec_():
            try:
                self.hhm.angle_offset.put(float(dlg.getValues()))
                self.update_angle_offset(value=float(dlg.getValues()))
            except Exception as exc:
                if type(exc) == ophyd_utils.errors.LimitError:
                    print('[New offset] {}. No reason to be desperate, though.'.format(exc))
                else:
                    print('[New offset] Something went wrong, not the limit: {}'.format(exc))
                return 1
            return 0

    def get_traj_names(self):
        filepath = QtWidgets.QFileDialog.getOpenFileName(directory=self.trajectory_path, filter='*.txt', parent=self)[0]
        self.label_current_trajectory.setText(filepath.rsplit('/', 1)[1])
        self.trajectory_path = filepath[:filepath.rfind('/')] + '/'
        self.push_plot_traj.setEnabled(True)

    def update_E0(self, text):
        self.e0 = text

    def update_edge(self, text):
        self.edge = text

    def update_element(self, text):
        self.element = text

    def update_repetitions_spinbox(self):
        if self.checkBox_traj_single_dir.isChecked():
            self.spinBox_tiling_repetitions.setValue(1)
            self.spinBox_tiling_repetitions.setEnabled(0)
        else:
            self.spinBox_tiling_repetitions.setEnabled(1)

    def questionMessage(self, title, question):
        reply = QtWidgets.QMessageBox.question(self, title,
                                               question,
                                               QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        if reply == QtWidgets.QMessageBox.Yes:
            return True
        elif reply == QtWidgets.QMessageBox.No:
            return False
        else:
            return False