Ejemplo n.º 1
0
    def _do_plot(self):
        stats = self._statistics.deserialize()
        metrics_to_plot = self._statistics.get_metrics_to_plot()
        subplots_count = len(stats)

        if not subplots_count:
            return

        fig, axarr = plt.subplots(subplots_count)
        fig.canvas.set_window_title(self._plot_title)

        time = range(len(stats[stats.keys()[0]]))
        axes_by_names = {}

        for i, key in enumerate(stats.keys()):
            axarr[i].plot(time,
                          stats[key],
                          label=metrics_to_plot[key].name,
                          lw=1,
                          color=COLORS[i])
            axarr[i].set_xlabel('time (sec)')
            axarr[i].set_ylabel(metrics_to_plot[key].unit.name)
            axarr[i].legend()
            axes_by_names[key] = i

        rax = plt.axes([0.01, 0.8, 0.1, 0.1])
        check_btns = CheckButtons(rax, stats.keys(), [True] * subplots_count)
        check_btns.on_clicked(self._get_show_hide_fn(fig, axarr,
                                                     axes_by_names))

        plt.subplots_adjust(left=0.2)
        plt.show()
Ejemplo n.º 2
0
    def build_plot(datas: List[PlotData], checkbox=True):
        fig, ax = plt.subplots()
        lines = []
        for data in datas:
            line, = ax.plot(data.xdata,
                            data.ydata,
                            'xb-',
                            lw=2,
                            color=data.color,
                            label=data.label)
            lines.append(line)
        plt.subplots_adjust(left=0.2)
        if checkbox:

            def change_state(label):
                index = labels.index(label)
                lines[index].set_visible(not lines[index].get_visible())
                plt.draw()

            rax = plt.axes([0.05, 0.4, 0.1, 0.15])
            labels = [str(line.get_label()) for line in lines]
            visibility = [line.get_visible() for line in lines]
            check = CheckButtons(rax, labels, visibility)
            check.on_clicked(change_state)
            plt.show()
Ejemplo n.º 3
0
Archivo: case.py Proyecto: ysshah/urap
def plotAllFlags():
    fig, ax = subplots(figsize=(16, 8))

    offsets = getOffsets()

    start = 22
    numFlags = [(flags[allChannels][:, -1] & (1 << start)) >> start]

    cmax = np.max(numFlags[0])
    cmin = np.min(numFlags[0])
    cmap = get_cmap('jet', cmax - cmin + 1)

    collection = RegularPolyCollection(numsides=4,
                                       rotation=np.pi / 4,
                                       sizes=(1000, ),
                                       linewidths=(1, ),
                                       offsets=offsets,
                                       transOffset=ax.transData,
                                       alpha=0.5,
                                       cmap=cmap)

    collection.set_clim(vmin=cmin - 0.5, vmax=cmax + 0.5)

    for i, w in enumerate(range(91) + range(91)):
        ax.annotate(str(w + 1), offsets[i], ha='center', va='center')

    subplots_adjust(left=0.2)

    ax.add_collection(collection)
    axis('equal')

    collection.set_array(numFlags[0])
    cb = colorbar(collection, ticks=np.arange(cmin, cmax + 1))

    rax = axes([0.05, 0.1, 0.1, 0.8])

    status = [True, False, False]
    check = CheckButtons(rax, ('22', '23', '24'), tuple(status))

    def func(label):
        bit = int(label)
        i = bit - start
        status[i] = not status[i]
        if status[i]:
            numFlags[0] += (flags[allChannels][:, -1] & (1 << bit)) >> bit
        else:
            numFlags[0] -= (flags[allChannels][:, -1] & (1 << bit)) >> bit

        cmax = np.max(numFlags[0])
        cmin = np.min(numFlags[0])
        cmap = get_cmap('jet', cmax - cmin + 1)

        ax.collections[0].set_array(numFlags[0])
        ax.collections[0].set_clim(vmin=cmin - 0.5, vmax=cmax + 0.5)
        ax.collections[0].set_cmap(cmap)
        cb.set_ticks(np.arange(cmin, cmax + 1))
        fig.canvas.draw()

    check.on_clicked(func)
    show()
Ejemplo n.º 4
0
    def _recreate_show_lines_check_button(self):

        axcolor = 'lightgoldenrodyellow'
        if hasattr(self, 'rax_showlines'):
            self.rax_showlines.cla()
        self.rax_showlines = plt.axes([self.x_start__ + self.slider_length__ + self.text_length__,
                                       self.y_start__,
                                       self.button_length__,
                                       self.button_height__], facecolor=axcolor)

        visible = self.prop_ifs.get_visible()
        show_ann = self.prop_ifs.get_annotation_visible()


        labels = ('showIFS',
                 #'marks',
                 #'edges',
                 'labels')
        actives = (visible,
                   # linestyle not in ['None', None],
                   show_ann)

        self.holder_actives = dict(zip(labels, actives))

        self.w_check_components = CheckButtons(self.rax_showlines,
                    labels,
                    actives)


        self.w_check_components.on_clicked(self.update_show_components)
        return self.w_check_components
Ejemplo n.º 5
0
def draw_plots(signals_descriptions):
    def on_click(label):
        plot = plots[label]
        plot.set_visible(not plot.get_visible())
        signals_figure.canvas.draw()

    signals_figure = plt.figure('Signals')
    plots = {}
    plt.subplots_adjust(bottom=0.25)
    plt.subplots_adjust(left=0.2)
    for signal_values, signal_label, visibility, spectrum in signals_descriptions:
        x_points, y_points = plot_values(signal_values)
        line, = plt.plot(x_points, y_points)
        plots[signal_label] = line
        plt.figure(signal_label)
        plt.stem(*plot_values(spectrum), linefmt='b', markerfmt=' ', basefmt=' ')
        plt.figure('Signals')
    checkboxes_axes = plt.axes([0.05, 0.4, 0.12, 0.15])
    checkboxes = CheckButtons(
        checkboxes_axes,
        [x.label for x in signals_descriptions],
        [x.visibility for x in signals_descriptions]
    )
    checkboxes.on_clicked(on_click)
    plt.figlegend(list(plots.values()), [x.label for x in signals_descriptions], loc='lower center')
    # need to hide after figlegend to use real colors for legend
    for _, label, visibility, _ in signals_descriptions:
        plots[label].set_visible(visibility)
    plt.show()
Ejemplo n.º 6
0
    def _do_plot(self):
        stats = self._statistics.deserialize()
        metrics_to_plot = self._statistics.get_metrics_to_plot()
        subplots_count = len(stats)

        if not subplots_count:
            return

        fig, axarr = plt.subplots(subplots_count)
        fig.canvas.set_window_title(self._plot_title)

        time = range(len(stats[stats.keys()[0]]))
        axes_by_names = {}

        for i, key in enumerate(stats.keys()):
            axarr[i].plot(time, stats[key], label=metrics_to_plot[key].name, lw=1, color=COLORS[i])
            axarr[i].set_xlabel('time (sec)')
            axarr[i].set_ylabel(metrics_to_plot[key].unit.name)
            axarr[i].legend()
            axes_by_names[key] = i

        rax = plt.axes([0.01, 0.8, 0.1, 0.1])
        check_btns = CheckButtons(rax, stats.keys(), [True] * subplots_count)
        check_btns.on_clicked(self._get_show_hide_fn(fig, axarr, axes_by_names))

        plt.subplots_adjust(left=0.2)
        plt.show()
Ejemplo n.º 7
0
    def add_checkboxes(self):
        """
        Checkboxes offer the ability to select multiple tags such as Motion, Ghosting Aliasing etc,
            instead of one from a list of mutual exclusive rating options (such as Good, Bad, Error etc).

        """

        ax_checkbox = plt.axes(cfg.position_checkbox,
                               facecolor=cfg.color_rating_axis)
        # initially de-activating all
        actives = [False] * len(self.issue_list)
        self.checkbox = CheckButtons(ax_checkbox,
                                     labels=self.issue_list,
                                     actives=actives)
        self.checkbox.on_clicked(self.save_issues)
        for txt_lbl in self.checkbox.labels:
            txt_lbl.set(**cfg.checkbox_font_properties)

        for rect in self.checkbox.rectangles:
            rect.set_width(cfg.checkbox_rect_width)
            rect.set_height(cfg.checkbox_rect_height)

        # lines is a list of n crosses, each cross (x) defined by a tuple of lines
        for x_line1, x_line2 in self.checkbox.lines:
            x_line1.set_color(cfg.checkbox_cross_color)
            x_line2.set_color(cfg.checkbox_cross_color)

        self._index_pass = self.issue_list.index(cfg.func_mri_pass_indicator)
 def initWindow(self):
     if not (self.args.placeOne and self.args.placeTwo):
         self.randomBB()
     for i in range(100):
         axes().set_aspect('equal', 'datalim')
         plt.subplot(2, 2, (1, 2))
         plt.subplot(2, 2, (1, 2)).set_aspect('equal')
         subplots_adjust(left=0.31)
         subplots_adjust(bottom=-0.7)
         plt.title('QSR Visualisation ' + self.args.distribution[0])
         axcolor = 'lightgoldenrodyellow'
         rax = plt.axes([0.03, 0.4, 0.22, 0.45], fc=axcolor)
         checkBox = CheckButtons(rax, self.qsr_type,
                                 (False, False, False, False, False))
         checkBox.on_clicked(self.EventClick)
         plt.subplot(2, 2, 3)
         plt.axis('off')
         plt.text(1,
                  1, (self.__compute_qsr(self.bb1[i], self.bb2[i])),
                  family='serif',
                  style='italic',
                  ha='center')
         if self.qsr:
             self.updateWindow()
         plt.show()
Ejemplo n.º 9
0
    def initVisibilityCheckBoxes(self):
        visibility = self.visibility
        if kElementsKey in visibility.keys():
            visibility.pop(kElementsKey)

        subAxes = plt.axes([0.81, 0.4, 0.1, 0.5], frameon=False, anchor='NW')
        self.checkBoxes = CheckButtons(subAxes, visibility.keys(),
                                       visibility.values())

        step = 0.15
        for i, (label, rectangle, lines) in enumerate(
                zip(self.checkBoxes.labels, self.checkBoxes.rectangles,
                    self.checkBoxes.lines)):
            h = 0.85 - step * i
            label.set_fontsize(11)
            rectangle.set_x(0.05)
            rectangle.set_y(h)
            rectangle.set(width=0.12, height=0.04)
            label.set_y(h + 0.02)
            label.set_x(0.2)

            lineA, lineB = lines
            lineA.set_xdata([0.05, 0.17])
            lineB.set_xdata([0.05, 0.17])
            lineA.set_ydata([h, h + 0.04])
            lineB.set_ydata([h + 0.04, h])

        self.checkBoxes.on_clicked(self.onCheckBoxCallback)
Ejemplo n.º 10
0
    def start_spectrum(self, *args, **kwargs):
        if self.fig_spectrum is None:
            self.fig_spectrum = plt.figure()
            self.ax_spectrum = self.fig_spectrum.add_axes([0.1, 0.1, 0.7, 0.8])

            # Widgets
            ax_hanning = self.fig_spectrum.add_axes([0.825, 0.75, 0.15, 0.15])
            self.checkbox_hanning = CheckButtons(ax_hanning, ["Hanning", "AC"],
                                                 [self.hanning, self.ac])
            self.checkbox_hanning.on_clicked(self.ask_hanning_change)

            ax_spectrum_unit = self.fig_spectrum.add_axes(
                [0.825, 0.51, 0.15, 0.25])
            self.radio_units = RadioButtons(
                ax_spectrum_unit,
                ["V^2/Hz", "V/sq(Hz)", "mV/sq(Hz)", "µV/sq(Hz)", "nV/sq(Hz)"],
            )
            self.radio_units.on_clicked(self.ask_spectrum_units_change)

            ax_restart = self.fig_spectrum.add_axes([0.825, 0.35, 0.15, 0.075])
            self.btn_restart = Button(ax_restart, label="Restart")
            self.btn_restart.on_clicked(self.clean_spectrum)

            ax_save_hold = self.fig_spectrum.add_axes(
                [0.825, 0.25, 0.15, 0.075])
            self.btn_save_hold = Button(ax_save_hold, label="Hold&Save")
            self.btn_save_hold.on_clicked(self.save_hold)

        self.clean_spectrum()
Ejemplo n.º 11
0
def make_log_button(ax, box=[0.015, 0.05, 0.12, 0.15], ylims=None):
    """ Make a log button

    ax : the axis
    ylims : None or dictionary with the ylim for 'linear' and 'log' scales
    """
    f = plt.gcf()
    ax_btn = f.add_axes(box, facecolor=slider_color)

    labels = ['log x', 'log y']
    widget = CheckButtons(ax_btn, labels,
                          [ax.get_xscale() == 'log',
                           ax.get_yscale() == 'log'])

    def set_log(label):
        if label == 'log x':
            method = 'set_xscale'
            index = 0
        if label == 'log y':
            method = 'set_yscale'
            index = 1
        state = 'log' if widget.get_status()[index] else 'linear'
        getattr(ax, method)(state)
        if ylims is not None:
            if label == 'log y':
                ax.set_ylim(ylims[state])

        f.canvas.draw_idle()

    widget.on_clicked(set_log)

    return widget
Ejemplo n.º 12
0
    def _recreate_show_operators_check_button(self):

        axcolor = 'lightgoldenrodyellow'
        if hasattr(self, 'rax_showlines_operator'):
            self.rax_showlines_operator.cla()
        self.rax_showlines_operator = plt.axes([self.x_start__ + self.slider_length__ \
                            + self.text_length__ + 2* self.button_length__,
                                       self.y_start__,
                                       self.button_length__,
                                       self.button_height__], facecolor=axcolor)

        visible = self.prop_ifs.holder.get_visible()
        linestyle = self.prop_ifs.holder.get_linestyle()

        labels = ('F', 'G', 'H', 'J')
        actives = (self.prop_ifs.hide_ifs, visible, linestyle
                   not in ['None', None], self.prop_ifs.show_ann)

        self.holder_actives_operator = dict(zip(labels, actives))

        self.w_check_components_operator = CheckButtons(
            self.rax_showlines_operator, labels, actives)

        self.w_check_components_operator.on_clicked(
            self.update_show_components_operator)
        return self.w_check_components_operator
Ejemplo n.º 13
0
def setup_ui():
    fig, ax = plt.subplots()
    plt.subplots_adjust(top=0.98, right=0.99, left=0.25, bottom=0.16)

    slider_axes = plt.axes([0.08, 0.04, 0.82, 0.03])
    slider = Slider(slider_axes, 'Steps', STEP_MIN, STEP_MAX, valinit=STEP)

    def slider_listener(value):
        global STEP
        STEP = int(value)
        plot(ax, value)
        fig.canvas.draw_idle()

    slider.on_changed(slider_listener)

    checkbox_axes = plt.axes([0.01, 0.3, 0.15, 0.5])
    checkbox = CheckButtons(checkbox_axes, METHODS, 
        [method in SELECTED_METHODS for method in METHODS])

    def checkbox_listener(label):
        method = [x for x in METHODS if x.name == label][0]
        if method in SELECTED_METHODS:
            SELECTED_METHODS.remove(method)
        else:
            SELECTED_METHODS.add(method)
        plot(ax, STEP)
        fig.canvas.draw_idle()

    checkbox.on_clicked(checkbox_listener)

    return ax, slider, checkbox
Ejemplo n.º 14
0
    def render(self):
        print(f'drawing with {self.plotter.n} circles')
        self.fig = Figure(figsize=(13, 13), dpi=100)
        self.ax = self.fig.subplots()
        self.root.wm_title(f"Render - {base_name(args.file_name, True)}")
        canvas = FigureCanvasTkAgg(self.fig, master=self.root)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
        if not self.hide_widgets:
            rax = self.fig.add_axes([0.05, 0.0, 0.1, 0.1])
            rax.axis('off')
            self.check = CheckButtons(rax, ('hide',), (self.plotter.hide,))
            self.check.on_clicked(lambda _: self.plotter.toggle_hide())

            nax = self.fig.add_axes([0.2, 0.07, 0.7, 0.02])
            self.nslider = Slider(nax, 'n', 2, self.plotter.frames,
                                  valinit=self.plotter.n, valstep=1)
            self.nslider.on_changed(self._update_n)
            fpsax = self.fig.add_axes([0.2, 0.03, 0.7, 0.02])
            self.fpsslider = Slider(fpsax, 'fps', 1, 50,
                                    valinit=10, valstep=1)
            self.fpsslider.on_changed(self._update_fps)
        self._init_animation()
        if args.save:
            self.save(args.out)
        else:
            tkinter.mainloop()
