Esempio n. 1
0
 def _init_fields_(self):
     # * 1st field
     self._operator_b = widg.Button(self._choose_operator,
                                    r'Обирати оператор L',
                                    color='#ff9900')
     self._operator_b.on_clicked(self.callback.operator_listbox)
     # * 2nd field
     self._function_b = widg.Button(self._choose_function,
                                    "Оберати функцію y(x, t)",
                                    color='#ff9900')
     self._function_b.on_clicked(self.callback.function_listbox)
     # * 3rd field
     plt.text(-8.2,
              10.2,
              "Введіть значення часу T для",
              fontsize=15,
              style='italic')
     plt.text(-8.2, 9.7, "  інтервалу [0, T]:", fontsize=15, style='italic')
     self._valueT_txtbox = widg.TextBox(self._T_field, "T = ", initial="0")
     self._valueT_txtbox.on_submit(self.callback.submit_T)
     plt.text(-8.2,
              7.9,
              "Введіть значення границі спостереження",
              fontsize=15,
              style='italic')
     plt.text(-8.2,
              7.4,
              "  a та b інтервалу [a, b]:",
              fontsize=15,
              style='italic')
     self._valuea_txtbox = widg.TextBox(self._a_field, "a = ", initial="0")
     self._valuea_txtbox.on_submit(self.callback.submit_a)
     self._valueb_txtbox = widg.TextBox(self._b_field, "b = ", initial="0")
     self._valueb_txtbox.on_submit(self.callback.submit_b)
     # * 4th field
     self._chose_ab_T_dots = widg.Button(self._mark_dots,
                                         "Позначити точки",
                                         color='#ff9900')
     self._chose_ab_T_dots.on_clicked(self.callback.dot_marker)
     # * EVALUATE button
     self._eval_button = widg.Button(self._eval_field,
                                     "Обрахувати",
                                     color='#339900')
     self._eval_button.on_clicked(self.callback.evaluateB)
     # * Border Show button
     self._border_button = widg.Button(self._border_field,
                                       "Показати на границях",
                                       color='#339900')
     self._border_button.on_clicked(self.callback.borderB)
Esempio n. 2
0
def test_TextBox(toolbar):
    # Avoid "toolmanager is provisional" warning.
    dict.__setitem__(plt.rcParams, "toolbar", toolbar)

    from unittest.mock import Mock
    submit_event = Mock()
    text_change_event = Mock()
    ax = get_ax()
    tool = widgets.TextBox(ax, '')
    tool.on_submit(submit_event)
    tool.on_text_change(text_change_event)

    assert tool.text == ''

    do_event(tool, '_click')

    tool.set_val('x**2')

    assert tool.text == 'x**2'
    assert text_change_event.call_count == 1

    tool.begin_typing(tool.text)
    tool.stop_typing()

    assert submit_event.call_count == 2

    do_event(tool, '_click')
    do_event(tool, '_keypress', key='+')
    do_event(tool, '_keypress', key='5')

    assert text_change_event.call_count == 3
def text_box(ax, leftside_label, initial_text, user_callback=None):
    """
    tbox = text_box(ax, leftside_label, initial_text, user_callback=None)

Puts up, in the passed axes ax, a text box with leftside_label (a string)
to its left. Initial text in the box will initial_text (also a string).
If the user_callback is set,, that function will be called with one 
parameter, the string in the box.

    You can also access the string currently in the box through
    
    tbox.text
        
Or, in Julia, with the PyCall syntax

    rab[:text]
    
And you can set the value with 

    rab[:set_value] = your_string

    """
    tbox = Wid.TextBox(ax, leftside_label, initial=initial_text)
    if user_callback != None:
        tbox.on_submit(user_callback)

    return tbox
Esempio n. 4
0
def test_TextBox():
    from unittest.mock import Mock
    submit_event = Mock()
    text_change_event = Mock()
    ax = get_ax()
    tool = widgets.TextBox(ax, '')
    tool.on_submit(submit_event)
    tool.on_text_change(text_change_event)

    assert tool.text == ''

    do_event(tool, '_click')

    tool.set_val('x**2')

    assert tool.text == 'x**2'
    assert text_change_event.call_count == 1

    tool.begin_typing(tool.text)
    tool.stop_typing()

    assert submit_event.call_count == 2

    do_event(tool, '_click')
    do_event(tool, '_keypress', key='+')
    do_event(tool, '_keypress', key='5')

    assert text_change_event.call_count == 3
