Ejemplo n.º 1
0
    def __init__(self, data=None, call_exec=False, loglevel=logging.INFO,
                 interactive=True):
        """

        :param data: Series | Dataframe | [Series] | {str: Series} | None
        :param call_exec: bool
            Block by calling app.exec_() and exit on close.
            Use call_exec=False if running interactively from python prompt.
        :param loglevel: loglevel the app will log at
        :param interactive: bool
            If not run in an interactive prompt, set this to False. Used for
            configuring inputhook under ipython.
        """
        global QtGui
        logging.basicConfig(
            level=loglevel,
            format="%(asctime)s %(levelname)-8s [%(name)s] : %(message)s"
        )
        logger.debug('Initializing Inspector ...')
        logger.debug('Using pyqt5: %s', is_pyqt5())
        # Make sure that we use any pre-existing QApplication instance
        if interactive:
            shell = get_ipython_if_any()
            if shell:
                if not shell._inputhook or shell._inputhook.__module__.endswith('.qt'):
                    shell.enable_gui('qt')
                    logger.info("Enabled 'qt' gui in current ipython shell")
        app = QtWidgets.QApplication.instance()
        self.app = app or QtWidgets.QApplication(sys.argv)
        QtGui.qApp = self.app

        self.model = Model()
        self.view = View(self.model, data=data, interactive=interactive)
        if call_exec:
            sys.exit(self.app.exec_())
Ejemplo n.º 2
0
def plot_data(x:np.ndarray, y:np.ndarray, xlabel, ylabel):
    """
    Creates a matplotlib plot with all the bells and whistles
    x       - the x axis data
    y       - the y axis data
    xlabel  - a label for the x axis
    ylabel  - a label for the y axis
    """
    from matplotlib.backends.qt_compat import QtWidgets
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar
    from matplotlib.figure import Figure
    class ApplicationWindow(QtWidgets.QMainWindow):
        def __init__(self):
            super().__init__()
            self._main = QtWidgets.QWidget()
            self.setCentralWidget(self._main)

            layout = QtWidgets.QVBoxLayout(self._main)
            static_canvas = FigureCanvas(Figure(figsize=(6,6)))
            layout.addWidget(static_canvas)
            self.addToolBar(NavigationToolbar(static_canvas, self))

            self.static_ax = static_canvas.figure.subplots()
            self.static_ax.plot(x,y,'.')
            self.static_ax.set_xlabel(xlabel)
            self.static_ax.set_ylabel(ylabel)
            self.static_ax.set_title(ylabel + ' as a function of ' + xlabel)
            self.static_canvas.figure.savefig('/media/usb1/DYNODATA/drive/plot'+str(len(os.listdir('/media/usb1/DYNODATA/drive/test')))+'.csv')
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    qapp.exec_()
Ejemplo n.º 3
0
def _create_qApp():
    """
    Only one qApp can exist at a time, so check before creating one.
    """
    global qApp

    if qApp is None:
        app = QtWidgets.QApplication.instance()
        if app is None:
            # check for DISPLAY env variable on X11 build of Qt
            if is_pyqt5():
                try:
                    from PyQt5 import QtX11Extras
                    is_x11_build = True
                except ImportError:
                    is_x11_build = False
            else:
                is_x11_build = hasattr(QtGui, "QX11Info")
            if is_x11_build:
                display = os.environ.get('DISPLAY')
                if display is None or not re.search(r':\d', display):
                    raise RuntimeError('Invalid DISPLAY variable')

            qApp = QtWidgets.QApplication([b"matplotlib"])
            qApp.lastWindowClosed.connect(qApp.quit)
        else:
            qApp = app

    if is_pyqt5():
        try:
            qApp.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
            qApp.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
        except AttributeError:
            pass
Ejemplo n.º 4
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    if len(sys.argv) != 2:
        print(sys.argv)
        print('Please supply the fits file for the data')
        sys.exit()
    else:
        AppWin = ApplicationWindow(sys.argv[1])
        AppWin.show()
        sys.exit(app.exec_())