def plot_hmm_path(trajectory_objs, paths, legends=[], items=[]):
    global colors
    print_n_flush("Colors are:", colors)
    for i, (trajectory, p) in enumerate(zip(trajectory_objs, paths)):
        print_n_flush("Path:", p)
        tr_colors = [colors[int(state)] for state in p]
        t = trajectory.plot2d(color=tr_colors)
        # t = plot_quiver2d(trajectory, color=tr_colors, path=p)
        too_high = [tt for tt in trajectory if tt[1] > 400]
        #         print_n_flush( "Too high", too_high)
        legends.append("Trajectory%i" % i)
        #     items.append(p)
        items.append(t)
    # gca().legend()



    # Let's create checkboxes
    rax = plt.axes([0.05, 0.4, 0.1, 0.15])
    # rax = plt.gca()
    from matplotlib.widgets import CheckButtons

    check = CheckButtons(rax, legends, [True] * len(legends))
    # plt.sca(axes)

    def func(label):
        widget = items[legends.index(label)]
        widget.set_visible(not widget.get_visible())
        plt.draw()

    check.on_clicked(func)
Ejemplo n.º 16
0
def build_stock_gdp():
    """
    Creates graphic of stock prices of 8 companies and GDP of USA
    >>> build_stock_gdp()
    """
    axes = []
    for comp in found_years:
        x = np.arange(found_years[comp], 2019)
        if comp == 'LGF':
            x = np.arange(found_years[comp], 2017)
        lst = []
        for el in database:
            if database[el][1][comp] is not None:
                lst.append(database[el][1][comp])
        y = np.array(lst)
        axes.extend([x, y])

    lst = []
    x = np.arange(1962, 2019)
    for el in gdp_info:
        if int(el) >= 1962:
            lst.append(gdp_info[el] / 100)
    y = np.array(lst)
    axes.extend([x, y])

    fig, ax = plt.subplots()
    l1, = plt.plot(axes[0], axes[1], linestyle='solid')
    l2, = plt.plot(axes[2], axes[3], linestyle='solid')
    l3, = plt.plot(axes[4], axes[5], linestyle='solid')
    l4, = plt.plot(axes[6], axes[7], linestyle='solid')
    l5, = plt.plot(axes[8], axes[9], linestyle='solid')
    l6, = plt.plot(axes[10], axes[11], linestyle='solid')
    l7, = plt.plot(axes[12], axes[13], linestyle='solid')
    l8, = plt.plot(axes[14], axes[15], linestyle='solid')
    l9, = plt.plot(axes[16], axes[17], linestyle='solid')

    plt.subplots_adjust(left=0.3)
    lgnd = ax.legend(list(found_years.keys()),
                     loc='upper center',
                     ncol=4,
                     fontsize='xx-small',
                     shadow=True)

    lgnd.get_frame().set_facecolor('#ffb19a')

    rax = plt.axes([0.04, 0.5, 0.17, 0.37], facecolor='lightgoldenrodyellow')
    check = CheckButtons(rax, tuple(found_years.keys()),
                         (True, True, True, True, True, True, True, True))

    def func(label):
        for line, comp in zip([l1, l2, l3, l4, l5, l6, l7, l8],
                              list(found_years.keys())):
            if label == comp:
                line.set_visible(not line.get_visible())
        plt.draw()

    check.on_clicked(func)

    plt.show()
Ejemplo n.º 17
0
    def plot(self):

        print("plotting object of dimension " +
              str(self.decomposition.dimension))

        self.make_figure()
        self.make_axes()

        self.main()

        self.label_axes()

        # I would love to move this to its own method, but I
        # don't think that is possible with the limiations of
        # matplotlib

        # can this be done with async??

        # Create our check boxes

        # These four coordinates specify the position of the checkboxes
        rax = plt.axes([0.05, 0.4, 0.2, 0.15])
        check = CheckButtons(rax,
                             ('Vertices', 'Surface', 'Raw Surface', 'STL'),
                             (True, True, False, False))

        # Export STL button
        # exportstl = plt.axes([0.81, 0.01, 0.15, 0.075])
        # bfvtostl = Button(exportstl,'Export STL')

        # if(bfvtostl.on_clicked()):
        #      print("Export successfully")

        def func(label):
            if label == 'Vertices':
                # works but with hardcoded axes
                self.options.visibility.vertices = (
                    not self.options.visibility.vertices)
                self.ax.clear()
                self.replot()
            elif label == 'Surface':
                self.options.visibility.samples = (
                    not self.options.visibility.samples)
                self.ax.clear()
                self.replot()
            elif label == 'Raw Surface':
                self.options.visibility.raw = (not self.options.visibility.raw)
                self.ax.clear()
                self.replot()
            elif label == 'STL':
                self.fvtostl()

            plt.draw()

        check.on_clicked(func)

        self.apply_title()

        plt.show()
Ejemplo n.º 18
0
class PeakIdentifier:
    def __click_cb(self, label):
        self.all_names[label] = not self.all_names[label]

    def __init_fig__(self, data_name):
        self.fig = figure()
        self.ax = subplot(111)
        self.fig.subplots_adjust(left=0.3)
        title(_path.basename(data_name))
        self.button_ax = plt.axes([0.05, 0.1, 0.15, 0.8])
        self.check = CheckButtons(self.button_ax, sorted(self.all_names.keys()), [False] * len(self.all_names))
        self.check.on_clicked(self.__click_cb)

    def __init_data__(self, data, start_i, end_i, pos, pos_s):
        start_i = int(start_i)
        end_i = int(end_i) + 1
        self.start_i = start_i
        self.end_i = end_i
        self.__pos = pos
        self.__pos_s = pos_s
        self.d = end_i - start_i
        new_start = start_i - 10 * self.d
        if new_start < 0:
            new_start = 0
        new_end = end_i + 10 * self.d
        if new_end >= len(data[2]):
            new_end = len(data[2] - 1)
        self.new_start = new_start
        self.new_end = new_end
        self.xs = r_[self.new_start : self.new_end]
        y1 = data[2][new_start:new_end]
        y2 = data[3][new_start:new_end]
        self.y = y2 - y1

    def __init_plot__(self):
        self.ax.axvline(self.__pos, color="m", linewidth=2)
        self.ax.axvline(self.__pos - self.__pos_s, color="g")
        self.ax.axvline(self.__pos + self.__pos_s, color="g")

        self.ax.plot(self.xs, self.y, color="c")

        self.ax.set_ylim(min(self.y), max(self.y))
        self.ax.set_xlim(self.new_start, self.new_end)

    def __init_names__(self, names):
        self.all_names = {}
        for n in names:
            self.all_names[n] = False

    def __init__(self, names, data, start_i, end_i, data_name, pos, pos_s):
        self.__init_names__(names)
        self.__init_fig__(data_name)
        self.__init_data__(data, start_i, end_i, pos, pos_s)
        self.__init_plot__()

    def run(self):
        show()
        close()
        return [k for k, v in self.all_names.items() if v]
Ejemplo n.º 19
0
 def _set_control_AS(self):
     """
     Will connect the checkbutton control panel with the plotting axis.
     """
     self.check_AS = CheckButtons(
         self.AS_widg_ax, ('all rep', 'avg', 'fill'),
         (self.plot_all_AS, self.plot_avg_AS, self.fill_between_AS))
     self.check_AS.on_clicked(self._on_click_AS)
Ejemplo n.º 20
0
 def GUI(self, figsize=(13,12)):
     """ 
     Creates the figure, lines, texts and annotations that will be manipulated, and also the 
     interactive elements.
     """
     # check if the GUI has already been initialized. If it is, just show the figure from the previous state
     if self.GUI_initialized:
         self.fig.show()
     else:
         # initializing GUI plot
         self.static_plot(show=False, figsize=figsize)
         self.spec_lim = self.init_spec_lim.copy()
 
         # adjust the main plots to make room for the sliders
         plt.subplots_adjust(bottom=self.bottom_adjust_val, top=self.top_adjust_val) 
 
         # make sliders
         self.sliders_ax, self.sliders, current_right_column_pos = self.make_sliders()
 
         # make input textboxes for wavelength limits
         if current_right_column_pos[0] == self.right_x:
             right_edge = self.reset_button_arg[0] - 0.03
         else:
             right_edge = self.right_x+self.width
         textbox_width = (right_edge-current_right_column_pos[0]-self.textbox_gap)/2
 
         self.ax_spec_min = plt.axes([current_right_column_pos[0], 
                                      current_right_column_pos[1], textbox_width, self.height])
         self.spec_min_box = TextBox(self.ax_spec_min, r'$\lambda_{min}$', initial=self.init_spec_lim[0])
         self.spec_min_box.on_submit(self.submit_min)
 
         self.ax_spec_max = plt.axes([current_right_column_pos[0]+textbox_width+self.textbox_gap, 
                                      current_right_column_pos[1], textbox_width, self.height])
         self.spec_max_box = TextBox(self.ax_spec_max, r'$\lambda_{max}$', initial=self.init_spec_lim[1])
         self.spec_max_box.on_submit(self.submit_max)
 
         # register the update function with each slider
         for key in self.sliders.keys():
             self.sliders[key].on_changed(self.update)
 
         # Create a `matplotlib.widgets.Button` to reset all sliders to initial values.
         self.resetax = plt.axes(self.reset_button_arg)
         self.reset_button = Button(self.resetax, 'Reset', color=self.slider_colors['misc'], hovercolor='0.975')
 
         self.reset_button.on_clicked(self.reset)
 
         # Create a `matplotlib.widgets.CheckButton` to toggle show or not additional plots
         self.moreplotsax = plt.axes(self.moreplots_check_arg)
         self.moreplots_check = CheckButtons(self.moreplotsax, ['additional plots'])
 
         self.moreplots_check.on_clicked(self.toggle_additional_plots)
 
         # additional plots toggle bool
         self.reset_additional_plots()
 
         plt.show()
 
         self.GUI_initialized = True
Ejemplo n.º 21
0
    def showat(self, ax):
        v = [self.__getattribute__(name) for name in self.names]
        self.check = CheckButtons(ax, self.names, v)

        def func(label):
            self.__setattr__(label, not self.__getattribute__(label))
            print("clicked")

        self.check.on_clicked(func)
Ejemplo n.º 22
0
def show_cse(filename):
    plt.subplots_adjust(left=0.04, top=0.99, bottom=0.03, wspace=0.12,
                        hspace=0.23, right=0.86)
    record = reader.read_cse(filename)
    with EcgInterpreter.from_record(record) as interpreter:
        borders = interpreter.get_global_borders()
        points = interpreter.get_points()
        measures = interpreter.get_intervals()
    borders = [x.sample for x in borders if x.sample > 0]
    onset = int(borders[0] - 0.02 * record.rate)
    offset = int(borders[-1] + 0.02 * record.rate)
    empty_count = 0
    local_points = []
    measurements = []
    name = _record_name(filename)
    for i, item in enumerate(record.signals):
        if 2 <= i <= 5:
            empty_count += 1
            continue
        chunk = item[onset:offset]
        plot_index = (i - empty_count) * 2
        if plot_index > 7:
            plot_index -= 7
        plt.subplot(421 + plot_index)
        plt.ylabel("Lead " + _LEADS[i] + ". Voltage, mV.")
        plt.xlabel("Time, s.")
        plt.plot(chunk)
        measurements += _plot_borders(onset, borders)
        local_points += _plot_local_points(onset, points[i], chunk)
    legend_items = {
        _LABEL_POINTS: local_points[0]
    }
    if measurements:
        legend_items[_LABEL_MEASURES] = measurements[0]
    plt.figlegend(legend_items.values(), legend_items.keys(), "upper right")
    triggers = CheckButtons(plt.axes([0.87, 0.8, 0.12, 0.10]),
                            legend_items.keys(),
                            [True] * len(legend_items))

    def switch(label):
        lines = None
        if label == _LABEL_MEASURES:
            lines = measurements
        elif label == _LABEL_POINTS:
            lines = local_points
        for item in lines:
            item.set_visible(not item.get_visible())
        plt.draw()

    triggers.on_clicked(switch)
    _result_table(measures, name, ((10, 15), (10, 10), (10, 10), (25, 30)),
                  "ref_dict.pkl")
    plt.get_current_fig_manager().window.state("zoomed")
    plt.gcf().canvas.set_window_title("CSE Miltilead: " + name)
    plt.show()
Ejemplo n.º 23
0
    def __init__(self, field, fieldname, halospec=None):
        """Initializes a visualization instance, that is a windows with a field
        field is a 3D numpy array
        fieldname is a string with the name of the field
        halospec is a 2x2 array with the definition of the halo size

        After this call the window is shown
        """
        self.field = field
        self.fieldname = fieldname

        # Register halo information
        if halospec is None:
            halospec = [[3, 3], [3, 3]]
        self.istart = halospec[0][0]
        self.iend = field.shape[0] - halospec[0][1]
        self.jstart = halospec[1][0]
        self.jend = field.shape[1] - halospec[1][1]
        self.plotHalo = True
        self.plotLogLog = False

        self.curklevel = 0

        self.figure = plt.figure()

        # Slider
        slideraxes = plt.axes([0.15, 0.02, 0.5, 0.03],
                              axisbg='lightgoldenrodyellow')
        self.slider = Slider(slideraxes,
                             'K level',
                             0,
                             field.shape[2] - 1,
                             valinit=0)
        self.slider.valfmt = '%2d'
        self.slider.set_val(0)
        self.slider.on_changed(self.updateSlider)

        # CheckButton
        self.cbaxes = plt.axes([0.8, -.04, 0.12, 0.15])
        self.cbaxes.set_axis_off()
        self.cb = CheckButtons(self.cbaxes, ('Halo', 'Logscale'),
                               (self.plotHalo, self.plotLogLog))
        self.cb.on_clicked(self.updateButton)

        # Initial plot
        self.fieldaxes = self.figure.add_axes([0.1, 0.15, 0.9, 0.75])
        self.collection = plt.pcolor(self._getField(), axes=self.fieldaxes)
        self.colorbar = plt.colorbar()
        self.fieldaxes.set_xlim(right=self._getField().shape[1])
        self.fieldaxes.set_ylim(top=self._getField().shape[0])
        plt.xlabel('i')
        plt.ylabel('j')
        self.title = plt.title('%s - Level 0' % (fieldname, ))

        plt.show(block=False)
Ejemplo n.º 24
0
    def __init__(self, field, fieldname, halospec=None):
        """Visualization a field in a matplotlib window

        Each k level is represented as a simple slice in the window.

        :param field: Field to display
        :type field: numpy.array
        :param fieldname: Name of the field to display
        :type fieldname: str
        :param halospec: 2x2 array with the definition of the halo size (e.g ``[[3, 3], [3, 3]]``)
        :type halospec: array[array]
        """
        self.__field = field
        self.__fieldname = fieldname

        # Register halo information
        if halospec is None:
            halospec = [[3, 3], [3, 3]]

        self.__istart = halospec[0][0]
        self.__iend = field.shape[0] - halospec[0][1]
        self.__jstart = halospec[1][0]
        self.__jend = field.shape[1] - halospec[1][1]
        self.__plotHalo = True
        self.__plotLogLog = False

        self.__curklevel = 0

        self.__figure = plt.figure()

        # Slider
        slideraxes = plt.axes([0.15, 0.02, 0.5, 0.03], axisbg='lightgoldenrodyellow')
        self.__slider = Slider(slideraxes, 'K level', 0, field.shape[2] - 1, valinit=0)
        self.__slider.valfmt = '%2d'
        self.__slider.set_val(0)
        self.__slider.on_changed(self.__update_slider)

        # CheckButton
        self.__cbaxes = plt.axes([0.8, -.04, 0.12, 0.15])
        self.__cbaxes.set_axis_off()
        self.__cb = CheckButtons(self.__cbaxes, ('Halo', 'Logscale'),
                                 (self.__plotHalo, self.__plotLogLog))
        self.__cb.on_clicked(self.__update_button)

        # Initial plot
        self.__fieldaxes = self.__figure.add_axes([0.1, 0.15, 0.9, 0.75])
        self.__collection = plt.pcolor(self.__get_field(), axes=self.__fieldaxes)
        self.__colorbar = plt.colorbar()
        self.__fieldaxes.set_xlim(right=self.__get_field().shape[1])
        self.__fieldaxes.set_ylim(top=self.__get_field().shape[0])

        plt.xlabel('i')
        plt.ylabel('j')
        self.__title = plt.title('%s - Level 0' % (fieldname,))
        plt.show(block=True)