Esempio n. 5
0
 def __init__(self, function, prompt_text, initial_text, coords, label_pad=0):
     self.function = function
     self.prompt_text = prompt_text
     self.initial_text = initial_text
     self.coords = coords
     self.axis = plt.axes(self.coords)
     self.textbox = mwidgets.TextBox(self.axis, self.prompt_text, initial=self.initial_text, label_pad=label_pad) 
     self.textbox.on_submit(self.function)
 def __init__(self,
              ax,
              label,
              initial='',
              color='.95',
              hovercolor='1',
              label_pad=.01):
     self.widget = mplw.TextBox(ax,
                                label,
                                initial='',
                                color='.95',
                                hovercolor='1',
                                label_pad=.01)
     self.annotation = ''  # The label for corresponding syllable manually entered by user
     self.label = label  # The label of the box (text that appears next to textbox)
Esempio n. 7
0
    def __init__(self, segments=None, gen_n=None):
        self.fig = plt.figure(figsize=(9, 7))

        SPECS = {"width_ratios": [7, 2],
                 "hspace": 0.0,
                 "wspace": 0.0}

        gs1 = plt.GridSpec(1, 2, **SPECS)
        gs1.tight_layout(self.fig)
        gs2 = plt.GridSpec(10, 2, **SPECS)

        self.ax = self.fig.add_subplot(gs1[0])

        self.text_ax = self.ax.text(-100, 105, "Application")

        self.ax.set_aspect("equal")
        self.ax.set_xlim(-100, 100)
        self.ax.set_ylim(-100, 100)

        if segments:
            self.segments = segments
        else:
            self.segments = []

        self.actors = []
        self.c_points = None

        self.fig.canvas.mpl_connect("button_press_event", self.add_segment)

        btn_ax = self.fig.add_subplot(gs2[1])
        self.reset_btn = wig.Button(btn_ax, "Reset")
        self.reset_btn.on_clicked(self.clear)

        initial = str(gen_n) if gen_n else ""

        btn_ax = self.fig.add_subplot(gs2[3])
        self.n_input = wig.TextBox(btn_ax, "N", initial=initial)
        self.n_input.on_submit(self.gen)

        btn_ax = self.fig.add_subplot(gs2[5])
        self.gen_btn = wig.Button(btn_ax, "Generuj")
        self.gen_btn.on_clicked(self.gen)

        if gen_n:
            self.gen()

        self.draw()
        self.fig.show()
Esempio n. 8
0
    def add_widgets(self):
        rect_props = dict(facecolor='blue', alpha=0.5)
        self.span = mwidgets.SpanSelector(self.plot_ax,
                                          self._on_interval_select,
                                          'horizontal',
                                          rectprops=rect_props,
                                          useblit=True)

        all_lr, _ = list(zip(*sorted(self.values[-1][0])))
        init_lr_min = all_lr[0]
        init_lr_max = self.init_lr_max or all_lr[-1]
        init_wd = self.values[-1][1]

        # add the plot controls
        self.plot_lr_min_text: str = ''
        self.plot_lr_max_text: str = ''
        self.plot_lr_min_text = str(init_lr_min)
        self.plot_lr_max_text = str(init_lr_max)
        self.plot_wd_text = str(init_wd)
        self.rerun_wd = init_wd

        self.rerun_lr_min_box = mwidgets.TextBox(self.plot_lr_min_ax,
                                                 label='LR min',
                                                 initial=str(init_lr_min))
        self.rerun_lr_max_box = mwidgets.TextBox(self.plot_lr_max_ax,
                                                 label='LR max',
                                                 initial=str(init_lr_max))
        self.rerun_wd_box = mwidgets.TextBox(self.plot_wd_ax,
                                             label='Weight decay',
                                             initial=str(init_wd))
        self.rerun_btn = mwidgets.Button(self.plot_btn_ax, label='PLOT')

        # add event handling
        self.rerun_lr_min_box.on_text_change(self._on_plot_lr_min_change)
        self.rerun_lr_max_box.on_text_change(self._on_plot_lr_max_change)
        self.rerun_wd_box.on_text_change(self._on_plot_wd_change)
        self.rerun_btn.on_clicked(self._on_rerun_click)

        # add the value input controls
        self.lr_min_text = ''
        self.lr_max_text = ''
        self.wd_text = str(init_wd)

        self.lr_min_box = mwidgets.TextBox(self.lr_min_ax, label='LR min')
        self.lr_max_box = mwidgets.TextBox(self.lr_max_ax, label='LR max')
        self.wd_box = mwidgets.TextBox(self.wd_ax,
                                       label='Weight decay',
                                       initial=str(init_wd))
        self.save_btn = mwidgets.Button(self.btn_ax, label='SAVE')

        # add event handling
        self.rerun_lr_min_box.on_text_change(self._on_lr_min_change)
        self.rerun_lr_max_box.on_text_change(self._on_lr_max_change)
        self.rerun_wd_box.on_text_change(self._on_wd_change)
        self.save_btn.on_clicked(self._on_save_click)