Ejemplo n.º 5
0
def runMe(cmd_args):
    # Check whether there is already a running QApplication (e.g., if running
    # from an IDE).
    qapp = QtWidgets.QApplication.instance()
    if not qapp:
        qapp = QtWidgets.QApplication(sys.argv)
    app = MainApp('Iseult', cmd_args)
    app.show()
    app.activateWindow()
    app.raise_()
    qapp.exec_()
Ejemplo n.º 6
0
def test_form_widget_get_with_datetime_and_date_fields():
    if not QtWidgets.QApplication.instance():
        QtWidgets.QApplication()
    form = [("Datetime field", datetime(year=2021, month=3, day=11)),
            ("Date field", date(year=2021, month=3, day=11))]
    widget = _formlayout.FormWidget(form)
    widget.setup()
    values = widget.get()
    assert values == [
        datetime(year=2021, month=3, day=11),
        date(year=2021, month=3, day=11)
    ]
Ejemplo n.º 7
0
def visualization(model, snapshot, tub):
    Model = load_model_class(model)
    model = Model()
    model.load(os.path.expanduser(snapshot))

    reader = ExtendedRecordsReader(tub, model)

    qapp = QtWidgets.QApplication([])
    app = ApplicationWindow(reader)
    app.show()
    qapp.exec_()
    print("exited")
Ejemplo n.º 8
0
def xncview(dataset):
    """
    Starts a QT window to display the data

    Args:
        dataset: xarray.Dataset
    """
    QApp = QW.QApplication.instance()
    if QApp is None:
        QApp = QW.QApplication(sys.argv)

    widget = Widget(dataset)
    widget.resize(1200, 800)
    widget.show()

    return QApp.exec_()
Ejemplo n.º 9
0
 def __init__(self, plot_callback=None, call_exec=False, interactive=True):
     if interactive:
         shell = get_ipython_if_any()
         if shell and not shell._inputhook.__module__.endswith('.qt'):
             shell.enable_gui('qt')
             logger.info("Enabled 'qt' gui in current ipython shell")
     maybe_existing_app = QtWidgets.QApplication.instance()
     self.app = maybe_existing_app or QtWidgets.QApplication(sys.argv)
     from matplotlib.backends.qt_compat import QtGui
     QtGui.qApp = self.app
     if plot_callback is None:
         plot_callback = default_sample_plot
     self.builder = StyleBuilderMainWidget(plot_callback)
     self.builder.build_tree()
     if call_exec:
         sys.exit(self.app.exec_())
Ejemplo n.º 10
0
def launch(result_images, source):
    """
    Launch the GUI.
    """
    entries = find_failing_tests(result_images, source)

    if len(entries) == 0:
        print("No failed tests")
        sys.exit(0)

    app = QtWidgets.QApplication(sys.argv)
    dialog = Dialog(entries)
    dialog.show()
    filter = EventFilter(dialog)
    app.installEventFilter(filter)
    sys.exit(app.exec_())
Ejemplo n.º 11
0
def preview(data_object):
    """Quick preview od the dataset."""
    axes = []
    data = deepcopy(data_object)
    # for i, dim in enumerate(data.dimensions):
    #     if hasattr(dim, "complex_fft"):
    #         if dim.complex_fft:
    #             npts = dim.count
    #             if npts % 2 == 0:
    #                 temp = npts * dim.increment / 2.0
    #             else:
    #                 temp = (npts - 1) * dim.increment / 2.0
    #             dim.coordinates_offset = dim.coordinates_offset - temp

    #             axes.append(-i - 1)
    #             dim.complex_fft = False

    for var in data.dependent_variables:
        var.components = fftshift(var.components, axes=axes)

    # print(matplotlib.get_backend())

    if matplotlib.get_backend() in ["Qt5Agg", "Qt4Agg"]:
        x = data.dimensions
        number_of_independents = len(x)
        if number_of_independents == 0:
            print("Preview of zero dimensional datasets is not implemented.")
            return

        if number_of_independents > 2:
            print(
                "Preview of three or higher dimensional datasets " "is not implemented."
            )
            return

        if np.any([x[i].type == "labeled" for i in range(len(x))]):
            print("Preview of labeled plots is not implemented.")
            return

        qapp = QtWidgets.QApplication(sys.argv)
        app = ApplicationWindow(data)
        app.show()
        sys.exit(qapp.exec_())
    else:
        _preview(data)