Ejemplo n.º 25
0
    def _init_checks(self):
        self.check_labels = []
        self.check_display = []
        for i in range(self.n):
            fn = self.config['data'][i]['filename']
            label = '%s' % (os.path.basename(fn))
            self.check_labels.append(label)
            self.check_display.append(self.mappables[i])

        self.checks = CheckButtons(self.check_ax, self.check_labels, \
                                   self.check_display)
Ejemplo n.º 26
0
def toggle_lines(ax=None, autoscl=True, numbering=False, txtwidth=15):
    """
  Make checkbuttons to toggle visibility of each line in current plot.
  autoscl  : Rescale axis limits as required by currently visible lines.
  numbering: Add numbering to labels.
  txtwidth : Wrap labels to this length.
  """

    # Get lines and their properties
    if ax is None: ax = plt.gca()
    lines = {'handle': list(ax.get_lines())}
    for p in ['label', 'color', 'visible']:
        lines[p] = [plt.getp(x, p) for x in lines['handle']]
    lines = pd.DataFrame(lines)
    lines = lines[~lines.label.str.startswith('_')]

    if numbering:
        lines['label'] = [
            str(i) + ': ' + lb for i, lb in enumerate(lines['label'])
        ]

    if txtwidth:
        lines['label'] = [
            textwrap.fill(n, width=txtwidth) for n in lines['label']
        ]

    # Setup buttons
    # When there's many, the box-sizing is awful, but difficult to fix.
    plt.subplots_adjust(left=0.32, right=0.97)
    N = len(lines)
    H = min(1, 0.07 * N)
    rax = plt.axes([0.05, 0.5 - H / 2, 0.22, H])
    check = CheckButtons(rax, lines.label, lines.visible)

    # Adjust button style
    for i in range(N):
        check.rectangles[i].set(lw=0, facecolor=lines.color[i])
        check.labels[i].set(color=lines.color[i])

    # Callback
    def toggle_visible(label):
        ind = lines.label == label
        handle = lines[ind].handle.item()
        vs = not lines[ind].visible.item()
        handle.set_visible(vs)
        lines.loc[ind, 'visible'] = vs
        if autoscl:
            autoscale_based_on(ax, lines[lines.visible].handle)
        plt.draw()

    check.on_clicked(toggle_visible)

    # Must return (and be received) so as not to expire.
    return check
Ejemplo n.º 27
0
    def add_button ( self , ax ) :
        #extend window to have some place to write the coordinate
        expand_figure ('LEFT' , 2 , ax , self.fig)

        ax_but = plt.axes([0.01, 0.05, 0.4, 0.8 ])
        #do not show the graph of the button axis
        ax_but.axis('off')

        #add buttons
        self.check = CheckButtons(ax_but, self.name_curves ,  [True for _ in self.curves] )
        #link the event handler function to the button
        self.check.on_clicked(self.on_click)
Ejemplo n.º 28
0
    def genCombineResalePrices(yearEnter, monthNum, p_leaseEnter, flatType):
        import numpy as np
        from datetime import datetime
        from matplotlib.widgets import CheckButtons
        global townSelect, towndata
        ## To get data within the Period from parameter pass of p_yearEnter p_monthEnter to current date
        dateStart = yearEnter + monthNum[-2:]
        firstStartDate = yearEnter + "-" + monthNum[-2:]
        dateEnd = datetime.now().strftime('%Y%m')
        dataPeriod = data[data['month'] == firstStartDate]
        for i in range(int(dateStart) + 1, int(dateEnd) + 1):
            strDate = str(i)
            last2digit = int(strDate[-2:])
            if last2digit < 13:
                iStrDate = str(i)
                iDate = iStrDate[0:4] + "-" + iStrDate[-2:]
                idata = data[data['month'] == iDate]
                dataPeriod = np.append(dataPeriod, idata)
        ## To get data within the Flat lease period (Flat Lease > parameter p_leaseEnter)
        leaseStart = int(p_leaseEnter) + 1
        leaseData = dataPeriod[dataPeriod['remaining_lease'] > leaseStart]
        flatTypeData = leaseData[leaseData['flat_type'] == flatType]
        towndata = flatTypeData

        ## To get data within the Selected Checkbox Town Line
        line_labels = [str(line.get_label()) for line in checkBoxLines]
        line_visibility = [line.get_visible() for line in checkBoxLines]
        check = CheckButtons(rax, line_labels, line_visibility)
        checkButtonThemes(check)

        status = check.get_status()

        #index = line_labels.index(label)
        #checkBoxLines[index].set_visible(not checkBoxLines[index].get_visible())
        statusIndex = np.arange(0, len(status))
        resale_prices = flatTypeData['resale_price']
        town_resale_prices = np.zeros(len(townList), object)
        for t in townIndex:
            town_resale_prices[t] = resale_prices[towndata['town'] ==
                                                  townList[t]]
        townSelect = np.zeros(len(townList), object)
        townName = []
        resale_prices_combined = []
        labelIndex = -1
        for s in statusIndex:
            if status[s]:
                labelIndex += 1
                townSelect[labelIndex] = towndata[towndata['town'] ==
                                                  townList[s]]
                #townSelect = np.append(townSelect,sdata)
                townName.append(line_labels[s])
                resale_prices_combined.append(town_resale_prices[s])
        return resale_prices_combined, townName
Ejemplo n.º 29
0
class AppMatplotlib(App):
    """
    A class that uses matplotlib to display the drawing of a graph.
    """
    def __init__(self, graph_list: List[nx.PlanarEmbedding]):
        App.__init__(self, graph_list)

        self.fig, self.ax = plt.subplots()
        self.fig.canvas.set_window_title('Planar graph drawing on a grid')
        plt.subplots_adjust(left=0, right=1, top=1, bottom=0)

        self.display_can_order = True
        self.prev_button = None
        self.next_button = None
        self.dummy_edge_button = None
        self.can_order_button = None

        self.change_graph()

        plt.show()
        plt.close()

    def add_widgets(self):
        axprev = plt.axes([0.01, 0.9, 0.1, 0.075])
        axnext = plt.axes([0.12, 0.9, 0.1, 0.075])
        self.prev_button = Button(axprev, "Previous")
        self.prev_button.on_clicked(lambda event: self.change_graph(-1))
        self.next_button = Button(axnext, "Next")
        self.next_button.on_clicked(lambda event: self.change_graph())
        axcanbox = plt.axes([0.01, 0.81, 0.1, 0.1], frameon=False)
        self.can_order_button = CheckButtons(axcanbox, ["Canonical order"], [self.display_can_order])
        self.can_order_button.on_clicked(self.toggle_can_order)
        axckeckbox = plt.axes([0.01, 0.76, 0.1, 0.1], frameon=False)
        self.dummy_edge_button = CheckButtons(axckeckbox, ["Dummy edges"], [self.display_dummy_edges])
        self.dummy_edge_button.on_clicked(self.toggle_dummy_edges)
        axes_text_box = plt.axes([0.01, 0.69, 0.06, 0.075], frameon=False)
        text_box = TextBox(axes_text_box, "", "Nodes : " + str(len(self.current_graph)))

    def toggle_dummy_edges(self, event=None):
        self.display_dummy_edges = not self.display_dummy_edges
        self.update_display()

    def toggle_can_order(self, event=None):
        self.display_can_order = not self.display_can_order
        self.update_display()

    def update_display(self):
        self.fig.clear()
        self.draw_graph()
        plt.axis('equal')
        # plt.gca().set_aspect('equal', adjustable='box')
        # plt.axis('off')
        self.add_widgets()
Ejemplo n.º 30
0
class fogContainerTrfcStat(MplCanvas):
    """ plot container traffic statistics for FOG demo"""
    colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']

    def __init__(self, trfc_stats, n_points=15, parent=None):
        '''
        trfc_stats: a list of multiprocessing.Value, in which each
        element coresponds to a container's current traffic bandwidth.
        '''
        super().__init__(parent=parent)
        self.trfc_stats = trfc_stats
        self.n_points = n_points
        self.n_lines = len(trfc_stats)
        self.fig.subplots_adjust(left=0.35)
        self.ax_checkbuttom = self.fig.add_axes([0.04, 0.2, 0.17, 0.5])
        self.compute_initial_figure()

    def compute_initial_figure(self):
        self.t = np.arange(0, self.n_points)
        self.alldata = []
        self.lines = []
        for i in range(self.n_lines):
            data = deque([0] * self.n_points, maxlen=self.n_points)
            ls = self.axes.plot(self.t,
                                data,
                                lw=1,
                                color=fogContainerTrfcStat.colors[i],
                                label=f'Container {i}')
            self.alldata.append(data)
            self.lines.append(ls[0])
        self.labels = [str(line.get_label()) for line in self.lines]
        self.visibility = [line.get_visible() for line in self.lines]
        self.checkbuttom = CheckButtons(self.ax_checkbuttom, self.labels,
                                        self.visibility)
        self.checkbuttom.on_clicked(self.checkbutton_func)
        self.axes.set_ylim(0, 810000)
        self.axes.legend(loc='upper right')  #'lower right'
        self.axes.get_xaxis().set_ticks([])
        self.draw()

    def checkbutton_func(self, label):
        idx = self.labels.index(label)
        self.lines[idx].set_visible(not self.lines[idx].get_visible())
        self.draw()

    def update_figure(self):
        #self.axes.cla()
        for i in range(self.n_lines):
            self.alldata[i].append(self.trfc_stats[i].value)
            self.lines[i].set_ydata(self.alldata[i])
            # print(self.alldata[i])
        self.draw()
Ejemplo n.º 31
0
    def _heatmap(self, heat):
        if heat is None: return

        if not hasattr(self, 'chxbox'):
            self.activated = True
            ax = self.fig.add_axes([.77, .82, 0.3, .2], frame_on=False)
            self.chxbox = CheckButtons(ax, ['heatmap'], [self.activated])

            def callback(_):
                self.activated = not self.activated

            self.chxbox.on_clicked(callback)

        if not self.activated:
            if hasattr(self, 'heat'):
                self.heat.remove()
                delattr(self, 'heat')
            return

        min_, max_ = np.min(heat), np.max(heat)
        heat = heat.reshape(self.x_plots, self.y_plots).T
        x_w, y_w = (self.ax_img.get_array().shape)
        heat = cv2.resize(heat, (x_w, y_w),
                          interpolation=cv2.INTER_CUBIC)  # cv2.INTER_NEAREST
        heat = interp1d([np.min(heat), np.max(heat)], [0., 1.])(heat)

        if not hasattr(self, 'heat'):
            self.heat = self.axes.imshow(
                heat,
                interpolation='bicubic',
                cmap='jet',
                alpha=.5,
            )

        if not self.cbar:
            self.cbar = self.fig.colorbar(
                self.heat,
                ax=self.axes,
                drawedges=False,
                format='%.3f',
                ticks=[0, 0.5, 1],
                label='pis',
            )

        self.heat.set_data(heat)  # update the heat map
        self.cbar.draw_all()
        self.cbar.set_alpha(1)  # avoid lines caused by transparency
        cbar_ticks = [
            float(f'{x:.4f}')
            for x in np.linspace(min_, max_, num=3, endpoint=True)
        ]
        self.cbar.ax.set_yticklabels(cbar_ticks)
Ejemplo n.º 32
0
def main():
    fmax = 0.1
    t = linspace(-fmax, fmax, num=20000)
    # Signals
    ft = f(t)  # Input
    gt = g(t)  # Tren de pulsos cuadrada
    fg = f(t) * g(t)  # Señal muestreada
    sf = signal_filter(fg)  # Señal recuperada con filtro
    # Se dibujan en la ventana
    fig, ax = plt.subplots(figsize=(13, 6))
    l0, = ax.plot(t,
                  ft,
                  visible=True,
                  lw=1,
                  color='green',
                  label='f(t)',
                  dashes=[6, 2])
    l1, = ax.plot(t,
                  gt,
                  visible=False,
                  lw=1,
                  color='red',
                  label='g(t)',
                  dashes=[6, 2])
    l2, = ax.plot(t, fg, visible=False, lw=1, color='blue', label='f(t)*g(t)')
    l3, = ax.plot(t,
                  sf,
                  visible=True,
                  lw=1,
                  color='blue',
                  label='Senial filtrada')
    lines = [l0, l1, l2, l3]
    # configuracion de la figura
    fig.canvas.set_window_title("Teorema de muestreo - %s" % (__author__))
    plt.subplots_adjust(left=0.2)
    plt.ylim(-4, 5)
    plt.xlim(-fmax, fmax)
    plt.axhline(0, color="black")
    plt.axvline(0, color="black")
    # Se crean los chebkbuttons para las señales lines[]
    rax = plt.axes([0.05, 0.4, 0.1, 0.15])
    labels = [str(line.get_label()) for line in lines]
    visibility = [line.get_visible() for line in lines]
    check = CheckButtons(rax, labels, visibility)

    def func(label):
        index = labels.index(label)
        lines[index].set_visible(not lines[index].get_visible())
        plt.draw()

    check.on_clicked(func)
    plt.show()
Ejemplo n.º 33
0
def plot_movie(dales, num_frames):
    n = len(fields)  # number of fields to draw
    fig, axes = plot.subplots(1, n, sharey=True)
    handles = []
    time_label = fig.text(0.1, 0.1, 'time')
    zf = dales.get_zf().value_in(units.m)
    ind = 0
    colors = "bgrcmyk"
    for ax in axes:
        f = fields[ind]
        var_name, var_unit = f[0], f[1]
        ax = axes[ind]
        ax.set_xlabel(var_name)
        ax.set_ylabel("z")
        var_prof = getattr(dales.profiles, var_name).value_in(var_unit)
        line = ax.plot(var_prof[:], zf[:], '-', color=colors[ind], linewidth=2)
        handles.append((ax, line))
        ind += 1

    # plot.tight_layout()
    # draw a check box for forcing
    rax = plot.axes([0.25, 0.05, 0.15, 0.08])
    check = CheckButtons(rax, ('Forcing', ), (False, ))
    check.on_clicked(checkbtn_clicked)

    def update_plot(lines, prof):
        lines[0].set_xdata(prof[:])

    def update(i):
        if forcingFlag:
            tendency = numpy.zeros(dales.get_ktot())
            print 'Applying forcing'
            for i in range(-15, 15):
                tendency[30 + i] = numpy.exp(-(i / 5.0)**2)
            dales.set_tendency_V(tendency * .2 | units.m / units.s**2)
            dales.set_tendency_QT(tendency * .000002 | units.mfu / units.s)

        t = dales.get_model_time()
        dales.evolve_model(t + dt)

        t = dales.get_model_time()
        print "updating with arg", i, 'time = ', t
        time_label.set_text('time %.2f' % t.value_in(units.s))

        for f, h in zip(fields, handles):
            name, unit = f[0], f[1]
            prof = getattr(dales.profiles, name).value_in(unit)
            update_plot(h[1], prof)

    a = movie.FuncAnimation(fig, update, frames=num_frames, repeat=False)
    plot.show()