Esempio n. 9
0
    def run(self):
        # Start thread for serial communication:
        self._serialThread.start()

        # Initialize plot:
        fig = pyplot.figure()
        gs = gridspec.GridSpec(9, 6, figure=fig)
        ax0 = fig.add_subplot(gs[:6, :])
        ax1 = fig.add_subplot(gs[6:8, :], sharex=ax0)
        ax2 = fig.add_subplot(gs[8, :2])
        ax3 = fig.add_subplot(gs[8, 2:4])
        ax4 = fig.add_subplot(gs[8, 4])
        ax5 = fig.add_subplot(gs[8, 5])
        axs = (ax0, ax1, ax2, ax3, ax4, ax5)
        box1 = widgets.TextBox(axs[2], 'Lower Limit (°C)')
        box1.on_text_change(self._changeLower)
        box2 = widgets.TextBox(axs[3], 'Upper Limit (°C)')
        box2.on_text_change(self._changeUpper)
        submit = widgets.Button(axs[5], 'Set')
        submit.on_clicked(self._setLimits)
        pyplot.ion()
        pyplot.show()

        # Start main loop:
        while True:
            # Check for messages:
            with self._serialLock:
                while True:
                    try:
                        print(self._serialData['messages'].pop(0))
                    except IndexError:
                        break

            # Acquire data:
            with self._serialLock:
                t = [v[0] for v in self._serialData['history']]
                Tc = [v[1] for v in self._serialData['history']]
                Tl = [v[2] for v in self._serialData['history']]
                Th = [v[3] for v in self._serialData['history']]
                Hs = [v[4] for v in self._serialData['history']]

            # Convert time to seconds relative to the last status:
            if len(t) > 0:
                t = [(v - t[-1]) / 1000. for v in t]

            # Clear plots:
            axs[0].clear()
            axs[1].clear()
            axs[4].clear()
            axs[4].axis('off')

            # Plot new data:
            axs[0].plot(t, Tc, c='tab:blue')
            axs[0].plot(t, Tl, c='tab:red')
            axs[0].plot(t, Th, c='tab:red')
            axs[0].set_ylabel('temperature / °C')
            axs[1].plot(t, Hs, c='tab:blue')
            axs[1].set_xlabel('time / s')
            axs[1].set_ylabel('heater')
            axs[1].set_yticks([0, 1])
            axs[1].set_yticklabels(['off', 'on'])

            # Set status:
            with self._serialLock:
                statusText = self._serialData['status']
            if len(t) > 0:
                statusText += ', %s, %s, %s' % (
                    '%.2f' % Tc[-1] if Tc[-1] is not None else '-',
                    '%.2f' % Tl[-1] if Tl[-1] is not None else '-',
                    '%.2f' % Th[-1] if Th[-1] is not None else '-')
            axs[4].text(0, 0, statusText)

            # Draw plots:
            fig.tight_layout()
            fig.canvas.draw_idle()
            fig.canvas.start_event_loop(2)