Ejemplo n.º 12
0
def fedit(data, title="", comment="", icon=None, parent=None, apply=None):
    """
    Create form dialog and return result
    (if Cancel button is pressed, return None)

    data: datalist, datagroup
    title: str
    comment: str
    icon: QIcon instance
    parent: parent QWidget
    apply: apply callback (function)

    datalist: list/tuple of (field_name, field_value)
    datagroup: list/tuple of (datalist *or* datagroup, title, comment)

    -> one field for each member of a datalist
    -> one tab for each member of a top-level datagroup
    -> one page (of a multipage widget, each page can be selected with a combo
       box) for each member of a datagroup inside a datagroup

    Supported types for field_value:
      - int, float, str, unicode, bool
      - colors: in Qt-compatible text form, i.e. in hex format or name
                (red, ...) (automatically detected from a string)
      - list/tuple:
          * the first element will be the selected index (or value)
          * the other elements can be couples (key, value) or only values
    """

    # Create a QApplication instance if no instance currently exists
    # (e.g., if the module is used directly from the interpreter)
    if QtWidgets.QApplication.startingUp():
        _app = QtWidgets.QApplication([])
    dialog = FormDialog(data, title, comment, icon, parent, apply)

    if parent is not None:
        if hasattr(parent, "_fedit_dialog"):
            parent._fedit_dialog.close()
        parent._fedit_dialog = dialog

    dialog.show()
Ejemplo n.º 13
0
    def __init__(self):
        self.qapp = QtWidgets.QApplication(sys.argv)
        super(TimePlot, self).__init__()
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        self.layout = QtWidgets.QGridLayout(self._main)

        # Empty objects that will be used during visualization.
        self.fig = None
        self.frames = None

        # Slider stuff
        hbox_timeline = QtWidgets.QHBoxLayout()
        self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
        self.slider.setMinimum(0)
        self.slider.valueChanged.connect(self.slider_valuechanged)
        hbox_timeline.addWidget(self.slider)
        self.layout.addLayout(hbox_timeline, 1, 0)

        # Bottom buttons
        hbox_buttons = QtWidgets.QHBoxLayout()
        hbox_buttons.addStretch(1)
        # Button for saving movies.
        save_movie_btn = QtWidgets.QPushButton(
            "&Save as movie")  # Shortcut is Alt+S
        save_movie_btn.clicked.connect(self._save_movie_clicked)
        # Button for next episode.
        next_btn = QtWidgets.QPushButton("&Next episode")  # Shortcut is Alt+N
        next_btn.clicked.connect(self._next_clicked)
        # Quit button.
        quit_btn = QtWidgets.QPushButton("&Quit")  # Shortcut is Alt+Q
        quit_btn.clicked.connect(self.closeEvent)
        # Add buttons to widget.
        hbox_buttons.addWidget(save_movie_btn)
        hbox_buttons.addWidget(next_btn)
        hbox_buttons.addWidget(quit_btn)
        self.layout.addLayout(hbox_buttons, 2, 0)

        self.is_closed = False
        self.is_playing = False