Ejemplo n.º 34
0
    def plot(self, params, confidence_levels=[0.90, 0.95, 0.99], downsample=100):
        from plotutils import plotutils as pu
        from matplotlib import pyplot as plt
        from matplotlib.widgets import CheckButtons

        from itertools import cycle
        lines = ['solid', 'dashed', 'dashdot', 'dotted']
        linecycler = cycle(lines)

        N = len(self._tracking_array)
        tracking_array = self._tracking_array

        param1 = tracking_array[params[0]]
        param2 = tracking_array[params[1]]
        pu.plot_greedy_kde_interval_2d(np.vstack([param1, param2]).T, [0.90,0.95,0.99])
        ax = plt.gca()

        arrows = {}
        for proposal in self._proposals:
            ls = next(linecycler)
            sel = tracking_array['proposal'] == proposal
            accepted = tracking_array['accepted'][sel]
            xs = param1[sel]
            ys = param2[sel]
            x_ps = tracking_array[params[0]+'_p'][sel]
            y_ps = tracking_array[params[1]+'_p'][sel]
            dxs = x_ps - xs
            dys = y_ps - ys

            arrows[proposal] = []
            for x, y, dx, dy, a in zip(xs,ys,dxs,dys,accepted):
                if dx != 0 or dy != 0:
                    c = 'green' if a else 'red'
                    arrow = ax.arrow(x, y, dx, dy, fc=c, ec=c, alpha=0.5, visible=False, linestyle=ls)
                    arrows[proposal].append(arrow)

        plt.subplots_adjust(left=0.5)
        rax = plt.axes([0.05, 0.4, 0.4, 0.35])
        check = CheckButtons(rax, self._proposals, [False for i in self._proposals])

        def func(proposal):
            N = len(arrows[proposal])
            step = int(np.floor(N/float(downsample)))
            step = step if step is not 0 else 1
            for l in arrows[proposal][::step]:
                l.set_visible(not l.get_visible())
            plt.draw()

        check.on_clicked(func)
        plt.show()
    def __init__(self):
        self.Consistency = 'Not self consistent'
        self.Bias = 0.1
        self.Gate = None
        self.OrbitalSel = None
        self.fig, (self.axBias, self.axTrans, self.axIVCurve) = plt.subplots(3,1)
        self.fig.patch.set_facecolor('ghostwhite')
        plt.subplots_adjust(left=0.3)
        pos = self.axBias.get_position()
        self.axBias.set_position ([pos.x0, 0.55, pos.width, 0.40])
        self.axTrans.set_position([pos.x0, 0.05, pos.width, 0.40])
        self.axIVCurve.set_position([0.05, 0.05, 0.2, 0.3])
        self.axCM = self.fig.add_axes([0.94, 0.55, 0.01, 0.35])

        self.fig.canvas.mpl_connect('button_press_event', self.OnClick)
        self.fig.canvas.mpl_connect('pick_event', self.OnPick)
        self.fig.canvas.mpl_connect('key_press_event', self.OnPress)

        self.InitMolecule()
        self.InitBias()
        self.InitTrans()
        self.InitOrbitals()
        self.InitIVCurve()
        
        self.axSC = plt.axes([0.05, 0.85, 0.15, 0.10], axisbg='white')
        self.cbSC = RadioButtons(self.axSC, ('Not self consistent', 'Hubbard', 'PPP'))
        self.cbSC.on_clicked(self.UpdateConsistency)

        self.axOptions1 = plt.axes([0.05, 0.7, 0.15, 0.10], axisbg='white')
        self.cbOptions1 = CheckButtons(self.axOptions1, ('Overlap', 'Show Local Density','Show Local Currents'), (False, False, True))
        self.cbOptions1.on_clicked(self.Options1)
        
        self.axOptions2 = plt.axes([0.05, 0.5, 0.15, 0.15], axisbg='white')
        self.cbOptions2 = CheckButtons(self.axOptions2, ('Show Transmission', 'Show Current', 'Show DOS', 'Show Orbitals', 'Show Phase'), (True, True, False, False, False))
        self.cbOptions2.on_clicked(self.Options2)
        c = ['seagreen', 'b', 'darkorange', 'lightsteelblue', 'm']    
        [rec.set_facecolor(c[i]) for i, rec in enumerate(self.cbOptions2.rectangles)]
        
        self.axGleft  = plt.axes([0.05, 0.43, 0.15, 0.02], axisbg='white')
        self.axGright = plt.axes([0.05, 0.40, 0.15, 0.02], axisbg='white')
        self.sGleft   = Slider(self.axGleft,  'Gl', 0.0, 1.0, valinit = gLeft)
        self.sGright  = Slider(self.axGright, 'Gr', 0.0, 1.0, valinit = gRight)
        self.sGleft.on_changed(self.UpdateG)
        self.sGright.on_changed(self.UpdateG)
        
        self.axSave = plt.axes([0.92, 0.95, 0.07, 0.04])
        self.bSave = Button(self.axSave, 'Save')
        self.bSave.on_clicked(self.Save)
Ejemplo n.º 36
0
    def __init__(self, fig, rect, labels, act=None, func=None, fargs=None):
        """init function

        Parameters:
            fig: a matplotlib.figure.Figure instance
            rect: [left, bottom, width, height]
                each of which in 0-to-1-fraction i.e. 0<=x<=1
            labels: array of strings
                labels to be checked
            act: a len(labels) array of booleans, optional, default: None
                indicating whether the label is active at first
                if None, all labels are inactive
            func: function, optional, default: None
                if not None, function called when checkbox status changes
            fargs: array, optional, default: None
                (optional) arguments for func
        """
        self.fig = fig
        self._rect = rect
        self._func = func
        self._fargs = fargs
        self._labels = labels
        self.axes = self.fig.add_axes(rect)
        self.axes.set_axis_bgcolor('1.00')
        inac = act if act is not None else (False,) * len(labels)
        self.cb = CheckButtons(self.axes, self._labels, inac)
        self.cb.on_clicked(self._onchange)
Ejemplo n.º 37
0
def init_ax4():
    
    global ax4, checkService, checkPause, checkEndBen, checkDist, check

    ax4 = fig.add_axes([.72, .15, .08, .12])
    ax4.set_xticklabels([])
    ax4.set_yticklabels([])
    ax4.set_xticks([])
    ax4.set_yticks([])
    
    # Define checkboxes
    check = CheckButtons(ax4, ('Service',   'Stepped', 'Pause',    'EndBen',    'Dist'),
                              (checkService, checkStepped, checkPause, checkEndBen, checkDist))
                               
    # Attach checkboxes to checkbox function
    check.on_clicked(func)
Ejemplo n.º 38
0
 def __init_fig__(self, data_name):
     self.fig = figure()
     self.ax = subplot(111)
     self.fig.subplots_adjust(left=0.3)
     title(_path.basename(data_name))
     self.button_ax = plt.axes([0.05, 0.1, 0.15, 0.8])
     self.check = CheckButtons(self.button_ax, sorted(self.all_names.keys()), [False] * len(self.all_names))
     self.check.on_clicked(self.__click_cb)
Ejemplo n.º 39
0
def init_ax4():

    global ax4, checkService, checkPause, checkEndBen, checkDist, check

    ax4 = fig.add_axes([0.72, 0.15, 0.08, 0.12])
    ax4.set_xticklabels([])
    ax4.set_yticklabels([])
    ax4.set_xticks([])
    ax4.set_yticks([])

    # Define checkboxes
    check = CheckButtons(
        ax4,
        ("Service", "Stepped", "Pause", "EndBen", "Dist"),
        (checkService, checkStepped, checkPause, checkEndBen, checkDist),
    )

    # Attach checkboxes to checkbox function
    check.on_clicked(func)
 def initWindow(self):
     if not (self.args.placeOne and self.args.placeTwo):
         self.randomBB()
     axes().set_aspect('equal', 'datalim')
     plt.subplot(2, 2, (1, 2))
     plt.subplot(2, 2, (1, 2)).set_aspect('equal')
     subplots_adjust(left=0.31)
     subplots_adjust(bottom=-0.7)
     plt.title('QSR Visualisation')
     axcolor = 'lightgoldenrodyellow'
     rax = plt.axes([0.03, 0.4, 0.22, 0.45], axisbg=axcolor)
     checkBox = CheckButtons(rax, self.qsr_type,(False,False,False,False,False))
     checkBox.on_clicked(self.EventClick)
     plt.subplot(2, 2, 3)
     plt.axis('off')
     plt.text(1, 1, (self.__compute_qsr(self.bb1, self.bb2)), family='serif', style='italic', ha='center')
     if self.qsr:
         self.updateWindow()
     plt.show()
Ejemplo n.º 41
0
    def __init__(self, data, auto_mask, savedir):
        '''The constructor initializes all the variables and creates the plotting window.

        **Input arguments:**

            - *data*: NxM array
                The background to be masked - an averaged (static) scattering image.

            - *auto_mask*: NxM array
                The default mask, masking all the bad pixels.

            - *savedir*: string
                Directory where the mask file will be saved.
        '''
        self.mask_saved = False
        self.savedir = savedir
        self.fig = figure()
        title('Select ROI to mask. Press m to mask or w to save and exit ')
        self.ax = self.fig.add_subplot(111)
        # Check button for logscale switching
        self.cbax = self.fig.add_axes([0.01, 0.8, 0.1, 0.15])
        self.cb_log = CheckButtons(self.cbax, ('log',), (False,))
        self.cb_log.on_clicked(self.toggle_logscale)
        self.log_flag = False
        self.canvas = self.ax.figure.canvas
        #self.data = n.log10(data)
        self.raw_data = data.copy()
        self.data = data
        self.lx, self.ly = shape(self.data)
        self.auto_mask = auto_mask
        self.mask = auto_mask
        self.masked_data = n.ma.masked_array(self.data,self.mask)
        self.points = []
        self.key = []
        self.x = 0
        self.y = 0
        self.xy = []
        self.xx = []
        self.yy = []
        self.ind = 0
        self.img = self.ax.imshow(self.masked_data,origin='lower',interpolation='nearest',animated=True)
        self.colorbar = colorbar(self.img,ax=self.ax)
        self.lc,=self.ax.plot((0,0),(0,0),'-+w',color='black',linewidth=1.5,markersize=8,markeredgewidth=1.5)
        self.lm,=self.ax.plot((0,0),(0,0),'-+w',color='black',linewidth=1.5,markersize=8,markeredgewidth=1.5)
        self.ax.set_xlim(0,self.lx)
        self.ax.set_ylim(0,self.ly)
        for i in range(self.lx):
            for j in range(self.ly):
                self.points.append([i,j])

        cidb = connect('button_press_event', self.on_click)
        cidk = connect('key_press_event',self.on_click)
        cidm = connect('motion_notify_event',self.on_move)
Ejemplo n.º 42
0
    def __init__(self, field, fieldname, halospec=None):
        """Initializes a visualization instance, that is a windows with a field
        field is a 3D numpy array
        fieldname is a string with the name of the field
        halospec is a 2x2 array with the definition of the halo size

        After this call the window is shown
        """
        self.field = field
        self.fieldname = fieldname

        # Register halo information
        if halospec is None:
            halospec = [[3, 3], [3, 3]]
        self.istart = halospec[0][0]
        self.iend = field.shape[0] - halospec[0][1]
        self.jstart = halospec[1][0]
        self.jend = field.shape[1] - halospec[1][1]
        self.plotHalo = True
        self.plotLogLog = False

        self.curklevel = 0

        self.figure = plt.figure()

        # Slider
        slideraxes = plt.axes([0.15, 0.02, 0.5, 0.03], axisbg="lightgoldenrodyellow")
        self.slider = Slider(slideraxes, "K level", 0, field.shape[2] - 1, valinit=0)
        self.slider.valfmt = "%2d"
        self.slider.set_val(0)
        self.slider.on_changed(self.updateSlider)

        # CheckButton
        self.cbaxes = plt.axes([0.8, -0.04, 0.12, 0.15])
        self.cbaxes.set_axis_off()
        self.cb = CheckButtons(self.cbaxes, ("Halo", "Logscale"), (self.plotHalo, self.plotLogLog))
        self.cb.on_clicked(self.updateButton)

        # Initial plot
        self.fieldaxes = self.figure.add_axes([0.1, 0.15, 0.9, 0.75])
        self.collection = plt.pcolor(self._getField(), axes=self.fieldaxes)
        self.colorbar = plt.colorbar()
        self.fieldaxes.set_xlim(right=self._getField().shape[1])
        self.fieldaxes.set_ylim(top=self._getField().shape[0])
        plt.xlabel("i")
        plt.ylabel("j")
        self.title = plt.title("%s - Level 0" % (fieldname,))

        plt.show(block=False)
Ejemplo n.º 43
0
    def _recreate_show_lines_check_button(self):

        axcolor = "lightgoldenrodyellow"
        if hasattr(self, "rax_showlines"):
            self.rax_showlines.cla()
        self.rax_showlines = plt.axes([0.2, 0.05, self.button_length__, self.button_height__], axisbg=axcolor)

        visible = self.prop_ifs.holder.get_visible()
        linestyle = self.prop_ifs.holder.get_linestyle()

        labels = ("hide ifs", "markers", "edges", "labels")
        actives = (self.prop_ifs.hide_ifs, visible, linestyle not in ["None", None], self.prop_ifs.show_ann)

        self.holder_actives = dict(zip(labels, actives))

        self.w_check_components = CheckButtons(self.rax_showlines, labels, actives)

        self.w_check_components.on_clicked(self.update_show_components)
        return self.w_check_components
Ejemplo n.º 44
0
    def _recreate_show_lines_check_button(self):
        if self.ax_active not in self.active_lines_idx.keys():
            return None

        axcolor = 'lightgoldenrodyellow'
        if hasattr(self, 'rax_showlines'):
            self.rax_showlines.cla()
        self.rax_showlines = plt.axes([0.2, 0.05,
                                       self.button_length__,
                                       self.button_height__], axisbg=axcolor)
        prop_ifs = self._prop_idx_active[self.line_active__]
        visible = prop_ifs.holder.get_visible()
        linestyle = prop_ifs.holder.get_linestyle()
        
        self.w_check_components = CheckButtons(self.rax_showlines, 
                        ('markers', 'edges', 'labels'),
                        (visible, linestyle not in ['None', None], prop_ifs.show_ann))
        self.w_check_components.on_clicked(self.update_show_components)
        return self.w_check_components
Ejemplo n.º 45
0
    def __init__(self):


        self.data = 0
        self.errors = 0
        self.tBins = 0

        self.fig = plt.figure(1) 
        self.ax = self.fig.add_subplot(111,title="Pulse Display")
        self.fig.subplots_adjust(left=0.3)
        self.numPulse = 1
        self.flcFlag = False
        self.timeOffset = 0.0
        self.currentModelName=[]

        self.tMaxSelector = 0

        self.resultAx =False
        self.useSelector = False

        #check if a pulseModSelector has been passed
        self.pms = False
        self.radio = False

        ax = plt.axes([.05, 0.05, 0.12, 0.08])
        self.addButton = Button(ax,'Add Pulse',color='0.95', hovercolor='0.45')
        self.addButton.on_clicked(self.AddPulse)

        ax2 = plt.axes([.05, 0.15, 0.12, 0.08])
        self.findMaxButton = Button(ax2,'Find Max',color='0.95', hovercolor='0.45')
        self.findMaxButton.on_clicked(self.FindMax)

        ax3 = plt.axes([.05, 0.25, 0.12, 0.08])
        self.fitButton = Button(ax3,'Fit',color='0.95', hovercolor='0.45')
        self.fitButton.on_clicked(self.FitPulse)



        ax4 = plt.axes([.05, 0.45, 0.12, 0.08])
        self.useSelectorCheck = CheckButtons(ax4, ["Selector"], [False] )
        self.useSelectorCheck.on_clicked(self.UseSelector)
    def __init__(self, ax, collection, rax, raxmap, labels, labelcolors):
        self.canvas = ax.figure.canvas
        self.collection = collection
        self.labelcolors = [colorConverter.to_rgba(c) for c in labelcolors]
        self.labels = labels

        self.xys = collection.get_offsets()
        self.Npts = len(self.xys)

        # Ensure that we have separate colors for each object
        self.fc = collection.get_facecolors()
        if len(self.fc) == 0:
            raise ValueError('Collection must have a facecolor')
        elif len(self.fc) == 1:
            self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1)
        self.sfc = self.fc.copy()

        self.state = [False] * len(labels)
        self.check = CheckButtons(rax,labels,self.state)
        self.check.on_clicked(self.onclick)
        self.raxmap = raxmap
        self.ind = []
  color='orange', hovercolor='orange')
bmark.on_clicked(callback.mark)


axcolor = 'lightgoldenrodyellow'
rb1_axes = plt.axes([0.70, 0.62, 0.10, 0.15], axisbg=axcolor)
radio1 = RadioButtons(rb1_axes, ('A', 'B', 'C'))
def rb_1(label):
  print 'radio button 1'  

radio1.on_clicked(rb_1)


rax = plt.axes([0.70, 0.3, 0.2, 0.25])
labels=['Type 1','Type 2', 'Type 4', 'Other']
check = CheckButtons(rax, (labels[0], labels[1], labels[2], labels[3]), 
 (False, False, False, False))

def func(label):
    if label == labels[0]: check_text=labels[0]
    elif label == labels[1]: check_text=labels[1]
    elif label == labels[2]: check_text=labels[2]
    elif label == labels[3]: check_text=labels[3]
    print 'checked: ', check_text
check.on_clicked(func)


ax.text=(0.9, 0.9, 'ax.text 0.5')
fig.text=(0.9, 0.9, 'fig.text 0.5')