Esempio n. 10
0
    def __init__(self, port, baud_rate, timeout=2):

        self.sleep_time = 0.01

        self.tolerance = 20.0
        self.reference = 440.0
        self.differnece = 0.0
        self.tuned = 0
        self.interface_run = False

        self.serial = serial.Serial(port,
                                    baud_rate,
                                    timeout=timeout,
                                    write_timeout=timeout)
        print(self.serial.readline())

        self.fig = plt.figure(figsize=(3, 3))

        self.ui = dict()
        self.ui['ref_textbox_ax'] = self.fig.add_axes([0.4, 0.05, 0.3, 0.1])
        self.ui['ref_textbox'] = widgets.TextBox(self.ui['ref_textbox_ax'],
                                                 'Reference = ',
                                                 initial='440')
        self.ui['ref_textbox'].on_submit(self.set_ref)
        self.ui['ref_units_text_ax'] = self.fig.add_axes(
            [0.73, 0.071, 0.075, 0.075])
        self.ui['ref_units_text_ax'].axis('off')
        self.ui['ref_units_text'] = self.ui['ref_units_text_ax'].text(
            0, 0, 'Hz', ha='left', va='bottom')

        self.ui['tol_textbox_ax'] = self.fig.add_axes([0.4, 0.2, 0.3, 0.1])
        self.ui['tol_textbox'] = widgets.TextBox(self.ui['tol_textbox_ax'],
                                                 'Tolerance = ',
                                                 initial='20')
        self.ui['tol_textbox'].on_submit(self.set_tol)
        self.ui['tol_units_text_ax'] = self.fig.add_axes(
            [0.73, 0.221, 0.075, 0.075])
        self.ui['tol_units_text_ax'].axis('off')
        self.ui['tol_units_text'] = self.ui['tol_units_text_ax'].text(
            0, 0, 'Hz', ha='left', va='bottom')

        self.ui['tuned_ax'] = self.fig.add_axes([.3, 0.35, .4, .2])
        self.ui['tuned_ax'].axis('off')
        self.ui['tuned_text'] = self.ui['tuned_ax'].text(.5,
                                                         0.48,
                                                         "Tuned",
                                                         ha="center",
                                                         va='center',
                                                         color='white')
        self.ui['tuned_circle'] = self.ui['tuned_ax'].add_patch(
            matplotlib.patches.Ellipse(
                (.5, .5),
                .4 / .7,
                1,
                fill=True,
                facecolor='#EE3333',
                edgecolor=None,
            ))

        self.ui['diff_ax'] = self.fig.add_axes([0.1, 0.55, 0.8, 0.4])
        self.ui['diff_ax'].axis('off')
        self.ui['diff_text'] = self.ui['diff_ax'].text(.5,
                                                       .1,
                                                       "0 Hz",
                                                       ha="center")
        self.ui['diff_rect'] = self.ui['diff_ax'].add_patch(
            matplotlib.patches.Rectangle(
                (0, .3),
                1,
                .7,
                fill=True,
                facecolor='#3333FF',
                edgecolor=None,
            ))

        self.interface_thread = threading.Thread(target=self.update)