Ejemplo n.º 14
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    if len(sys.argv) < 2:
        print(sys.argv)
        print('Please supply the python script that defines the model')
        sys.exit()
    elif len(sys.argv) == 2:
        if sys.argv[1].endswith('.py'):
            sys.argv[1] = sys.argv[1][:-3]
        AppWin = ApplicationWindow(sys.argv[1])
        AppWin.show()
        sys.exit(app.exec_())
    elif len(sys.argv) == 3:
        if sys.argv[1].endswith('.py'):
            sys.argv[1] = sys.argv[1][:-3]
        AppWin = ApplicationWindow(sys.argv[1], sys.argv[2])
        AppWin.show()
        sys.exit(app.exec_())
    else:
        print(sys.argv)
        print('Too many arguments supplied to the funcion.')
        sys.exit()
        self._static_ax.plot(t, np.tan(t), ".")

        self._dynamic_ax = dynamic_canvas.figure.subplots()
        self._timer = dynamic_canvas.new_timer(50)
        self._timer.add_callback(self._update_canvas)
        self._timer.start()

    def _update_canvas(self):
        self._dynamic_ax.clear()
        t = np.linspace(0, 10, 101)
        # Use fixed vertical limits to prevent autoscaling changing the scale
        # of the axis.
        self._dynamic_ax.set_ylim(-1.1, 1.1)
        # Shift the sinusoid as a function of time.
        self._dynamic_ax.plot(t, np.sin(t + time.time()))
        self._dynamic_ax.figure.canvas.draw()


if __name__ == "__main__":
    # Check whether there is already a running QApplication (e.g., if running
    # from an IDE).
    qapp = QtWidgets.QApplication.instance()
    if not qapp:
        qapp = QtWidgets.QApplication(sys.argv)

    app = ApplicationWindow()
    app.show()
    app.activateWindow()
    app.raise_()
    qapp.exec_()
Ejemplo n.º 16
0
from pygerm import TRIGGER_SETUP_SEQ, START_DAQ, STOP_DAQ

import time as tm


import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.qt_compat import QtWidgets, QtCore
plt.ion()


# Create an QApplication object.
a = QtWidgets.QApplication.instance()
if a is None:
    a = QtWidgets.QApplication(["MARS DAQ"])
    a.lastWindowClosed.connect(a.quit)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QtWidgets.QWidget()

# Set window size.
w.resize(320, 140)

# Set window title
w.setWindowTitle("MARS DAQ!")