plt.show()
Ejemplo n.º 48
0
class Visualizer:
    def __init__(self, field, fieldname, halospec=None):
        """Initializes a visualization instance, that is a windows with a field
        field is a 3D numpy array
        fieldname is a string with the name of the field
        halospec is a 2x2 array with the definition of the halo size

        After this call the window is shown
        """
        self.field = field
        self.fieldname = fieldname

        # Register halo information
        if halospec is None:
            halospec = [[3, 3], [3, 3]]
        self.istart = halospec[0][0]
        self.iend = field.shape[0] - halospec[0][1]
        self.jstart = halospec[1][0]
        self.jend = field.shape[1] - halospec[1][1]
        self.plotHalo = True
        self.plotLogLog = False

        self.curklevel = 0

        self.figure = plt.figure()

        # Slider
        slideraxes = plt.axes([0.15, 0.02, 0.5, 0.03], axisbg="lightgoldenrodyellow")
        self.slider = Slider(slideraxes, "K level", 0, field.shape[2] - 1, valinit=0)
        self.slider.valfmt = "%2d"
        self.slider.set_val(0)
        self.slider.on_changed(self.updateSlider)

        # CheckButton
        self.cbaxes = plt.axes([0.8, -0.04, 0.12, 0.15])
        self.cbaxes.set_axis_off()
        self.cb = CheckButtons(self.cbaxes, ("Halo", "Logscale"), (self.plotHalo, self.plotLogLog))
        self.cb.on_clicked(self.updateButton)

        # Initial plot
        self.fieldaxes = self.figure.add_axes([0.1, 0.15, 0.9, 0.75])
        self.collection = plt.pcolor(self._getField(), axes=self.fieldaxes)
        self.colorbar = plt.colorbar()
        self.fieldaxes.set_xlim(right=self._getField().shape[1])
        self.fieldaxes.set_ylim(top=self._getField().shape[0])
        plt.xlabel("i")
        plt.ylabel("j")
        self.title = plt.title("%s - Level 0" % (fieldname,))

        plt.show(block=False)

    def updateSlider(self, val):
        if val == self.curklevel:
            return
        self.curklevel = round(val)
        self.title.set_text("%s - Level %d" % (self.fieldname, self.curklevel))

        # Draw new field level
        field = self._getField()
        size = field.shape[0] * field.shape[1]
        array = field.reshape(size)
        self.collection.set_array(array)

        self.colorbar.set_clim(vmin=field.min(), vmax=field.max())
        self.collection.set_clim(vmin=field.min(), vmax=field.max())
        self.colorbar.update_normal(self.collection)
        self.figure.canvas.draw_idle()

    def updateButton(self, label):
        if label == "Halo":
            self.plotHalo = not self.plotHalo
        if label == "Logscale":
            self.plotLogLog = not self.plotLogLog
        self.updatePlot()

    def updatePlot(self):

        # Redraw field
        self.collection.remove()
        field = self._getField()
        if self.plotLogLog:
            minvalue = field.min()
            norm = SymLogNorm(linthresh=1e-10)
            self.collection = plt.pcolor(field, axes=self.fieldaxes, norm=norm)
            self.colorbar.set_clim(vmin=minvalue, vmax=field.max())
        else:
            self.collection = plt.pcolor(field, axes=self.fieldaxes)
            self.colorbar.set_clim(vmin=field.min(), vmax=field.max())
            self.colorbar.set_norm(norm=Normalize(vmin=field.min(), vmax=field.max()))
        self.fieldaxes.set_xlim(right=field.shape[1])
        self.fieldaxes.set_ylim(top=field.shape[0])

        self.colorbar.update_normal(self.collection)
        self.figure.canvas.draw_idle()

    def _getField(self):
        if self.plotHalo:
            return np.rot90(self.field[:, :, self.curklevel])
        else:
            return np.rot90(self.field[self.istart : self.iend, self.jstart : self.jend, self.curklevel])
Ejemplo n.º 49
0
def evaluateKineticsGroupValues(family, database, method, testSetLabels, plot, exactOnly=False, estimateOnly=False):
    """
    Evaluate the kinetics group additivity values for the given reaction 
    `family` using the specified lists of depository components 
    `testSetLabels` as the test set. The already-loaded RMG database should be 
    given as the `database` parameter.
    """
    kunits = family.getRateCoefficientUnits()
    
    assert not (exactOnly and estimateOnly)
                    
    print 'Categorizing reactions in test sets for {0}'.format(family.label)
    testSets0 = []
    for testSetLabel in testSetLabels:
        testSet = createDataSet(testSetLabel, family, database)
        testSets0.append((testSetLabel, testSet))
    
    for testSetLabel, testSet in testSets0:
        for index in range(len(testSet)):
            reaction, template, entry = testSet[index]
            for reactant in reaction.reactants:
                if isinstance(reactant, Species) and not reactant.label and len(reactant.molecule) > 0:
                    reactant.label = reactant.molecule[0].toSMILES()
            for product in reaction.products:
                if isinstance(product, Species) and not product.label and len(product.molecule) > 0:
                    product.label = product.molecule[0].toSMILES()
    
    # For each entry in each test set, determine the kinetics as predicted by
    # RMG-Py and as given by the entry in the test set
    # Note that this is done on a per-site basis!
    kineticsModels = []; kineticsData = []
    testSets = []
    for testSetLabel, testSet0 in testSets0:
        testSet = []
        for index in range(len(testSet0)):
            reaction, template, entry = testSet0[index]
            krule = family.getKineticsForTemplate(template, degeneracy=1, method='rate rules')
            kgroup = family.getKineticsForTemplate(template, degeneracy=1, method='group additivity')
            kdata = convertKineticsToPerSiteBasis(reaction.kinetics, reaction.degeneracy)
            if exactOnly and not re.search('Exact', krule.comment):
                continue
            elif estimateOnly and not re.search('Estimated', krule.comment):
                continue   
            testSet.append((reaction, template, entry, krule, kgroup, kdata))
        testSets.append((testSetLabel, testSet))
    
    # Generate parity plots at several temperatures
    print 'Generating parity plots for {0}'.format(family.label)
    
    import matplotlib.pyplot as plt
    from matplotlib.widgets import CheckButtons
    
    Tdata = [500,1000,1500,2000]
    
    if kunits == 'm^3/(mol*s)':
        kunits = 'cm$^3$/mol*s'; kfactor = 1.0e6
    elif kunits == 's^-1':
        kunits = 's$^{-1}$'; kfactor = 1.0
    
    for T in Tdata:
        
        stdev_total = 0; ci_total = 0; count_total = 0
        
        # Initialize plot
        if plot == 'interactive':
            fig = pylab.figure(figsize=(10,8))
            ax = plt.subplot(1, 1, 1)
        else:
            fig = pylab.figure(figsize=(6,5))
            ax = plt.subplot(1, 1, 1) 
        ax = plt.subplot(1, 1, 1)
        lines = []
        legend = []
        
        # Iterate through the test sets, plotting each
        for testSetLabel, testSet in testSets:
            
            kmodel = []; kdata = []
            stdev = 0; ci = 0; count = 0
                
            for reaction, template, entry, kineticsRule, kineticsGroup, kineticsData in testSet:
                
                if method == 'rate rules':
                    kineticsModel = kineticsRule
                elif method == 'group additivity':
                    kineticsModel = kineticsGroup
                
                # Honor temperature ranges when plotting data
                # Place a dummy value so that the points so that the
                # interactivity is still correct
                if not kineticsData.isTemperatureValid(T):
                    kmodel.append(0.0)
                    kdata.append(0.0)
                    continue
                
                # Evaluate k(T) for both model and data at this temperature
                if isinstance(kineticsModel, ArrheniusEP):
                    km = kineticsModel.getRateCoefficient(T, 0) * kfactor
                else:
                    km = kineticsModel.getRateCoefficient(T) * kfactor
                kmodel.append(km)
                if isinstance(kineticsData, ArrheniusEP):
                    kd = kineticsData.getRateCoefficient(T, 0) * kfactor
                else:
                    kd = kineticsData.getRateCoefficient(T) * kfactor
                kdata.append(kd)
                
                # Evaluate variance
                stdev += (math.log10(km) - math.log10(kd))**2
                count += 1
            
            stdev_total += stdev
            count_total += count
            stdev = math.sqrt(stdev / (count - 1))
            ci = scipy.stats.t.ppf(0.975, count - 1) * stdev
            
            assert len(kmodel) == len(testSet)
            assert len(kdata) == len(testSet)
            
            print "Test set {0} contained {1} rates.".format(testSetLabel, count)
            print 'Confidence interval at T = {0:g} K for test set "{1}" = 10^{2:g}'.format(T, testSetLabel, ci)
        
            # Add this test set to the plot
            lines.append(ax.loglog(kdata, kmodel, 'o', picker=5)[0])
            legend.append(testSetLabel)
        
        stdev_total = math.sqrt(stdev_total / (count_total - 1))
        ci_total = scipy.stats.t.ppf(0.975, count_total - 1) * stdev_total
        
        print 'Total confidence interval at T = {0:g} K for all test sets = 10^{1:g}'.format(T, ci_total)
                
        # Finish plots
        xlim = pylab.xlim()
        ylim = pylab.ylim()
        lim = (min(xlim[0], ylim[0])*0.1, max(xlim[1], ylim[1])*10)
        ax.loglog(lim, lim, '-k')
        ax.loglog(lim, [lim[0] * 10**ci_total, lim[1] * 10**ci_total], '--k')
        ax.loglog(lim, [lim[0] / 10**ci_total, lim[1] / 10**ci_total], '--k')
        pylab.xlabel('Actual rate coefficient ({0})'.format(kunits))
        pylab.ylabel('Predicted rate coefficient ({0})'.format(kunits))
        if len(testSets) > 1:
            pylab.legend(legend, loc=4, numpoints=1)
        pylab.title('%s, T = %g K' % (family.label, T))
        pylab.xlim(lim)
        pylab.ylim(lim)
        
        plot_range = math.log10(lim[1] / lim[0])
        if plot_range > 25:
            majorLocator = matplotlib.ticker.LogLocator(1e5)
            minorLocator = matplotlib.ticker.LogLocator(1e5, subs=[1, 10, 100, 1000, 10000])
        elif plot_range > 20:
            majorLocator = matplotlib.ticker.LogLocator(1e4)
            minorLocator = matplotlib.ticker.LogLocator(1e4, subs=[1, 10, 100, 1000])
        elif plot_range > 15:
            majorLocator = matplotlib.ticker.LogLocator(1e3)
            minorLocator = matplotlib.ticker.LogLocator(1e3, subs=[1, 10, 100])
        elif plot_range > 10:
            majorLocator = matplotlib.ticker.LogLocator(1e2)
            minorLocator = matplotlib.ticker.LogLocator(1e2, subs=[1, 10])
        else:
            majorLocator = matplotlib.ticker.LogLocator(1e1)
            minorLocator = None   
        ax.xaxis.set_major_locator(majorLocator)
        ax.yaxis.set_major_locator(majorLocator)
        if minorLocator:
            ax.xaxis.set_minor_locator(minorLocator)
            ax.yaxis.set_minor_locator(minorLocator)
        
        def onpick(event):
            index = lines.index(event.artist)
            xdata = event.artist.get_xdata()
            ydata = event.artist.get_ydata()
            testSetLabel, testSet = testSets[index]
            for ind in event.ind:
                reaction, template, entry, krule, kgroup, kdata = testSet[ind]
                kunits = 'm^3/(mol*s)' if len(reaction.reactants) == 2 else 's^-1'
                print testSetLabel
                print 'template = [{0}]'.format(', '.join([g.label for g in template]))
                print 'entry = {0!r}'.format(entry)
                print str(reaction)
                print 'k_data   = {0:9.2e} {1}'.format(xdata[ind], kunits)
                print 'k_model  = {0:9.2e} {1}'.format(ydata[ind], kunits)
                print krule
                if kgroup: print kgroup
                print krule.comment
                if kgroup: print kgroup.comment
                print
                
        connection_id = fig.canvas.mpl_connect('pick_event', onpick)
        
        if plot == 'interactive':
            rax = plt.axes([0.15, 0.65, 0.2, 0.2])
            check = CheckButtons(rax, legend, [True for label in legend])
            
            def func(label):
                for index in range(len(lines)):
                    if legend[index] == label:
                        lines[index].set_visible(not lines[index].get_visible())
                plt.draw()
            check.on_clicked(func)
            
            fig.subplots_adjust(left=0.10, bottom=0.10, right=0.97, top=0.95, wspace=0.20, hspace=0.20)

        else:
            fig.subplots_adjust(left=0.15, bottom=0.14, right=0.95, top=0.93, wspace=0.20, hspace=0.20)
            filename = '{0}_{1:g}'.format(family.label, T)
            if method == 'rate rules':
                filename += '_rules'
            elif method == 'group additivity':
                filename += '_groups'
            if exactOnly:
                filename += '_exact'
            elif estimateOnly:
                filename += '_estimate'
            pylab.savefig('{0}.pdf'.format(filename))
            pylab.savefig('{0}.png'.format(filename), dpi=200)
          
        pylab.show()
Ejemplo n.º 50
0
    def displayResults2(self):
        """ show results with time slider

            geneNames have to be unique!

        """
##
##        import pylab
####        from matplotlib.widgets import Slider
##        mi=1
##        ma=self.results.shape[1]
##        print(ma)# should be 101
##
##        figure=pylab.figure()
##
##        ax=pylab.Axes(figure,[0.15, 0.1, 0.65, 0.03])
##        slider=pylab.Slider(ax=ax,label='time slider',valmin=mi,valmax=ma,valinit=1)
##
##        def update():
##            pylab.plot(self.results[:,slider.val,:])
##            pylab.draw()
##
##        slider.on_changed(update)
##        pylab.show()

        import pylab
        import scipy
        from matplotlib.widgets import Slider, Button, RadioButtons, CheckButtons


##        test = pylab.plot(self.results[:,-1,:])
##        pylab.show()

        # results is a data cube [cell, time, gene]
        miTime=0
        maTime=self.results.shape[1]-1
##        xdata=range(self.results.shape[0])

        ##ax = pylab.subplot(111)

        pylab.subplots_adjust(left=0.25, bottom=0.25)
##        t = scipy.arange(0.0, 1.0, 0.001)
##        a0 = 5
##        f0 = 3
##        s = a0*scipy.sin(2*scipy.pi*f0*t)
##        plot, = pylab.plot(t,s, lw=2, color='red')
        selection=scipy.ones(len(self.geneNames)).astype(bool)# select all on start
        plots = pylab.plot(self.results[:,maTime,:]) # apperently returns a plot for each line...


##        pylab.axis([0, 1, -10, 10])


        axcolor = 'lightgoldenrodyellow'
##        axfreq = pylab.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
##        axamp  = pylab.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)

##        sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
##        samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
        ax=pylab.axes([0.15, 0.1, 0.65, 0.03])
        slider=pylab.Slider(ax=ax,label='time slider',valmin=miTime,valmax=maTime,valinit=maTime)

        def update(val):
##            amp = samp.val
##            freq = sfreq.val
##            l.set_ydata(amp*scipy.sin(2*scipy.pi*freq*t))
            for i in range(len(plots)):
                plots[i].set_ydata(self.results[:,slider.val,i])
                plots[i].set_visible(selection[i])

            pylab.draw()

##        sfreq.on_changed(update)
##        samp.on_changed(update)
        slider.on_changed(update)

        resetax = pylab.axes([0.8, 0.025, 0.1, 0.04])
        button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
        def reset(event):
##            sfreq.reset()
##            samp.reset()
            slider.reset()
        button.on_clicked(reset)


        rax = pylab.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
        checker=CheckButtons(rax,self.geneNames,actives=selection)
        def selector(val):
##            print(val)
##            print(scipy.array(range(len(self.geneNames)))[self.geneNames==val][0])
            geneNr=scipy.array(range(len(self.geneNames)))[self.geneNames==val][0] # its retarded to check label names... but that is the way they like it....
            selection[geneNr]=not(selection[geneNr])
            update(slider.val)
        checker.on_clicked(selector)
##        print(checker.eventson)
##        print(checker.drawon)

##        radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)


##
##        rax = pylab.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
##        radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
##        def colorfunc(label):
##            for i in range(len(plots)):
##                plots[i].set_color(label)
####            plots.set_color(label)
##            pylab.draw()
##        radio.on_clicked(colorfunc)

        pylab.show()
Ejemplo n.º 51
0
#centers = utils.canopy_clustering(0.5, 0.65, X, utils.cosine_simularity)
#print "Number of seeds: ", len(centers)