Esempio n. 11
0
    def on_slider(val):
        if val != anim.frame_val:
            anim.frame_idx = int(val * anim.clip_len)

    def print_clip(val):
        data = anim.data[anim.clip_idx *
                         anim.clip_len:anim.clip_idx * anim.clip_len +
                         anim.clip_len]
        print(data)
        np.savetxt("out.txt", data)

    fig = plt.figure("Controls", figsize=(
        3,
        3,
    ))
    textbox = widgets.TextBox(plt.axes([0.4, 0.8, 0.4, 0.1]), "Clip:", '0')
    lentextbox = widgets.TextBox(plt.axes([0.4, 0.7, 0.4, 0.1]),
                                 "Clip Length:", '240')

    prevbutton = widgets.Button(plt.axes([0.25, 0.4, 0.1, 0.1]), "$\u29CF$")
    pausebutton = widgets.Button(plt.axes([0.25 + 0.2, 0.4, 0.1, 0.1]),
                                 "$\u25A0$")
    nextbutton = widgets.Button(plt.axes([0.25 + 0.4, 0.4, 0.1, 0.1]),
                                "$\u29D0$")
    widgets.TextBox(plt.axes([0.1, 0.2, 0.8, 0.1]), "",
                    "Total number of clips: %d " % (len(data) / 240))
    frameslider = widgets.Slider(plt.axes([0.2, 0.55, 0.6, 0.06]), "", 0, 1, 0)
    printbutton = widgets.Button(plt.axes([0.25, 0.08, 0.2, 0.1]), "Print")

    # Drawing
    anim = Animation(data, frameslider)
    def __init__(self, save_pdf=False, manual_elm_list=None):
        self.manual_elm_list = manual_elm_list
        self.time_markers = [None, None, None, None]
        self.marker_label = [
            'Pre-ELM start', 'ELM start', 'ELM end', 'Post-ELM end'
        ]
        self.fig, self.axes = plt.subplots(ncols=3, figsize=[11.5, 4])
        self.fig_num = self.fig.number
        self.fig.canvas.mpl_connect('close_event', self.on_close)
        for axes in self.axes:
            axes.set_xlabel('Time (ms)')
            axes.set_title('empty')
        self.axes[0].set_ylabel('Line avg dens (AU)')
        self.axes[1].set_ylabel('D alpha')
        self.axes[2].set_ylabel('BES')
        plt.tight_layout(rect=(0, 0.15, 1, 1))

        self.fig.canvas.mpl_connect('button_press_event', self.axis_click)

        self.save_pdf = save_pdf

        # self.quit_button = widgets.Button(plt.axes([0.01, 0.05, 0.07, 0.075]),
        #                                   'Quit',
        #                                   color='lightsalmon',
        #                                   hovercolor='red')
        # self.quit_button.on_clicked(self.on_close)

        self.skip_button = widgets.Button(plt.axes([0.01, 0.05, 0.07, 0.075]),
                                          'Skip ELM',
                                          color='lightsalmon',
                                          hovercolor='red')
        self.skip_button.on_clicked(self.skip)

        self.clear_button = widgets.Button(plt.axes([0.2, 0.05, 0.2, 0.075]),
                                           'Clear markers',
                                           color='lightgray',
                                           hovercolor='darkgray')
        self.clear_button.on_clicked(self.clear_markers)

        self.status_box = widgets.TextBox(plt.axes([0.5, 0.05, 0.2, 0.075]),
                                          'Status:',
                                          color='w',
                                          hovercolor='w')

        self.accept_button = widgets.Button(plt.axes([0.75, 0.05, 0.2, 0.075]),
                                            'Accept markers',
                                            color='whitesmoke',
                                            hovercolor='whitesmoke')
        self.accept_button.on_clicked(self.accept)

        self.multi = widgets.MultiCursor(self.fig.canvas,
                                         self.axes,
                                         color='r',
                                         lw=1)

        self.elm_data_file = h5py.File(elm_signals_file, 'r')
        self.nelms = len(self.elm_data_file)

        self.label_file = h5py.File(labeled_elms_file, 'a')
        self.labeled_elms = self.label_file.attrs.setdefault(
            'labeled_elms', np.array([], dtype=np.int))
        self.skipped_elms = self.label_file.attrs.setdefault(
            'skipped_elms', np.array([], dtype=np.int))

        self.validate_data_file()

        self.rng = np.random.default_rng()
        self.elm_index = None
        self.shot = None
        self.start_time = None
        self.stop_time = None
        self.time = None
        self.signals = None
        self.connection = MDSplus.Connection('atlas.gat.com')

        self.vlines = []
        self.data_lines = []
        self.clear_and_get_new_elm()
    barlist[0].set_color('r')
    barlist[1].set_color('g')
    barlist[2].set_color('purple')
    barlist[3].set_color('b')
    plt.title("Movies on Streaming Platforms")
    plt.ylabel("Streaming Platforms")
    plt.xlim(0, 1)
    plt.xticks(range(0, 2), ["", ""])
    plt.yticks(range(0, 4), ["Netflix", "Hulu", "Amazon Prime", "Disney+"])
    plt.draw()
    conn.close()


# Creates the textbox
axbox = plt.axes([0.195, 0.05, 0.15, 0.025])
movie_title = w.TextBox(axbox, "Search Movie Title", initial="")
movie_title.on_submit(titleUpdate)