# Add a button
btn_q = QtWidgets.QPushButton('Quit!', w)
btn_trig = QtWidgets.QPushButton('DAQ Trigger', w)
Ejemplo n.º 17
0
def show(time, data, com, com_dot, com_ddot, com_i, grf, angles, stick):
    qapp = QtWidgets.QApplication(sys.argv)
    app = QtWidgets.QMainWindow()
    app.setWindowTitle("Analyse biomécanique de Kinovea")

    _main = QtWidgets.QWidget()
    app.setCentralWidget(_main)
    main_layout = QtWidgets.QHBoxLayout(_main)

    # Body position column
    body_position_layout = QtWidgets.QVBoxLayout()
    main_layout.addLayout(body_position_layout)

    # Show model
    body_position_canvas = FigureCanvas(Figure(figsize=(5, 3)))
    body_position_layout.addWidget(body_position_canvas)
    body_position_ax = body_position_canvas.figure.subplots()

    time_idx = 0
    body_position_ax.set_ylabel("Axe vertical (m)")
    body_position_ax.set_xlabel("Axe frontal (m)")
    body_position_text = body_position_ax.text(
        0.5, 0.99, "", fontsize=12, horizontalalignment='center', verticalalignment='top', transform=body_position_ax.transAxes
    )

    kino_n_image = 5
    kino_pre_plot = []
    kino_post_plot = []
    kino_colors = np.linspace(0.88, 0, kino_n_image)
    for i in range(kino_n_image):
        i2 = kino_n_image - 1 - i
        kino_pre_plot.append(
            body_position_ax.plot(np.nan, np.nan, color=[kino_colors[i2], kino_colors[i2], kino_colors[i2]])
        )
        kino_post_plot.append(
            body_position_ax.plot(np.nan, np.nan, color=[kino_colors[i2], kino_colors[i2], kino_colors[i2]])
        )

    stick_plot = body_position_ax.plot(np.nan, np.nan, 'r')
    comi_plot = body_position_ax.plot(np.nan, np.nan, 'k.')
    com_plot = body_position_ax.plot(np.nan, np.nan, 'k.', markersize=20)

    def move_stick_figure(time_idx):
        body_position_ax.set_title(f"Position du corps à l'instant {time[time_idx]:.2f} s")

        body_position_text.set_text(f"CoM = [{str(np.round(com[0, 0, time_idx], 2))}; {str(np.round(com[1, 0, time_idx], 2))}]")

        for i in range(kino_n_image):
            if time_idx - i - 1 >= 0 and kino_pre_check.isChecked():
                kino_pre_plot[i][0].set_data(data[0, stick, time_idx - i - 1], data[1, stick, time_idx - i - 1])
            else:
                kino_pre_plot[i][0].set_data(np.nan, np.nan)
            if time_idx + i + 1 < data.shape[2] and kino_post_check.isChecked():
                kino_post_plot[i][0].set_data(data[0, stick, time_idx + i + 1], data[1, stick, time_idx + i + 1])
            else:
                kino_post_plot[i][0].set_data(np.nan, np.nan)

        stick_plot[0].set_data(data[0, stick, time_idx], data[1, stick, time_idx])
        comi_plot[0].set_data(com_i[0, :, time_idx], com_i[1, :, time_idx])
        com_plot[0].set_data(com[0, 0, time_idx], com[1, 0, time_idx])

    # Force axis equal with min and max data
    body_position_ax.plot(
        [np.min(data[0, :, :]), np.max(data[0, :, :])],
        [np.min(data[1, :, :]) - (np.max(data[1, :, :]) - np.min(data[1, :, :]))*0.1 ,
                              np.max(data[1, :, :]) + (np.max(data[1, :, :]) - np.min(data[1, :, :]))*0.1 ], 'w.'
    )
    body_position_ax.axis('equal')

    time_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
    body_position_layout.addWidget(time_slider)

    kinogram_layout = QtWidgets.QHBoxLayout()
    body_position_layout.addLayout(kinogram_layout)
    kino_pre_check = QtWidgets.QCheckBox()
    kino_pre_check.setText("Kinogramme pre")
    kinogram_layout.addWidget(kino_pre_check)
    kino_post_check = QtWidgets.QCheckBox()
    kino_post_check.setText("Kinogramme post")
    kinogram_layout.addWidget(kino_post_check)

    # Trajectory column
    trajectory_canvas = FigureCanvas(Figure(figsize=(5, 3)))
    main_layout.addWidget(trajectory_canvas)
    buffer = (time[-1]-time[0])*0.005
    xlim = (time[0]-buffer, time[-1]+buffer)

    ax_height = trajectory_canvas.figure.add_subplot(411)
    ax_height.set_title("Hauteur du CoM")
    ax_height.set_ylabel("Hauteur (m)")
    ax_height.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
    ax_height.plot(time, com[1, 0, :])
    ylim = ax_height.get_ylim()
    height_vbar = ax_height.plot((np.nan, np.nan), ylim, 'r')
    ax_height.set_xlim(xlim)
    ax_height.set_ylim(ylim)

    ax_velocity = trajectory_canvas.figure.add_subplot(412)
    ax_velocity.set_title("Vitesse verticale")
    ax_velocity.set_ylabel("Vitesse (m/s)")
    ax_velocity.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
    ax_velocity.plot(time, com_dot[1, 0, :])
    ylim = ax_velocity.get_ylim()
    velocity_vbar = ax_velocity.plot((np.nan, np.nan), ylim, 'r')
    ax_velocity.set_xlim(xlim)
    ax_velocity.set_ylim(ylim)

    ax_acceleration = trajectory_canvas.figure.add_subplot(413)
    ax_acceleration.set_title("Accélération verticale")
    ax_acceleration.set_ylabel("Accélération (m/s²)")
    ax_acceleration.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
    ax_acceleration.plot(time, com_ddot[1, 0, :])
    ylim = ax_acceleration.get_ylim()
    acceleration_vbar = ax_acceleration.plot((np.nan, np.nan), ylim, 'r')
    ax_acceleration.set_xlim(xlim)
    ax_acceleration.set_ylim(ylim)

    ax_grf = trajectory_canvas.figure.add_subplot(414)
    ax_grf.set_title("GRF")
    ax_grf.set_ylabel("GRF (N)")
    ax_grf.set_xlabel("Temps (s)")
    ax_grf.plot(time, grf[1, 0, :])
    ylim = ax_grf.get_ylim()
    grf_vbar = ax_grf.plot((np.nan, np.nan), ylim, 'r')
    ax_grf.set_xlim(xlim)
    ax_grf.set_ylim(ylim)

    trajectory_canvas.figure.tight_layout(h_pad=-0.5, w_pad=-6)

    # Angles column
    angles_canvas = FigureCanvas(Figure(figsize=(5, 3)))
    main_layout.addWidget(angles_canvas)
    ax_angles = angles_canvas.figure.subplots()
    ax_angles.set_title("Angles articulaire au cours du temps")
    ax_angles.set_ylabel("Angle (°)")
    ax_angles.set_xlabel("Temps (s)")
    for joint in angles.values():
        ax_angles.plot(time, KinoveaReader.to_degree(joint))
    ylim = ax_angles.get_ylim()
    angles_vbar = ax_angles.plot((np.nan, np.nan), ylim, 'r')
    ax_angles.set_xlim(xlim)
    ax_angles.set_ylim(ylim)
    ax_angles.legend(angles.keys())

    def change_time():
        time_idx = time_slider.value()

        move_stick_figure(time_idx)
        body_position_canvas.draw()

        height_vbar[0].set_xdata([time[time_idx], time[time_idx]])
        velocity_vbar[0].set_xdata([time[time_idx], time[time_idx]])
        acceleration_vbar[0].set_xdata([time[time_idx], time[time_idx]])
        grf_vbar[0].set_xdata([time[time_idx], time[time_idx]])
        trajectory_canvas.draw()

        angles_vbar[0].set_xdata([time[time_idx], time[time_idx]])
        angles_canvas.draw()

    time_slider.setMinimum(0)
    time_slider.setMaximum(time.shape[0] - 1)
    time_slider.setPageStep(1)
    time_slider.setValue(0)
    time_slider.valueChanged.connect(change_time)
    body_position_canvas.mpl_connect(body_position_canvas.resize_event, change_time)
    kino_pre_check.stateChanged.connect(change_time)
    kino_post_check.stateChanged.connect(change_time)

    # app.showMaximized()
    change_time()
    app.show()
    qapp.exec_()