#left, bottom, width, height


pace_ax = axes([.92,.28,.05,.05])
dur_ax = axes([.92,.34,.05,.05])
cal_ax = axes([.92,.22,.05,.05])
fuel_ax = axes([.92,.16,.05,.05])
distance_ax = axes([.92,.40,.05,.05])
reset_ax = axes([.92,.75,.05,.05])

clust_ax = axes([.03,.65,.05,.05])
rax = axes([.03, .75, .05,.15])
check = CheckButtons(rax, ('dist','dur','pace','cal','fuel'),(True, True, True, True, True))


b_pace = Button(pace_ax, "Pace")
b_dist = Button(distance_ax, "Dist")
b_dur = Button(dur_ax, "Duration")
b_cal = Button(cal_ax, "Calories")
b_fuel = Button(fuel_ax, "Fuel")
b_reset = Button (reset_ax, "Reset")
b_reclust = Button(clust_ax, "Cluster")


buckets = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5,13,13.5,14,14.5]
pace_buckets = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5,13,13.5,14,14.5]
dur_buckets = [0.0,  5.0,10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0, 65.0, 70.0, 75.0, 80.0, 85.0, 90.0, 95.0, 100.0, 105.0]
cal_buckets = [0,50,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000.0,1050,1100,1150,1200,1250,1300,1350,1400,1450,1500]
Ejemplo n.º 52
0
def svdplot(input_data, fmax=None, hold=0):

    if hold==0: pl.clf() # erase the figure, as this is a mult- axis plot
    else: pl.clf() # do it anyway, trying to overcome checkbuttons problem

    n_SV = len(input_data.svs)

    #for chrono in input_data.chronos:
    #    print(peak_freq(chrono, input_data.dim1))

    # define axes 
    ax1 = pl.subplot(221)
    ax2 = pl.subplot(222)
    ax3 = pl.subplot(223)
    ax4 = pl.subplot(224)

    # allow space for check buttons
    pl.subplots_adjust(left=0.2, right=0.98)

    # setup check boxes
    rax = pl.axes([0.01, 0.05, 0.09, 0.9])

    # CheckButtons take tuple arguments, tuples are immutable, so create lists fom svd info, and then cast as tuple
    button_name_list=[]
    button_setting_list=[]

    for i in range(n_SV):
        button_name_list.append('  '+str(i))
        button_setting_list.append(False)
        
    # have first 2 SVs on as default
    for i in [0,1]:
        button_setting_list[i] = True

        # like "self"
    check = CheckButtons(rax, tuple(button_name_list), tuple(button_setting_list))
    # hack to make check buttons square
    check_box_stretch = 7
    for i in range(len(check.rectangles)):
    #if (1 == 0):  # use this line instead of for i in... to turn off the hack
        check.rectangles[i].set_width(check_box_stretch*check.rectangles[i].get_height())
        for j in [0,1]: # two lines of the x
            orig_x_data = check.lines[i][j].get_xdata()
            orig_y_data = check.lines[i][j].get_ydata()
            orig_width = orig_x_data[1]-orig_x_data[0]
            new_width = check_box_stretch*orig_width
            new_x_data = [orig_x_data[0],orig_x_data[0]+new_width]
            check.lines[i][j].set_data(new_x_data,orig_y_data)

    # plot all SVs, use button_setting_list for initial visibility
    # axes 1: chrono
    pl.axes(ax1)
    #pl.xlabel('Time -*-get units from Timebase-*-')
    pl.ylabel('chronos [a.u.]')  # used to be labelled amplitude, but is not really.
    # you can get to the reconstructed signals via fs.signal, but chronos is better here
    ## python3 - all these plot_lists refactored to look nicer in python2/3
    plot_list_1 = [ ax1.plot(np.arange(len(input_data.chronos[sv_i])), input_data.chronos[sv_i], visible= button_setting_list[sv_i],alpha=0.5)[0] for sv_i in range(n_SV)]
    #pl.xlim(min(input_data.dim1), max(input_data.dim1))

    # axes 2: SVs
    pl.axes(ax2)
    sv_sv = [input_data.svs[i] for i in range(n_SV)]
    ax2.semilogy(np.arange(n_SV),sv_sv,'ko',markersize=3)
    # avoid extreme ylim ranges - start with no more than 10^3
    (ymin,ymax) = ax2.get_ylim()
    ax2.set_ylim(max(ymin, ymax/1000), ymax)
    entropy = input_data.H
    pl.xlabel('Singular Value number')
    pl.ylabel('Singular Value')
#    pl.figtext(0.75,0.83,'1/H = %.2f' %(1./entropy),fontsize=12, color='r')
#    pl.figtext(0.75,0.81,'H = %.2f' %(entropy),fontsize=12, color='b')
    # this is done in two places - potential for inconsistency - wish I knew better -dgp
    # These changes make it easier to adjust the subplot layout
    # was pl.figtext(0.75,0.78, (relative to figure), make it relative to axes