# Create Fifth Subplot
plt.subplot(2, 3, 5)
xTitle = []
yTitle = []
currentImdbVal = 0
currentRtVal = 0
annotate = ""
plt.scatter(xTitle, yTitle)
plt.title("Movies by Rating")
plt.xlabel("IMDb Rating")
plt.ylabel("Rotten Tomatoes Rating")
plt.xlim(0, 10)
plt.ylim(0, 100)
Esempio n. 14
0
    def __init__(self,
                 data_filter_change=None,
                 data_fir_n_change=None,
                 der_filter_change=None,
                 der_fir_n_change=None,
                 file_change=None,
                 refresh_button_click=None,
                 sh_click=None,
                 icg_click=None,
                 file_list: List[str] = None):

        self.fig, self.axs = plt.subplots(3, 2, constrained_layout=True)
        self.lines = numpy.ndarray(shape=(3, 2), dtype=plt.Line2D)
        plt.subplots_adjust(bottom=0.25)

        widgets.TextBox(plt.axes([0, 0.17, 0.12, 0.02]),
                        "",
                        initial="Data filter")
        self.data_filter_widget = widgets.RadioButtons(
            plt.axes([0, 0.01, 0.12, 0.15]), ["savgol", "FIR", "None"], 2)
        self.data_filter_widget.on_clicked(data_filter_change)

        self.data_fir_n_widget = widgets.Slider(plt.axes(
            [0.4, 0.08, 0.25, 0.05]),
                                                "Data FIR N",
                                                5,
                                                100,
                                                20,
                                                valstep=1)
        self.data_fir_n_widget.on_changed(data_fir_n_change)

        widgets.TextBox(plt.axes([0.12, 0.17, 0.12, 0.02]),
                        "",
                        initial="Derivative filter")
        self.der_filter_widget = widgets.RadioButtons(
            plt.axes([0.12, 0.01, 0.12, 0.15]), ["savgol", "FIR", "None"], 2)
        self.der_filter_widget.on_clicked(der_filter_change)

        self.der_fir_n_widget = widgets.Slider(plt.axes(
            [0.4, 0.02, 0.25, 0.05]),
                                               "Deriv FIR N",
                                               5,
                                               100,
                                               50,
                                               valstep=1)
        self.der_fir_n_widget.on_changed(der_fir_n_change)

        self.refresh_button = widgets.Button(
            plt.axes([0.40, 0.15, 0.08, 0.05]), "Measure")
        self.refresh_button.on_clicked(refresh_button_click)

        self.sh_widget = widgets.TextBox(plt.axes([0.5, 0.15, 0.05, 0.05]), "",
                                         "200")
        self.sh_plus_btn = widgets.Button(plt.axes([0.55, 0.175, 0.02, 0.025]),
                                          "+")
        self.sh_minus_btn = widgets.Button(plt.axes([0.55, 0.15, 0.02, 0.025]),
                                           "-")

        def sh_pl_cl(_):
            new_val = int(self.sh_widget.text) + 50
            self.sh_widget.set_val(str(new_val))
            sh_click(new_val)

        def sh_mn_cl(_):
            new_val = int(self.sh_widget.text) - 50
            self.sh_widget.set_val(str(new_val))
            sh_click(new_val)

        self.sh_plus_btn.on_clicked(sh_pl_cl)
        self.sh_minus_btn.on_clicked(sh_mn_cl)
        self.sh_widget.on_text_change(
            lambda _: sh_click(int(self.sh_widget.text)))

        self.icg_widget = widgets.TextBox(plt.axes([0.6, 0.15, 0.05, 0.05]),
                                          "", "100000")
        self.icg_plus_btn = widgets.Button(
            plt.axes([0.65, 0.175, 0.02, 0.025]), "+")
        self.icg_minus_btn = widgets.Button(
            plt.axes([0.65, 0.15, 0.02, 0.025]), "-")
        self.icg_widget.on_text_change(
            lambda _: icg_click(int(self.icg_widget.text)))

        def icg_pl_cl(_):
            new_val = int(self.icg_widget.text) + 1000
            self.icg_widget.set_val(str(new_val))
            sh_click(new_val)

        def icg_mn_cl(_):
            new_val = int(self.icg_widget.text) - 1000
            self.icg_widget.set_val(str(new_val))
            sh_click(new_val)

        self.icg_plus_btn.on_clicked(icg_pl_cl)
        self.icg_minus_btn.on_clicked(icg_mn_cl)

        if file_list is not None:
            self.file_list_widget = widgets.RadioButtons(
                plt.axes([0.7, 0.01, 0.28, 0.15]), file_list)
            self.file_list_widget.on_clicked(file_change)