Ejemplo n.º 18
0
        self.editing = False
        self.lower_double.hide()
        self.lower_single.hide()
        self.all_plots.redraw()

    def update_selection(self):
        if self.selected_ipo == self.all_plots.ipo_y_phase:
            self.select_pv(self.selected_ipo, self.selected_y)
        else:
            self.select(self.selected_ipo, self.selected_y)

    def keyPressEvent(self, e):
        key = e.key()
        if key == Qt.Key_Escape:
            self.close()
        elif key == Qt.Key_F:
            self.selected_y += 1
            self.update_selection()
        elif key == Qt.Key_S:
            self.selected_y -= 1
            self.update_selection()


if __name__ == "__main__":
    # if we don't pass the style, we'll get some warnings
    # https://github.com/therecipe/qt/issues/306
    qapp = QtWidgets.QApplication(['main.py', '--style', 'Fusion'])
    app = ApplicationWindow()
    app.show()
    qapp.exec_()
Ejemplo n.º 19
0
    @QtCore.pyqtSlot()
    def toggle_pulser(self):
        req = wib.Pulser()
        if self.pulser_button.text() == "Enable Pulser":
            req.start = True
            self.pulser_button.setText('Disable Pulser')
            print("Starting pulser")
        else:
            req.start = False
            self.pulser_button.setText('Enable Pulser')
            print("Stopping pulser")
        rep = wib.Status()
        self.send_command(req,rep);


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Visually display data from a WIB')
    parser.add_argument('--wib_server','-w',default='127.0.0.1',help='IP of wib_server to connect to [127.0.0.1]')
    parser.add_argument('--config','-C',default='default.json',help='WIB configuration to load [default.json]')
    parser.add_argument('--rows','-r',default=1,type=int,help='Rows of plots [1]')
    parser.add_argument('--cols','-c',default=1,type=int,help='Columns of plots [1]')
    parser.add_argument('--layout','-l',default=None,help='Load a saved layout')
    args = parser.parse_args()
    
    
    qapp = QtWidgets.QApplication([])
    qapp.setApplicationName('WIB Scope (%s)'%args.wib_server)
    app = EvDisp(**vars(args))
    app.show()
    qapp.exec_()