# Use kwargs so that most formatting is common to all three labels.    
    kwargs={'fontsize':8,'transform':ax2.transAxes,
            'horizontalalignment':'right', 'verticalalignment':'top'}
    bsl = np.array(button_setting_list)
    RMS_scale=np.sqrt(np.mean(
            (input_data.scales[:,0]*bsl)**2))
    ### Note: amp is dodgy - calcualted roughly here
    ## reconsider how fs p is calculated!  maybe factor scales in before sum
    ## Note also - a12 is calcuated differently here  but looks OK
    # Also, shold update these like Dave does with Energy
    amp=np.sqrt(np.sum(input_data.p*bsl))*RMS_scale
    print("amp=%.3g:" % (amp)),
    energy = Energy(input_data.p,bsl)
    energy_label = ax2.text(0.96,0.98,'E = %.1f %%' %(100.*energy.value),
                            color='b', **kwargs)

    labstr = str('tmid = {tm:.1f} ms, 1/H = {invH:.2f}, below for 0,1, '\
                     '?Amp = {Amp:.2g}, a12 = {a12:.2f} '
                 .replace(', ','\n')
                 .format(tm=1e3*np.average(input_data.chrono_labels),
                         invH=(1./entropy), 
                         Amp = float(np.sqrt(np.sum(input_data.p*bsl))*RMS_scale),
                         a12 = float(np.sqrt(input_data.p[1]/input_data.p[0]))))
    ax2.text(0.96,0.85,labstr, color='r', **kwargs)

    # grid('True')
    plot_list_2 = []
    for sv_i in range(n_SV):        
        col = plot_list_1[sv_i].get_color()
        plot_list_2.append(ax2.semilogy([sv_i], [input_data.svs[sv_i]],
                                        '%so' %(col),visible= button_setting_list[sv_i],
                                        markersize=8,alpha=0.5)[0])

    # axes 3: fft(chrono)
    pl.axes(ax3)
    pl.xlabel('Frequency [kHz]')
    pl.ylabel('Power Spectrum')
    pl.grid(True)            # matplotlib 1.0.X wants a boolean (unquoted)
    nyquist_kHz = 1.e-3*0.5/np.average(np.diff(input_data.chrono_labels))
    plot_list_3 = []
    for sv_i in range(n_SV):
        col = plot_list_1[sv_i].get_color()
        tmp_chrono = input_data.chronos[sv_i]
        tmp_fft = np.fft.fft(tmp_chrono)[:len(tmp_chrono)//2]
        freq_array = nyquist_kHz*np.arange(len(tmp_fft))/(len(tmp_fft)-1)
        plot_list_3.append(ax3.plot(freq_array, abs(tmp_fft), col,visible= button_setting_list[sv_i],alpha=0.5)[0])
        
    if fmax is None: 
        ffact = 1e3  # seems like this routine is in kHz - where does it cvt?
        try:
            axt = eval(pyfusion.config.get('Plots','FT_Axis'))
            if axt[3]<2e3: ffact=1.0  # avoid a python3 issue 
            fmax = axt[3]/ffact
        except:
            fmax = nyquist_kHz
        
    pl.xlim(0,fmax)

    # axes 4: topo
    pl.axes(ax4)
    pl.xlabel('Channel')
    pl.ylabel('Topo [a.u.]')
    angle_array = np.arange(n_SV+1)
    #channel_names = input_data.timesegment.data[input_data.diagnostic.name].ordered_channel_list
    #channel_names.append(channel_names[0])
    #pl.xticks(angle_array,channel_names, rotation=90)
    plot_list_4 = []
    for sv_i in range(n_SV):
        col = plot_list_1[sv_i].get_color()
        tmp_topo = join_ends(input_data.topos[sv_i])
        pos,neg =  posNegFill(angle_array,np.zeros(len(angle_array)),tmp_topo)
        ### BUG: it looks like ax4.fill doesn't work in a couple of cases, leaving sub_plot_4_list[i] as int, which raises a set_visible() bug in button_action - also has problems with draw(). other subplots all worked fine before I started with subplot 4
        sub_plot_4_list = list(range(len(pos)+len(neg)+2))
        for j in range(len(pos)):
            sub_plot_4_list[j], = ax4.fill(pos[j][0],pos[j][1],col,visible= button_setting_list[sv_i],alpha=0.5)
        for j in range(len(neg)):
            sub_plot_4_list[j+len(pos)], = ax4.fill(neg[j][0],neg[j][1],col,visible= button_setting_list[sv_i],alpha=0.5)
                
        sub_plot_4_list[len(neg)+len(pos)+0], = ax4.plot(angle_array,tmp_topo,'%so' %(col),visible= button_setting_list[sv_i],markersize=3)
        # show repeated val
        sub_plot_4_list[len(neg)+len(pos)+1], = ax4.plot([angle_array[-1]],[tmp_topo[-1]],'kx', visible= button_setting_list[sv_i],markersize=6)
        debug_(pyfusion.DEBUG, 2, key='svdplot')
        plot_list_4.append(sub_plot_4_list)

    def test_action(label):
        print(label)

    def button_action(label):
        print('action')
	# this is not very clear: but basically, the label is the str() of the element of plot_list_x we want to make / unmake visible
        visible_status = plot_list_1[int(label)].get_visible()
        plot_list_1[int(label)].set_visible(not visible_status)
        plot_list_2[int(label)].set_visible(not visible_status)
        plot_list_3[int(label)].set_visible(not visible_status)
        for i in range(len(plot_list_4[int(label)])):
            plot_list_4[int(label)][i].set_visible(not visible_status)
        # if visible_status == False, then we are adding visiblity => add to energy, vice-verca
        if visible_status:
            energy.sub(int(label))
        else:
            energy.add(int(label))
        energy_label._text='E = %.2f %%' %(100.*energy.value)
        pl.draw()

    # action when button is clicked
    check.on_clicked(button_action)
    #check.on_clicked(test_action)

    # show plot
    pl.show(block=hold)
Ejemplo n.º 53
0
def initialize(A,B,C,dA,dB,dC,DJ,DJK,DK,dJ,dK,ua,ub,uc,f_lower,f_upper,T,J_max,last_times_picked_list):
    #matplotlib.use('TkAggx')
    global DJ_g,DJK_g,DK_g,ua_g,ub_g,uc_g,T_g,dJ_g,dK_g,f_lower_g,f_upper_g,J_max_g
    J_max_g = J_max
    DJ_g = DJ
    DJK_g = DJK
    DK_g = DK
    ua_g = ua
    ub_g = ub
    uc_g = uc
    T_g=T
    dJ_g = dJ
    dK_g = dK
    f_lower_g = f_lower
    f_upper_g = f_upper
    
    
    global picked_list
    picked_list = last_times_picked_list
    plt.close()
    global figure_h
    figure_h = plt.figure(figsize=(16.5, 4))
    try:
        figure_h.canvas.manager.window.Move((00,00))
    except AttributeError:
        pass
    #thismanager = pl.get_current_fig_manager()
    #thismanager.window.SetPosition((00, 0))
    #thismanager.window.wm_geometry("+00+0")
    


    int_writer(ua,ub,uc,temp=T_g,freq=(f_upper_g/1000))
    var_writer_uncert(A,B,C,DJ,DJK,DK,dJ_g,dK_g)
    run_SPCAT()
    data = cat_reader()
    global t
    global s
    t = []
    s = []
    t_b = []
    s_b = []    
    for x in data:
        s.append(0.0)
        s.append(str(10**float(x[1]))) 
        s.append(0.0)
        t.append(float(x[0])-0.0001)
        t.append(x[0])
        t.append(float(x[0])+0.0001)
        for y in picked_list:
            if x[2]==y[1] and x[3]==y[2]:
                s_b.append(0.0)
                s_b.append(str(10**float(x[1]))) 
                s_b.append(0.0)
                t_b.append(float(x[0])-0.0001)
                t_b.append(x[0])
                t_b.append(float(x[0])+0.0001)  
    ax = figure_h.add_subplot(212)
    plt.subplots_adjust(left=0.25, bottom=0.25)
    pl.subplots_adjust( hspace=0.0,right=0.97 )

    
    
    a0 = 5
    f0 = 3
    global l,triples_plt
    l, = plt.plot(t,s, lw=2, color='red')
    triples_plt, = plt.plot([],[], '*',markersize=15,color='blue')
    ax.set_xlim([f_lower_g,f_upper_g])
    global picked_plt, ax2
    picked_plt, = plt.plot(t_b,s_b,lw=2,color='black')
    #plt.axis([0, 1, -10, 10])
    #figure_h.canvas.mpl_connect('button_press_event', handle_mouse_press)
    ax2 = figure_h.add_subplot(211,sharex=ax)
    ax2.axes.get_xaxis().set_visible(False)
    
    global peak_list_plt,exp_plt,trans_1_plt,trans_2_plt,trans_3_plt
    peak_list_plt, = ax2.plot([],[],'o',color='red')
    trans_1_plt, = ax2.plot([],[],'s',color='cyan')
    trans_2_plt, = ax2.plot([],[],'s',color='magenta')
    trans_3_plt, = ax2.plot([],[],'s',color='yellow')
    ax2.set_xlim([f_lower_g,f_upper_g])
    global locator   
    locator = ax2.yaxis.get_major_locator() 

    exp_plt, = ax2.plot([],[],lw=2,color='black')

    global peak_1_uncertainty,peak_2_uncertainty,peak_3_uncertainty,peaklist,freq_low,freq_high


    figure_h.canvas.mpl_connect('key_press_event', on_key)
    axcolor = 'lightgoldenrodyellow'
    axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
    axB  = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    axC  = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
    
    axua = plt.axes([0.03, 0.22, 0.1, 0.03], axisbg=axcolor)
    axub = plt.axes([0.03, 0.17, 0.1, 0.03], axisbg=axcolor)
    axuc = plt.axes([0.03, 0.12, 0.1, 0.03], axisbg=axcolor)
    #axub  = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    #axuc  = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
    global ua_slider
    ua_slider = Slider(axua, 'mu a', ua_g-1, ua_g+1, valinit=ua_g)
    ua_slider.on_changed(update)
    global ub_slider
    ub_slider = Slider(axub, 'mu b', ub_g-1, ub_g+1, valinit=ub_g)
    ub_slider.on_changed(update)
    global uc_slider
    uc_slider = Slider(axuc, 'mu c', uc_g-1, uc_g+1, valinit=uc_g)
    uc_slider.on_changed(update)
    global A_slider
    global B_slider
    global C_slider
    global rax
    rax = plt.axes([0.0, 0.5, 0.19, 0.4])
    global check
    check = CheckButtons(rax, ('','','',''), (True, False, False,False))
    

    check.on_clicked(func)
    
    
    
    
    A_slider = Slider(axA, 'A', A-dA, A+dA, valinit=A)
    B_slider = Slider(axB, 'B', B-dB, B+dB, valinit=B)
    C_slider = Slider(axC, 'C', C-dC, C+dC, valinit=C)
    
    
    
    A_slider.on_changed(update)
    B_slider.on_changed(update)
    C_slider.on_changed(update)
    global button
    global radio
    resetax = plt.axes([0.1, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset Sliders', color=axcolor, hovercolor='0.975')

    button.on_clicked(reset)
    #rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
    #radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
    #radio.on_clicked(colorfunc)
    global text_box
    #global text_box2
    text_box = plt.text(-1,8, "")
    text_box2 = plt.text(-1,23, "Refine Mouse Selection:                             Select transitions by pushing 'q' and then clicking in the predicted spectrum ")
Ejemplo n.º 54
0
def animate(sources, reflect=False):
    fig = plt.figure()

    # create reflection images of sources
    if reflect:
        reflectedSources = []
        for src in sources:
            reflSrc = deepcopy(src)
            reflSrc.pos = -src.pos
            reflectedSources.append(reflSrc)

            
    # subplot for every source
    lines = []
    for i, src in enumerate(sources):
        # pressure on left y axis
        ax1 = fig.add_subplot(len(sources)+1, 1, i+1)
        ax1.set_xlim([0, xMax])
        yLim = src.pAmpl * 1.3 * (1+reflect)
        ax1.set_ylim([-yLim, yLim])
        ax1.set_ylabel('p')
        line_pSrc, = plt.plot([], [], 'r--', lw=1)
        line_pRefl, = plt.plot([], [], 'r:', lw=1)
        line_p, = plt.plot([], [], 'r', lw=1, label='p')
        ax1.legend(loc='upper left')
                
        # velocity on right y axis
        ax2 = ax1.twinx()
        ax2.set_xlim([0, xMax])
        yLim = src.uAmpl * 2  * (1+reflect)
        ax2.set_ylim([-yLim, yLim])
        ax2.set_ylabel('u')
        line_uSrc, = plt.plot([], [], 'b--', lw=1)
        line_uRefl, = plt.plot([], [], 'b:', lw=1)
        line_u, = plt.plot([], [], 'b', lw=1, label='u')
        ax2.legend(loc='upper right')

        ax1.set_title(src.name)
        lines.append([line_pSrc, line_uSrc, line_pRefl, line_uRefl, line_p, line_u])

    # subplot for total pressure and velocity
    # pressure on left y axis
    ax1 = fig.add_subplot(len(sources)+1, 1, len(sources)+1)
    ax1.set_xlim([0, xMax])
    yLim = sum([src.pAmpl for src in sources]) * 1.3 * (1+reflect)
    ax1.set_ylim([-yLim, yLim])
    ax1.set_ylabel('p')
    line_p, = plt.plot([], [], 'r', lw=1, label='p')
    ax1.legend(loc='upper left')

    # velocity on right y axis
    ax2 = ax1.twinx()
    ax2.set_xlim([0, xMax])
    yLim = sum([src.uAmpl for src in sources]) * 2 * (1+reflect)
    ax2.set_ylim([-yLim, yLim])
    ax2.set_ylabel('u')
    line_u, = plt.plot([], [], 'b', lw=1, label='u')
    ax2.legend(loc='upper right')

    ax1.set_title('Sum of all sources')
    lineSum = [line_p, line_u]

    
    # interactive plots :)
    plt.subplots_adjust(left=0.15, top=0.9)
    showVelocity = [not reflect]  # value in list - a hack to use nonlocal in Python 2
    showPressure = [True]
    checkAx = plt.axes([0.05, 0.6, 0.05, 0.15])
    checkButtons = CheckButtons(checkAx, ('p', 'v'), (True, showVelocity[0]))
    def toggleLines(label):
        if label == 'p': 
            showPressure[0] = not showPressure[0]
        elif label == 'v':
            showVelocity[0] = not showVelocity[0]
    checkButtons.on_clicked(toggleLines)

    resetAnimation = [False]
    buttonAx = plt.axes([0.05, 0.85, 0.05, 0.04])
    button = Button(buttonAx, 'Reset', hovercolor='0.975')
    def reset(event):
        resetAnimation[0] = True
    button.on_clicked(reset)
    

    

    def drawBackground():
        for iSrc, src in enumerate(sources):
            lines[iSrc][0].set_data([src.pos, src.pos],
                                    [-src.pAmpl * 3, src.pAmpl * 3])
            for line in lines[iSrc][1:]:
                line.set_data([], [])
        
        lineSum[0].set_data([], [])
        lineSum[1].set_data([], [])
        
        return tuple(itertools.chain(*lines)) + tuple(lineSum)
        
    def drawFrame(i):
        t = i * SPEED
        x = np.linspace(0, xMax, nPOINTS)
        pSum = np.zeros(nPOINTS)
        uSum = np.zeros(nPOINTS)
        for iSrc, src in enumerate(sources):
            pDirect = np.zeros(nPOINTS)
            uDirect = np.zeros(nPOINTS)
            pRefl = np.zeros(nPOINTS)
            uRefl = np.zeros(nPOINTS)
            p = np.zeros(nPOINTS)
            u = np.zeros(nPOINTS)
            for i in xrange(0, nPOINTS):
                pDirect[i] = src.p(pnt2x(i), t)
                uDirect[i] = src.u(pnt2x(i), t)
                if reflect:
                    pRefl[i] = reflectedSources[iSrc].p(pnt2x(i), t)
                    uRefl[i] = reflectedSources[iSrc].u(pnt2x(i), t)
                pSum[i] += (pDirect[i] + pRefl[i])
                uSum[i] += (uDirect[i] + uRefl[i])

            p = pDirect + pRefl
            u = uDirect + uRefl

            if showPressure[0]:
                lines[iSrc][0].set_data(x, pDirect)
                lines[iSrc][2].set_data(x, pRefl)
                lines[iSrc][4].set_data(x, p)
            else:
                lines[iSrc][0].set_data([], [])
                lines[iSrc][2].set_data([], [])
                lines[iSrc][4].set_data([], [])
            if showVelocity[0]:
                lines[iSrc][1].set_data(x, uDirect)
                lines[iSrc][3].set_data(x, uRefl)
                lines[iSrc][5].set_data(x, u)
            else:
                lines[iSrc][1].set_data([], [])
                lines[iSrc][3].set_data([], [])
                lines[iSrc][5].set_data([], [])

        if showPressure[0]:
            lineSum[0].set_data(x, pSum)
        else:
            lineSum[0].set_data([], [])
        if showVelocity[0]:
            lineSum[1].set_data(x, uSum)
        else:
            lineSum[1].set_data([], [])

        return tuple(itertools.chain(*lines)) + tuple(lineSum)

    def cnt():
        i = 0
        while True:
            yield i
            if resetAnimation[0]:
                i = 0
                resetAnimation[0] = False
            else:
                i += 1
        
    anim = animation.FuncAnimation(fig, drawFrame, init_func=drawBackground,
                                   frames=cnt, interval=40, blit=True, repeat=False)
    plt.show()
Ejemplo n.º 55
0
def plot_data_for_station(station, available_data, event, get_data_callback,
                          domain_bounds):
    """
    Plots all data for a station in an interactive plot.

    :type station: dict
    :param station: A dictionary containing the keys 'id', 'latitude',
        'longitude', 'elevation_in_m', and 'local_depth_in_m' describing the
        current station.
    :type available_data: dict
    :param available_data: The available processed and synthetic data. The raw
        data is always assumed to be available.
    :type event: dict
    :param event: A dictionary describing the current event.
    :type get_data_callback: function
    :param get_data_callback: Callback function returning an ObsPy Stream
        object.

        get_data_callback("raw")
        get_data_callback("synthetic", iteration_name)
        get_data_callback("processed", processing_tag)

    :type domain_bounds: dict
    :param domain_bounds: The domain bounds.
    """
    import datetime
    import matplotlib.dates
    from matplotlib.widgets import CheckButtons
    from obspy.core.util.geodetics import calcVincentyInverse
    import textwrap

    # Setup the figure, the window and plot title.
    fig = plt.figure(figsize=(14, 9))
    fig.canvas.set_window_title("Data for station %s" % station["id"])
    fig.text(0.5, 0.99, "Station %s" % station["id"],
             verticalalignment="top", horizontalalignment="center")

    # Add one axis for each component. Share all axes.
    z_axis = fig.add_axes([0.30, 0.65, 0.68, 0.3])
    n_axis = fig.add_axes([0.30, 0.35, 0.68, 0.3], sharex=z_axis,
                          sharey=z_axis)
    e_axis = fig.add_axes([0.30, 0.05, 0.68, 0.3], sharex=z_axis,
                          sharey=z_axis)
    axis = [z_axis, n_axis, e_axis]

    # Set grid, autoscale and hide all tick labels (some will be made visible
    # later one)
    for axes in axis:
        plt.setp(axes.get_xticklabels(), visible=False)
        plt.setp(axes.get_yticklabels(), visible=False)
        axes.grid(b=True)
        axes.autoscale(enable=True)
        axes.set_xlim(0.0, 12345.0)

    # Axes for the data selection check boxes.
    raw_check_axes = fig.add_axes([0.01, 0.8, 0.135, 0.15])
    synth_check_axes = fig.add_axes([0.155, 0.8, 0.135, 0.15])
    proc_check_axes = fig.add_axes([0.01, 0.5, 0.28, 0.29])

    # The map axes
    map_axes = fig.add_axes([0.01, 0.05, 0.28, 0.40])

    # Fill the check box axes.
    raw_check = CheckButtons(raw_check_axes, ["raw"], [True])
    proc_check = CheckButtons(proc_check_axes, [
        "\n".join(textwrap.wrap(_i, width=30))
        for _i in available_data["processed"]],
        [False] * len(available_data["processed"]))
    synth_check = CheckButtons(synth_check_axes, available_data["synthetic"],
                               [False] * len(available_data["synthetic"]))

    for check in [raw_check, proc_check, synth_check]:
        plt.setp(check.labels, fontsize=10)

    raw_check_axes.text(
        0.02, 0.97, "Raw Data", transform=raw_check_axes.transAxes,
        verticalalignment="top", horizontalalignment="left", fontsize=10)
    proc_check_axes.text(
        0.02, 0.97, "Processed Data", transform=proc_check_axes.transAxes,
        verticalalignment="top", horizontalalignment="left", fontsize=10)
    synth_check_axes.text(
        0.02, 0.97, "Synthetic Data", transform=synth_check_axes.transAxes,
        verticalalignment="top", horizontalalignment="left", fontsize=10)

    bounds = domain_bounds["bounds"]
    map_object = plot_domain(
        bounds["minimum_latitude"], bounds["maximum_latitude"],
        bounds["minimum_longitude"], bounds["maximum_longitude"],
        bounds["boundary_width_in_degree"],
        rotation_axis=domain_bounds["rotation_axis"],
        rotation_angle_in_degree=domain_bounds["rotation_angle"],
        plot_simulation_domain=False, zoom=True, ax=map_axes)

    plot_stations_for_event(map_object=map_object,
                            station_dict={station["id"]: station},
                            event_info=event)
    # Plot the beachball for one event.
    plot_events([event], map_object=map_object, beachball_size=0.05)
    dist = calcVincentyInverse(
        event["latitude"], event["longitude"], station["latitude"],
        station["longitude"])[0] / 1000.0

    map_axes.set_title("Epicentral distance: %.1f km | Mag: %.1f %s" %
                       (dist, event["magnitude"], event["magnitude_type"]),
                       fontsize=10)

    PLOT_OBJECTS = {
        "raw": None,
        "synthetics": {},
        "processed": {}
    }

    def plot(plot_type, label=None):
        if plot_type == "raw":
            st = get_data_callback("raw")
            PLOT_OBJECTS["raw"] = []
            save_at = PLOT_OBJECTS["raw"]
        elif plot_type == "synthetic":
            st = get_data_callback("synthetic", label)
            PLOT_OBJECTS["synthetics"][label] = []
            save_at = PLOT_OBJECTS["synthetics"][label]
        elif plot_type == "processed":
            st = get_data_callback("processed", label)
            PLOT_OBJECTS["processed"][label] = []
            save_at = PLOT_OBJECTS["processed"][label]

        # Loop over all traces.
        for tr in st:
            # Normalize data.
            tr.data = np.require(tr.data, dtype="float32")
            tr.data -= tr.data.min()
            tr.data /= tr.data.max()
            tr.data -= tr.data.mean()
            tr.data /= np.abs(tr.data).max() * 1.1

            # Figure out the correct axis.
            component = tr.stats.channel[-1].upper()
            if component == "N":
                axis = n_axis
            elif component == "E":
                axis = e_axis
            elif component == "Z":
                axis = z_axis
            else:
                raise NotImplementedError

            if plot_type == "synthetic":
                time_axis = matplotlib.dates.drange(
                    event["origin_time"].datetime,
                    (event["origin_time"] + tr.stats.delta * (tr.stats.npts))
                    .datetime,
                    datetime.timedelta(seconds=tr.stats.delta))
                zorder = 2
                color = "red"
            elif plot_type == "raw":
                time_axis = matplotlib.dates.drange(
                    tr.stats.starttime.datetime,
                    (tr.stats.endtime + tr.stats.delta).datetime,
                    datetime.timedelta(seconds=tr.stats.delta))
                zorder = 0
                color = "0.8"
            elif plot_type == "processed":
                time_axis = matplotlib.dates.drange(
                    tr.stats.starttime.datetime,
                    (tr.stats.endtime + tr.stats.delta).datetime,
                    datetime.timedelta(seconds=tr.stats.delta))
                zorder = 1
                color = "0.2"
            else:
                msg = "Plot type '%s' not known" % plot_type
                raise ValueError(msg)

            save_at.append(axis.plot_date(time_axis[:len(tr.data)], tr.data,
                           color=color, zorder=zorder, marker="",
                           linestyle="-"))
            axis.set_ylim(-1.0, 1.0)
            axis.xaxis.set_major_formatter(
                matplotlib.dates.DateFormatter("%H:%M:%S"))

            if component == "E":
                try:
                    plt.setp(axis.get_xticklabels(), visible=True)
                except:
                    pass

            if plot_type != "raw":
                axis.set_xlim(time_axis[0], time_axis[-1])
            # Adjust the limit only if there are no synthetics and processed if
            # plotting raw data.
            elif not PLOT_OBJECTS["synthetics"] and \
                    not PLOT_OBJECTS["processed"]:
                axis.set_xlim(time_axis[0], time_axis[-1])

        for label, axis in zip(("Vertical", "North", "East"),
                               (z_axis, n_axis, e_axis)):
            axis.text(0.98, 0.95, label,
                      verticalalignment="top", horizontalalignment="right",
                      bbox=dict(facecolor="white", alpha=0.5, pad=5),
                      transform=axis.transAxes, fontsize=11)

    def _checked_raw(label):
        checked(label, "raw")

    def _checked_proc(label):
        checked(label, "proc")

    def _checked_synth(label):
        checked(label, "synth")

    def checked(label, check_box):
        if check_box == "raw":
            if PLOT_OBJECTS["raw"] is not None:
                for _i in PLOT_OBJECTS["raw"]:
                    for _j in _i:
                        _j.remove()
                PLOT_OBJECTS["raw"] = None
            else:
                PLOT_OBJECTS["raw"] = []
                plot("raw")
        elif check_box == "synth":
            if label in PLOT_OBJECTS["synthetics"]:
                for _i in PLOT_OBJECTS["synthetics"][label]:
                    for _j in _i:
                        _j.remove()
                del PLOT_OBJECTS["synthetics"][label]
            else:
                PLOT_OBJECTS["synthetics"][label] = []
                plot("synthetic", label=label)
        elif check_box == "proc":
            # Previously broken up.
            label = label.replace("\n", "")
            if label in PLOT_OBJECTS["processed"]:
                for _i in PLOT_OBJECTS["processed"][label]:
                    for _j in _i:
                        _j.remove()
                del PLOT_OBJECTS["processed"][label]
            else:
                PLOT_OBJECTS["processed"][label] = []
                plot("processed", label=label)

        try:
            fig.canvas.draw()
        except:
            pass

    raw_check.on_clicked(_checked_raw)
    proc_check.on_clicked(_checked_proc)
    synth_check.on_clicked(_checked_synth)

    # Always plot the raw data by default.
    _checked_raw("raw")

    try:
        fig.canvas.draw()
    except:
        pass

    # One has call plt.show() to activate the main loop of the new figure.
    # Otherwise events will not work.
    plt.gcf().patch.set_alpha(0.0)
    plt.show()
class Graphics (GraphMolecule, GraphBias, GraphTrans, GraphOrbitals, GraphIVCurve):
    """ Manages the graphical representation of the project
        Attributes
        fig                     Handle to the entire figure
        Bias                    The selected bias
        Gate                    The selected gate voltage
        OrbitalSel              The selected orbital or series of orbitals

        axSC                    Handle to the radio buttons window for the self consistency
        cbSC                    Handle to the radio buttons for the self consistency

        axOptions1              Handle to the checkbox window with options 1
        cbOptions1              Handle to the checkboxes with options 1
        
        axOptions2              Handle to the checkbox window with options 2
        cbOptions2              Handle to the checkboxes with options 2

        axGleft, axGright       Handle to the slider windows for selecting the lead interaction strength
        sGleft,  sGright        Handle to the sliders for selecting the lead interaction strength

        axSave                  Handle to the save button window
        bSave                   Handle to the save button

        Methods
        init()
        OnPick(event)           Manages the pick events
        OnClick(event)          Manages the on click events
        Save()                  Manages the input from the save button
        Options1(label)         Manages the input from the options 1 window
        Options2(label)         Manages the input from the options 2 window

        SetMolecule(Mol)        Sets the molecule class from which the graphics gets its information
        UpdateMolecule()        Updates everything that changes when the molecule has changed

        UpdateConsistency(label)Updates the selected consistency method
        UpdateG(val)            Updates the interaction strength with the leads
        UpdateBias(bias)        Updates the selected bias
        UpdateHamExt()          Updates everything that changes when the extended hamiltonian is changed
        
        UpdateGate(gate)        Updates the selected gate voltage
        UpdateAtomSel(iAtom)    Updates the selected atom
        UpdateOrbitalSel(iOrb)  Updates the selected orbital
        UpdateSelection()       Updates everything that changes after one of the selections has changed

    """

    def __init__(self):
        self.Consistency = 'Not self consistent'
        self.Bias = 0.1
        self.Gate = None
        self.OrbitalSel = None
        self.fig, (self.axBias, self.axTrans, self.axIVCurve) = plt.subplots(3,1)
        self.fig.patch.set_facecolor('ghostwhite')
        plt.subplots_adjust(left=0.3)
        pos = self.axBias.get_position()
        self.axBias.set_position ([pos.x0, 0.55, pos.width, 0.40])
        self.axTrans.set_position([pos.x0, 0.05, pos.width, 0.40])
        self.axIVCurve.set_position([0.05, 0.05, 0.2, 0.3])
        self.axCM = self.fig.add_axes([0.94, 0.55, 0.01, 0.35])

        self.fig.canvas.mpl_connect('button_press_event', self.OnClick)
        self.fig.canvas.mpl_connect('pick_event', self.OnPick)
        self.fig.canvas.mpl_connect('key_press_event', self.OnPress)

        self.InitMolecule()
        self.InitBias()
        self.InitTrans()
        self.InitOrbitals()
        self.InitIVCurve()
        
        self.axSC = plt.axes([0.05, 0.85, 0.15, 0.10], axisbg='white')
        self.cbSC = RadioButtons(self.axSC, ('Not self consistent', 'Hubbard', 'PPP'))
        self.cbSC.on_clicked(self.UpdateConsistency)

        self.axOptions1 = plt.axes([0.05, 0.7, 0.15, 0.10], axisbg='white')
        self.cbOptions1 = CheckButtons(self.axOptions1, ('Overlap', 'Show Local Density','Show Local Currents'), (False, False, True))
        self.cbOptions1.on_clicked(self.Options1)
        
        self.axOptions2 = plt.axes([0.05, 0.5, 0.15, 0.15], axisbg='white')
        self.cbOptions2 = CheckButtons(self.axOptions2, ('Show Transmission', 'Show Current', 'Show DOS', 'Show Orbitals', 'Show Phase'), (True, True, False, False, False))
        self.cbOptions2.on_clicked(self.Options2)
        c = ['seagreen', 'b', 'darkorange', 'lightsteelblue', 'm']    
        [rec.set_facecolor(c[i]) for i, rec in enumerate(self.cbOptions2.rectangles)]
        
        self.axGleft  = plt.axes([0.05, 0.43, 0.15, 0.02], axisbg='white')
        self.axGright = plt.axes([0.05, 0.40, 0.15, 0.02], axisbg='white')
        self.sGleft   = Slider(self.axGleft,  'Gl', 0.0, 1.0, valinit = gLeft)
        self.sGright  = Slider(self.axGright, 'Gr', 0.0, 1.0, valinit = gRight)
        self.sGleft.on_changed(self.UpdateG)
        self.sGright.on_changed(self.UpdateG)
        
        self.axSave = plt.axes([0.92, 0.95, 0.07, 0.04])
        self.bSave = Button(self.axSave, 'Save')
        self.bSave.on_clicked(self.Save)

    def OnPick(self, event):
        if isinstance(event.artist, Rectangle):
            self.OnPickOrbital(event)
        else:
            self.OnPickMolecule(event)
                   
    def OnClick (self, event):
        if event.inaxes==self.axMol:
            if event.button==1:
                self.OnClickMolecule (event)
            elif event.button==3:
                self.OnClickBias (event)
        elif event.inaxes==self.axOrb:
            if event.button==1:
                return
            if event.button==3:
                self.OnClickTrans (event)
        return

    def Save(self, event):
        self.Mol.Save()

    def Options1(self, label):
        if label == 'Overlap':
            self.Mol.SetOverlap(self.cbOptions1.lines[0][0].get_visible())
            self.UpdateMolecule()
        elif label == 'Show Local Density':
            self.DrawLocalDensity(self.cbOptions1.lines[1][0].get_visible())
        elif label == 'Show Local Currents':
            self.DrawLocalCurrents(self.cbOptions1.lines[2][0].get_visible())
        return

    def Options2(self, label):
        if label == 'Show Transmission':
            self.DrawTransmission()
        elif label == 'Show Current':
            self.DrawCurrent()
        elif label == 'Show DOS':
            self.DrawDOS()
        elif label == 'Show Orbitals':
            self.DrawOrbitals()
            self.DrawSelOrbitals()
        elif label == 'Show Phase':
            self.DrawTransmission()
            self.DrawSelTransmission()
        return

     
    def SetMolecule(self, Molecule):
        self.Mol = Molecule
        self.UpdateMolecule()
        
    def UpdateMolecule (self):
        self.Mol.CreateHam()
        self.Mol.CreateOverlap()
        self.Mol.CreateV()
        self.ChangeMolecule ()
        self.ChangeMoleculeOrbitals ()
        self.DrawMolecule ()
        return self.UpdateHamExt ()
        

    def UpdateConsistency(self, label):
        self.Consistency = label
        print "Consistency set to:", self.Consistency
        return self.UpdateHamExt ()     
       
    def UpdateG (self, val):
        print "Interaction strengths set to:", self.sGleft.val, self.sGright.val
        self.Mol.SetG (self.sGleft.val, self.sGright.val)
        return self.UpdateHamExt ()
    
    def UpdateBias(self, bias):
        self.Bias = bias
        print "Bias voltage set to: ", self.Bias, "V"
        return self.UpdateHamExt ()

    def UpdateHamExt (self):
        self.Mol.CreateHamExt (self.Bias, self.Consistency)
        self.Mol.CalcGamma()
        self.Mol.Density(self.Bias)
        self.Mol.Transmission()
        self.Mol.Current(self.Bias)
        self.Mol.CalcDOS()
        
        self.DrawLocalDensity ()
        self.DrawBias ()
        self.DrawTransmission ()
        self.DrawDOS ()
        self.DrawCurrent ()
        self.DrawOrbitals ()
        return self.UpdateSelection()

    def UpdateGate (self, gate):
        self.Gate = gate
        print "Gates voltage set to: ", self.Gate, "V"
        self.OrbitalSel = None
        self.AtomSel    = None
        return self.UpdateSelection()

    def UpdateAtomSel(self, iAtom):
        self.AtomSel = iAtom
        if self.AtomSel == None:
            print "No atom selected"
            self.axMol.set_title('No atom selected')
            self.OrbitalSel = None
        elif isinstance(iAtom, int):
            print "Selected atom", self.Mol.Atom[self.AtomSel][0], "at", self.AtomSel, " Local density = ", self.Mol.LD[self.AtomSel, self.AtomSel]
            self.axMol.set_title('Selected atom: %c at %d. Density = %f'%(self.Mol.Atom[self.AtomSel][0],self.AtomSel, self.Mol.LD[self.AtomSel, self.AtomSel]))
            Orbitals = []
            for i in range(self.Mol.N):
                Orbitals.append(np.real(self.Mol.eigvec[i][self.AtomSel]*np.conjugate(self.Mol.eigvec[i][self.AtomSel])))
            self.OrbitalSel = Orbitals
        return self.UpdateSelection()
        
    def UpdateOrbitalSel(self, iOrbital):
        self.OrbitalSel = iOrbital
        
        if isinstance(self.OrbitalSel, int):
            print "Orbital set to:", self.OrbitalSel, "with energy", self.Mol.e_arr[self.OrbitalSel], "eV"
            self.AtomSel    = self.Mol.eigvec[iOrbital]
            self.Gate       = self.Mol.e_arr[self.OrbitalSel]
        return self.UpdateSelection()

    def UpdateSelection (self):
        self.DrawLocalCurrents ()
        self.DrawGate()
        self.DrawIVCurve()
        self.DrawSelAtom()
        self.DrawSelOrbitals()
        self.DrawSelTransmission()
        return

    def RunSequence (self):
        self.fig.set_size_inches(18.5, 13.5) #default 18.5, 10.5
        
        N=100
        for i in range(N):
            e = self.Mol.Gates[0]+(self.Mol.Gates[-1]-self.Mol.Gates[0])/N*i
            self.UpdateGate(e)            
            self.fig.savefig('Output/PN/Armchair 7,21, seq ' + str(i) + ' Energy=' + str(math.ceil(e*100)/100) + 'eV.png', dpi=self.fig.dpi)
            print e
Ejemplo n.º 57
0
    for i in iterHulls:
        for j in iterHulls[i]:
            if j.get_visible():
                legLine.append(j)
                legLabel.append(j.get_label())

    font=FontProperties(size='small')
    if (len(legLine) > 0):
        ax.legend(legLine, legLabel, loc=options.lpos, shadow=True, prop=font)
    else:
        ax.legend(("",),loc=options.lpos, shadow=True, prop=font)
    plt.draw()

if not options.outfile:
    rax = plt.axes([0.05, 0.15, 0.15, 0.6])
    check = CheckButtons(rax, ['scatter', 'all', 'config'] + itervars.keys(), (scatterPoints.get_visible(), allHull.get_visible(), options.configs) + tuple(itervarsenabled.values()))
    check.on_clicked(toggleHullVisibility)

toggleHullVisibility("")
if options.zoom:
    limits = options.zoom.split(",");
    if len(limits) != 4:
        print "-z parameter needs 4 comma-seperated float values!"
        exit(-1)
    ax.set_xlim(float(limits[0]), float(limits[1]))
    ax.set_ylim(float(limits[2]), float(limits[3]))

plt.show()

if options.outfile:
#    fig.savefig(options.outfile)
Ejemplo n.º 58
0
def plot_clusters_in_brain(bn,background,cluster_list,actives=[True,False,False]):
  if len(cluster_list)<3:
    print 'just '+str(len(cluster_list))+ ' cluster'
  colors=[[1,0,0],[0,1,0],[0,0,1]]  
  node2voxel=bn.get_node2voxel()
  img=nib.load(bn.mask)
  imgB = nib.load(background)
  D=img.get_data()
  sh=D.shape
  A=bn.affine
  aspect1=abs(A[2,2]/A[0,0])
  aspect2=abs(A[2,2]/A[1,1])
  aspect3=abs(A[1,1]/A[0,0])
  M=pylab.zeros((sh[0],sh[1],sh[2],3))
  B=M
  B0=imgB.get_data().astype(numpy.float32, copy=False) 
  #B0img.get_data().astype(numpy.float32, copy=False)
  B[:,:,:,0]=(B0-B0.min())/(B0.max()-B0.min())
  B[:,:,:,1]=B[:,:,:,0]
  B[:,:,:,2]=B[:,:,:,0]
  M=B  
  #M[D>0,:]=pylab.ones_like(M[D>0,:])
  for ii in range(len(actives)):
    if actives[ii]:
      if len(cluster_list)>ii:
        for node in cluster_list[ii]:
          (i,j,k)=node2voxel[str(node)]
          M[i,j,k,:]=[B[i,j,k,l]*colors[ii][l] for l in range(3)]
  plt.figure()
  plt.subplot(221)
  j0 = round(M.shape[1]*0.5)
  lj = plt.imshow(M[:,j0,:,:].swapaxes(0,1),interpolation='None',aspect=aspect1)
  plt.axis([0, sh[0], 0, sh[2]])
  plt.subplot(222)
  i0 = round(M.shape[0]*0.5)
  li = plt.imshow(M[i0,:,:,:].swapaxes(0,1),interpolation='None',aspect=aspect2)
  plt.axis([0, sh[1], 0, sh[2]])
  plt.subplot(223)
  k0 = round(M.shape[2]*0.5)
  lk = plt.imshow(M[:,:,k0,:].swapaxes(0,1),interpolation='None',aspect=aspect3)
  plt.axis([0, sh[0], 0, sh[1]])
  axcolor = 'lightgoldenrodyellow'
  axi = plt.axes([0.55, 0.3, 0.4, 0.03], axisbg=axcolor)
  axj = plt.axes([0.55, 0.2, 0.4, 0.03], axisbg=axcolor)
  axk = plt.axes([0.55, 0.1, 0.4, 0.03], axisbg=axcolor)
  si = Slider(axi, 'i', 0, sh[0]-1, valinit=i0,valfmt='%i')
  sj = Slider(axj, 'j', 0, sh[1]-1, valinit=j0,valfmt='%i')
  sk = Slider(axk, 'k', 0, sh[2]-1, valinit=k0,valfmt='%i')
  def update(val):
    i = int(si.val)
    j = int(sj.val)
    k = int(sk.val)
    lj.set_data(M[:,j,:,:].swapaxes(0,1))
    li.set_data(M[i,:,:,:].swapaxes(0,1))
    lk.set_data(M[:,:,k,:].swapaxes(0,1))
    plt.draw()
  si.on_changed(update)
  sj.on_changed(update)
  sk.on_changed(update)
  rax = plt.axes([0.025, 0.5, 0.1, 0.15], axisbg=axcolor)
  check = CheckButtons(rax, ('0', '1', '2'), actives=actives)

  def showcluster(label):
    i0=int(si.val)
    j0=int(sj.val)
    k0=int(sk.val)
    M=B
    for node in cluster_list[int(label)]:
      (i,j,k)=node2voxel[str(node)]
      if all(M[i,j,k,:]==colors[int(label)]):
        M[i,j,k,:]=[1,1,1]
      else:
        M[i,j,k,:]=colors[int(label)]
    lj.set_data(M[:,j0,:,:].swapaxes(0,1))
    li.set_data(M[i0,:,:,:].swapaxes(0,1))
    lk.set_data(M[:,:,k0,:].swapaxes(0,1))
    plt.draw()
  check.on_clicked(showcluster)
  return
Ejemplo n.º 59
0
class CBox(object):
    """Custom checkbox."""
    
    def __init__(self, fig, rect, labels, act=None, func=None, fargs=None):
        """init function

        Parameters:
            fig: a matplotlib.figure.Figure instance
            rect: [left, bottom, width, height]
                each of which in 0-to-1-fraction i.e. 0<=x<=1
            labels: array of strings
                labels to be checked
            act: a len(labels) array of booleans, optional, default: None
                indicating whether the label is active at first
                if None, all labels are inactive
            func: function, optional, default: None
                if not None, function called when checkbox status changes
            fargs: array, optional, default: None
                (optional) arguments for func
        """
        self.fig = fig
        self._rect = rect
        self._func = func
        self._fargs = fargs
        self._labels = labels
        self.axes = self.fig.add_axes(rect)
        self.axes.set_axis_bgcolor('1.00')
        inac = act if act is not None else (False,) * len(labels)
        self.cb = CheckButtons(self.axes, self._labels, inac)
        self.cb.on_clicked(self._onchange)

    def _onchange(self,label):
        """Actual function called when checkbox status changes."""
        if self.get_visible():
            if self._func is not None:
                if self._fargs is not None:
                    self._func(*self._fargs)
                else:
                    self._func()
            self.fig.canvas.draw()

    def get_status(self):
        """Get checkbox status.

        Returns: status
            status: list of booleans
                a len(labels) list of booleans indicating whether
                    label is active
                    
        NB: checkbox status changes even when it's not visible
            if a click hits the checkbox!
        """
        stat = []
        for i in self.cb.lines:
            stat.append(i[0].get_visible() or i[1].get_visible())
        return stat
        
    def set_visible(self,b):
        """Set its visibility.

        Parameters:
            b: boolean
        """
        self.axes.set_visible(b)

    def get_visible(self):
        """Get its visibility.

        Returns: b
            b: boolean
        """
        return self.axes.get_visible()