Esempio n. 15
0
    def __init__(self):
        # Disable default Toolbar and enable interactive mode
        mpl.rcParams['toolbar'] = 'None'
        plt.ion()

        # New figure
        self.fig = plt.figure()

        # Data Axes
        self.ax = self.fig.add_subplot(111)
        self.ax.grid(which='major')
        # default viewport
        self.ax.set_xlim([-10, 10])
        self.ax.set_ylim([-10, 10])
        # fixed aspect ratio
        self.ax.set_aspect('equal', adjustable='datalim')
        # labels
        self.ax.set_xlabel('X (mm)')
        self.ax.set_ylabel('Y (mm)')

        # Pad prototype
        self.padProto = None
        self.padProtoPoly = None
        self.padProtoEdge = None
        self.padProtoNet = None
        self.padWidth = 0
        self.padHeight = 0

        # Load Button
        self.bloadAx = self.fig.add_axes([0.01, 0.9, 0.25, 0.075])
        self.bload = wid.Button(self.bloadAx, 'Load Gerber Layer')
        self.bload.on_clicked(self._bloadClick)

        # Save Button
        self.bsaveAx = self.fig.add_axes([0.27, 0.9, 0.25, 0.075])
        self.bsave = wid.Button(self.bsaveAx, 'Save KiCad Module')
        self.bsave.on_clicked(self._bsaveClick)

        # Pad size input
        self.twidthAx = self.fig.add_axes([0.65, 0.9, 0.1, 0.075])
        self.twidth = wid.TextBox(self.twidthAx,
                                  'Pad W',
                                  initial=str(self.padWidth))
        self.twidth.on_submit(self._twidthSubmit)

        # Pad size input
        self.theightAx = self.fig.add_axes([0.85, 0.9, 0.1, 0.075])
        self.theight = wid.TextBox(self.theightAx,
                                   'Pad H',
                                   initial=str(self.padHeight))
        self.theight.on_submit(self._theightSubmit)

        # Layers
        self.gerberLayers = []
        self.activeLayer = None

        # Patches
        self.polyPatches = []

        # Highlight shape
        self.highlight = None

        # Mouse position
        self.mouseDownX = 0
        self.mouseDownY = 0
        # Mouse Mode
        self.mouseMode = self.MOUSE_NONE
        # Scroll factor
        self.mouseScrollFact = 1.1
        # Maximum click time
        self.mouseClickTime = 0.25
        # center pad pixel distance
        self.centerPadDist = 10
        self.selectDist = 20

        # Mouse events
        self.fig.canvas.mpl_connect('button_press_event', self._mouseDown)
        self.fig.canvas.mpl_connect('button_release_event', self._mouseUp)
        self.fig.canvas.mpl_connect('motion_notify_event', self._mouseMove)
        self.fig.canvas.mpl_connect('scroll_event', self._mouseScroll)
Esempio n. 16
0
        xs, ys = zip(*points)
        ppp.set_xdata(xs)
        ppp.set_ydata(ys)

        selected.set_xdata(-1)
        selected.set_ydata(-1)

        areaa = max(math.floor(PolyArea(xs, ys) / circleArea), 1)
        areaT.set_text(f'Max Capacity: {areaa}')

        lineP.set_xdata(xs)
        lineP.set_ydata(ys)
        areaP.set_xy(points)

    fig.canvas.draw()
    fig.canvas.flush_events()


fig.canvas.mpl_connect('button_press_event', onclick)
fig.canvas.mpl_connect('motion_notify_event', onmove)
fig.canvas.mpl_connect('key_press_event', press)

text_box = mpw.TextBox(scaleBox, 'Scale (m):', initial="10")
text_box.on_submit(update)