Ejemplo n.º 20
0
def main():
    e = 2.718281828459045235360287471352662497757247093699959574966967627724076630353
    app = QtWidgets.QApplication(sys.argv)
    application = ApplicationWindow()
    application.show()
    sys.exit(app.exec_())
Ejemplo n.º 21
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    w = Program()
    w.show()
    sys.exit(app.exec_())
Ejemplo n.º 22
0
def gui():
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    qapp.exec()
Ejemplo n.º 23
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    form = Form()
    form.show()
    app.exec_()
Ejemplo n.º 24
0
def default_during_task(blocking_event):
    """
    The default setting for the RunEngine's during_task parameter.

    This makes it possible for plots that use matplotlib's Qt backend to update
    live during data acquisition.

    It solves the problem that Qt must be run from the main thread.
    If matplotlib and a known Qt binding are already imported, run the
    matplotlib qApp until the task completes. If not, there is no need to
    handle qApp: just wait on the task.
    """
    global _qapp
    if 'matplotlib' not in sys.modules:
        # We are not using matplotlib + Qt. Just wait on the Event.
        blocking_event.wait()
    # Figure out if we are using matplotlib with which backend
    # without importing anything that is not already imported.
    else:
        import matplotlib
        backend = matplotlib.get_backend().lower()
        # if with a Qt backend, do the scary thing
        if 'qt' in backend:
            from matplotlib.backends.qt_compat import QtCore, QtWidgets
            app = QtWidgets.QApplication.instance()
            if app is None:
                _qapp = app = QtWidgets.QApplication([b'bluesky'])
            assert app is not None
            event_loop = QtCore.QEventLoop()

            def start_killer_thread():
                def exit_loop():
                    blocking_event.wait()
                    # If the above wait ends quickly, we need to avoid the race
                    # condition where this thread might try to exit the qApp
                    # before it even starts.  Therefore, we use QTimer, below,
                    # which will not start running until the qApp event loop is
                    # running.
                    event_loop.exit()

                threading.Thread(target=exit_loop).start()

            # https://www.riverbankcomputing.com/pipermail/pyqt/2015-March/035674.html
            # adapted from code at
            # https://bitbucket.org/tortoisehg/thg/commits/550e1df5fbad
            if os.name == 'posix' and hasattr(signal, 'set_wakeup_fd'):
                # Wake up Python interpreter via pipe so that SIGINT
                # can be handled immediately.
                # (http://qt-project.org/doc/qt-4.8/unix-signals.html)
                # Updated docs:
                # https://doc.qt.io/qt-5/unix-signals.html
                import fcntl
                rfd, wfd = os.pipe()
                for fd in (rfd, wfd):
                    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
                    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
                wakeupsn = QtCore.QSocketNotifier(rfd,
                                                  QtCore.QSocketNotifier.Read)
                origwakeupfd = signal.set_wakeup_fd(wfd)

                def cleanup():
                    wakeupsn.setEnabled(False)
                    rfd = wakeupsn.socket()
                    wfd = signal.set_wakeup_fd(origwakeupfd)
                    os.close(int(rfd))
                    os.close(wfd)

                def handleWakeup(inp):
                    # here Python signal handler will be invoked
                    # this book-keeping is to drain the pipe
                    wakeupsn.setEnabled(False)
                    rfd = wakeupsn.socket()
                    try:
                        os.read(int(rfd), 4096)
                    except OSError as inst:
                        print('failed to read wakeup fd: %s\n' % inst)

                    wakeupsn.setEnabled(True)

                wakeupsn.activated.connect(handleWakeup)

            else:
                # On Windows, non-blocking anonymous pipe or socket is
                # not available.

                def null():
                    ...

                # we need to 'kick' the python interpreter so it sees
                # system signals
                # https://stackoverflow.com/a/4939113/380231
                kick_timer = QtCore.QTimer()
                kick_timer.timeout.connect(null)
                kick_timer.start(50)

                cleanup = kick_timer.stop

            # we also need to make sure that the qApp never sees
            # exceptions raised by python inside of a c++ callback (as
            # it will segfault its self because due to the way the
            # code is called there is no clear way to propgate that
            # back to the python code.
            vals = (None, None, None)

            old_sys_handler = sys.excepthook

            def my_exception_hook(exctype, value, traceback):
                nonlocal vals
                vals = (exctype, value, traceback)
                event_loop.exit()
                old_sys_handler(exctype, value, traceback)

            # this kill the Qt event loop when the plan is finished
            killer_timer = QtCore.QTimer()
            killer_timer.setSingleShot(True)
            killer_timer.timeout.connect(start_killer_thread)
            killer_timer.start(0)

            try:
                sys.excepthook = my_exception_hook
                event_loop.exec_()
                # make sure any pending signals are processed
                event_loop.processEvents()
                if vals[1] is not None:
                    raise vals[1]
            finally:
                try:
                    cleanup()
                finally:
                    sys.excepthook = old_sys_handler
        elif 'ipympl' in backend or 'nbagg' in backend:
            Gcf = matplotlib._pylab_helpers.Gcf
            while True:
                done = blocking_event.wait(.1)
                for f_mgr in Gcf.get_all_fig_managers():
                    if f_mgr.canvas.figure.stale:
                        f_mgr.canvas.draw()
                if done:
                    return
        else:
            # We are not using matplotlib + Qt. Just wait on the Event.
            blocking_event.wait()