rad_box = mpw.TextBox(radiusBox, 'Radius (m):', initial="2")
rad_box.on_submit(radUpdate)

plt.show()
Esempio n. 17
0
    def __init__(self,
                 input_unlabeled_elm_event_file=None,
                 output_labeled_elm_event_filename=None,
                 save_pdf=True,
                 manual_elm_list=None):
        self.manual_elm_list = manual_elm_list
        self.time_markers = [None, None, None, None]
        self.marker_label = [
            'Pre-ELM start', 'ELM start', 'ELM end', 'Post-ELM end'
        ]
        self.fig, self.axes = plt.subplots(nrows=3, figsize=[15, 8])
        # self.fig_num = self.fig.number
        self.fig.canvas.mpl_connect('close_event', self.on_close)
        for axes in self.axes:
            axes.set_xlabel('Time (ms)')
        self.axes[0].set_ylabel('Line avg dens (AU)')
        self.axes[1].set_ylabel('D alpha')
        self.axes[2].set_ylabel('BES')
        plt.suptitle('empty')
        plt.tight_layout(rect=(0, 0.08, 1, 1))

        self.fig.canvas.mpl_connect('button_press_event', self.axis_click)

        self.save_pdf = save_pdf

        self.skip_button = widgets.Button(plt.axes([0.01, 0.02, 0.07, 0.04]),
                                          'Skip ELM',
                                          color='lightsalmon',
                                          hovercolor='red')
        self.skip_button.on_clicked(self.skip)

        self.clear_button = widgets.Button(plt.axes([0.2, 0.02, 0.2, 0.04]),
                                           'Clear markers',
                                           color='lightgray',
                                           hovercolor='darkgray')
        self.clear_button.on_clicked(self.clear_markers)

        self.status_box = widgets.TextBox(plt.axes([0.5, 0.02, 0.2, 0.04]),
                                          'Status:',
                                          color='w',
                                          hovercolor='w')

        self.accept_button = widgets.Button(plt.axes([0.75, 0.02, 0.2, 0.04]),
                                            'Accept markers',
                                            color='whitesmoke',
                                            hovercolor='whitesmoke')
        self.accept_button.on_clicked(self.accept)

        self.multi = widgets.MultiCursor(self.fig.canvas,
                                         self.axes,
                                         color='r',
                                         lw=1)

        assert Path(input_unlabeled_elm_event_file).exists()
        self.unlabeled_elm_events_h5 = h5py.File(
            input_unlabeled_elm_event_file, 'r')
        self.n_elms = len(self.unlabeled_elm_events_h5)
        print(
            f'Unlabeled ELM event data file: {input_unlabeled_elm_event_file}')
        print(f'  Number of ELM events: {self.n_elms}')
        # shots = np.unique([elm_event.attrs['shot'] for elm_event in self.unlabeled_elm_events_h5.values()])
        # print(f'  Number of unique shots: {shots.size}')

        output_file = Path().resolve() / output_labeled_elm_event_filename
        print(f'Output labeled ELM event file: {output_file}')
        print(f'  File exists: {output_file.exists()}')
        self.labeled_elm_events_h5 = h5py.File(output_file.as_posix(), 'a')

        self.figures_dir = Path().resolve() / 'figures'
        self.figures_dir.mkdir(exist_ok=True)

        self.labeled_elms = self.labeled_elm_events_h5.attrs.setdefault(
            'labeled_elms', np.array([], dtype=int))
        self.skipped_elms = self.labeled_elm_events_h5.attrs.setdefault(
            'skipped_elms', np.array([], dtype=int))

        self.validate_data_file()

        self.rng = np.random.default_rng()
        self.elm_index = None
        self.shot = None
        self.start_time = None
        self.stop_time = None
        self.time = None
        self.signals = None
        self.connection = MDSplus.Connection('atlas.gat.com')

        self.vlines = []
        self.data_lines = []
        self.clear_and_get_new_elm()
        plt.show()
Esempio n. 18
0
 def draw(self):
     self.axes = plt.axes(self.dims)
     self.type = mwidgets.TextBox(self.axes,
                                  self.str + ':',
                                  initial=str(self.val))
     self.type.on_submit(self.on)