Ejemplo n.º 25
0
def main():
    global app
    app = QtWidgets.QApplication(sys.argv)
    gui = Window()
    sys.exit(app.exec_())
Ejemplo n.º 26
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    application = ApplicationWindow()
    application.show()
    app.exec_()
Ejemplo n.º 27
0
# non-ipython envs
with suppress(ImportError):
    from IPython import get_ipython
with suppress(AttributeError, NameError):
    # List available APIs
    get_ipython().run_line_magic("matplotlib", "-l")
    get_ipython().run_line_magic("matplotlib", "qt5")

print(plt.get_backend())
#%% Matplotlib adjustments
# Adjust matplotlib qt5 backend for high DPI monitors
if plt.get_backend() == "Qt5Agg":
    from matplotlib.backends.qt_compat import QtWidgets  # pylint: disable=C0412
    from sys import argv

    qApp = QtWidgets.QApplication(argv)
    plt.matplotlib.rcParams["figure.dpi"] = qApp.desktop().physicalDpiX()

# Set LaTeX compatibility settings
# matplotlib.use("pgf")
matplotlib.rcParams.update({
    "pgf.texsystem": "pdflatex",
    "font.family": "sans-serif",
    "text.usetex": True,
    "pgf.rcfonts": False,
})

# plt.rcParams["figure.autolayout"] = True

# Adjust figure default size
plt.rcParams["figure.figsize"] = (6, 4)  # Default fig size (w, h))
Ejemplo n.º 28
0
def show_GUI(pupil, luminance_range):
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow(pupil, luminance_range)
    app.show()
    qapp.exec_()