Ejemplo n.º 1
0
 def build(self):
     global fig, ax, textinput1, textinput2, textinput3, textinput4, canvas
     fig,ax = plt.subplots(1)
     plt.imshow(img)
     box = BoxLayout()
     canvas = FigureCanvas(figure = fig)
     box.add_widget(canvas)
     fig.canvas.mpl_connect('button_press_event', onclick)
     # some widgets
     textinput1 = TextInput(text = "x1", multiline = False, size_hint = (0.7, None), height = 60)
     textinput1.bind(on_text_validate = on_enter)
     textinput2 = TextInput(text = "y1", multiline = False, size_hint = (0.7, None), height = 60)
     textinput2.bind(on_text_validate = on_enter)
     textinput3 = TextInput(text = "x2", multiline = False, size_hint = (0.7, None), height = 60)
     textinput3.bind(on_text_validate = on_enter)
     textinput4 = TextInput(text = "y2", multiline = False, size_hint = (0.7, None), height = 60)
     textinput4.bind(on_text_validate = on_enter)
     box.add_widget(textinput1)
     box.add_widget(textinput2)
     box.add_widget(textinput3)
     box.add_widget(textinput4)
     button1 = Button(text = 'update', size_hint = (0.7, None), height = 60)
     box.add_widget(button1)
     button1.bind(on_press = updateGraph)
     button2 = Button(text = 'recover', size_hint = (0.7, None), height = 60)
     box.add_widget(button2)
     button2.bind(on_press = recoverGraph)
     canvas.draw()
     return box
 def initializePlots(self):
     for m in range(0, 10):
         muscle = plt.figure(facecolor=(0.3, 0.3, 0.3))
         plt.subplots_adjust(top=0.85, bottom=0.1, left=0.1, right=0.9)
         ax = muscle.add_subplot(1, 1, 1)
         ax.spines['bottom'].set_color('white')
         ax.spines['top'].set_color('white')
         ax.spines['left'].set_color('white')
         ax.spines['right'].set_color('white')
         ax.tick_params(length=0,
                        color='white',
                        labelsize=8,
                        labelcolor='white')
         ax.set_title("Trigno Sensor " + str(m + 1), color='white')
         ax.set_xlim([0, self.timescale * 2000])
         ax.set_ylim([-0.1, 0.1])
         ax.set_facecolor((0.3, 0.3, 0.3))
         ax.set_xticks([])
         ax.set_yticks([])
         ax.set_xticklabels([])
         ax.set_yticklabels([])
         ax.plot([], linewidth=1)[0]
         muscle_handle = FigureCanvas(muscle)
         muscle_handle.blit()
         self.add_widget(muscle_handle)
         self.plotHandle.append(muscle_handle)
Ejemplo n.º 3
0
    def __init__(self, rec = None, **kwargs):
        #--------------- UI Constuctions ---------------------
        super(RootWidget, self).__init__(**kwargs)
        # Set up the widgets orientations
        self.padding = 10
        self.orientation = 'vertical'
        
        # Play the recorder
        self.rec = rec
        self.rec.stream_init(playback = True)
        self.playing = True

        # Set up the plot canvas
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.set_ylim(-5e4,5e4)
        self.line = ax.plot(range(len(self.rec.signal_data)),
                            self.rec.signal_data)[0]
        self.canvas_widget = FigureCanvas(fig)
        self.add_widget(self.canvas_widget)

        # Set up the button
        btn = Button(text='Switch')
        btn.bind(on_press = self.toggle_rec)
        self.add_widget(btn)
        btn.size_hint_y = 0.1

        # Set up live update plot
        event = Clock.schedule_interval(self.update_line, 1 / 60.)
Ejemplo n.º 4
0
 def __init__(self, ch_id, plot_info, show=False, label='Noname', **kwargs):
     self.ch_id = ch_id
     self.show = show
     self.label = label
     self.fig = plt.figure()
     self.wid = FigureCanvas(self.fig)
     self.ax = self.fig.add_subplot(111, **kwargs)
     self.line = self.ax.plot(range(100), [1 / 2] * 100, label=self.label)[0]
     self.ax.set_xlabel(plot_info.xlabel)
     self.ax.set_ylabel(plot_info.ylabel)
     self.ax.legend()
     self.ax.grid(True)
     self.carrier_ch_n = int(ch_id[1]) if int(ch_id[0]) < 2 else None
     self.plot_info = plot_info
     self._old_results = []
Ejemplo n.º 5
0
    def display_graph(self):
        #read data from firebase
        self.data = db.child('chickenrice').child(
            'end_of_day_sales').get().val()

        #data processing - data looks like Ordereddict((name, [list of food]), (name, [list of food]))
        #delete all placeholders from self.data
        del self.data['0']
        del self.data['Placeholder']
        g = []
        #extract all items from self.data and plug into list g
        for key, val in self.data.items():
            for element in val:
                g.append(element)
#plot graph
#instantiate plot
        fig, ax = plt.subplots()
        bar_graph = FigureCanvas(fig)
        #s is a list with only 1 of every item (no duplicates) used as the x axis of bar plot
        s = list(set(g))
        #counts of each element in s
        counts = []
        for i in range(len(s)):
            counts.append(g.count(s[i]))
        ax.bar(s, counts)
        #add the graph into box layout with id bargraph
        self.ids.bargraph.add_widget(bar_graph)
Ejemplo n.º 6
0
    def do_action(self):

        StaticVars.btn1 = self.ids.btnTerminal
        StaticVars.btn1.text = 'hello?'
        StaticVars.btn1.bind(on_press=callback)

        self.btnMenu = self.ids.btnMenu
        self.btnMenu.bind(on_press=callback2)

        self.ids.wordCloudBtn.text = '42'

        fl = self.ids.wordCloudPlot
        fl.clear_widgets()
        btn = Button()

        wCanavas = canvas
        # wCanvas2 = canvas2
        wCanavas.size = (3000, 3000)
        # wCanvas2.size = (3000, 3000)
        # wCanavas.size_hint = (0.1, 0.1)
        # fl.add_widget(wCanavas)
        fl.add_widget(FigureCanvas(fig))
        # fl.add_widget(wCanvas2)

        # fl.add_widget(btn)
        fl.add_widget(self.get_fc(1))
        fl.add_widget(self.get_fc(2))
        # fl.add_widget(canvas)

        #self.ids.myBox.orientation = 'horizontal'

        # pass
        print('hello World')
Ejemplo n.º 7
0
    def updateChart(self, clock=0):
        print(Global.array.shape)
        if Global.array.shape[0] <= 1:
            label = Label(text='Nicht genug Daten')
            self.my_box.clear_widgets()
            self.my_box.add_widget(label)
            return

        #self.data, self.X, self.Y = sqlPort.getValuesBySurface(self.time)
        self.data = np.sum(Global.array, 2) / Global.config["ybounds"]
        print(self.data)

        fig, ax = plt.subplots(facecolor='black')

        my_mpl_kivy_widget = FigureCanvas(fig)

        ax.set_xlabel('x', fontsize=15)
        ax.set_ylabel('y', fontsize=15)

        #CS = ax.contourf(self.X, self.Y, self.data)
        CS = ax.contourf(self.data)
        cbar = plt.colorbar(CS)

        cbar.set_label('amplidtude')

        nav2 = NavigationToolbar2Kivy(my_mpl_kivy_widget)

        self.my_box.clear_widgets()
        self.my_box.add_widget(nav2.actionbar)
        self.my_box.add_widget(my_mpl_kivy_widget)
Ejemplo n.º 8
0
 def get_graph(self, crypto):
     plt.clf()
     fig, ax = plt.subplots(figsize=(10, 5), dpi=400, facecolor='black')
     ax.set_facecolor('black')
     fig.subplots_adjust(left=0.01, top=1.00, right=1.00, bottom=0.01)
     self.graph_data = parser42.get_histodata(crypto)
     candlestick_ohlc(ax, self.graph_data, colorup='g')
     return FigureCanvas(fig)
Ejemplo n.º 9
0
 def get_fc(self, i):
     fig1 = plt.figure()
     fig1.suptitle('mouse hover over figure or axes to trigger events' +
                   str(i))
     ax1 = fig1.add_subplot(211)
     ax2 = fig1.add_subplot(212)
     wid = FigureCanvas(fig1)
     return wid
Ejemplo n.º 10
0
 def post_prep_plot(self, x_data, yscale, has_yunit):
     self.set_axes_xdata(x_data)
     self.set_axes_ylim(yscale)
     self.set_axes_yunit(has_yunit)
     self.fig.canvas.figure.patch.set_facecolor('white')
     self.add_widget(FigureCanvas(self.fig))
     c1 = self.fig.canvas.mpl_connect('figure_enter_event', self.enter_fig)
     c2 = self.fig.canvas.mpl_connect('figure_leave_event', self.leave_fig)
     self._cids.extend([c1, c2])
Ejemplo n.º 11
0
    def get_fc(self, i):
        #print plt.style.available
        with plt.style.context(('dark_background')):
            figure = plt.figure()

            figure.suptitle(
                'mouse hover over figure or axes to trigger events' + str(i))
            ax1 = figure.add_subplot(211)
            ax2 = figure.add_subplot(212)
            wid = FigureCanvas(figure)
            self.add_bindings(figure)
        return wid
Ejemplo n.º 12
0
    def on_enter(self, *args):
        self.plot.clear_widgets()
        password, name, created = db.get_user(self.current)
        self.n.text = "Account Name: " + name
        self.email.text = "Email: " + self.current
        self.created.text = "Created On: " + created
        x = np.random.rand(100)
        fig, ax = plt.subplots()
        ax.hist(x)
        canvas = FigureCanvas(figure=fig)

        self.plot.add_widget(canvas)
Ejemplo n.º 13
0
 def get_fc(self, i):
     fig1 = plt.figure()
     fig1.suptitle('mouse hover over figure or axes to trigger events' +
                   str(i))
     ax1 = fig1.add_subplot(211)
     ax2 = fig1.add_subplot(212)
     wid = FigureCanvas(fig1)
     fig1.canvas.mpl_connect('figure_enter_event', enter_figure)
     fig1.canvas.mpl_connect('figure_leave_event', leave_figure)
     fig1.canvas.mpl_connect('axes_enter_event', enter_axes)
     fig1.canvas.mpl_connect('axes_leave_event', leave_axes)
     return wid
Ejemplo n.º 14
0
 def make_plot(self):
     muscle = plt.figure(facecolor=(0.3, 0.3, 0.3))
     plt.subplots_adjust(top=0.99, bottom=0.01, left=0.05, right=0.95)
     ax = muscle.add_subplot(1, 1, 1)
     ax.spines['bottom'].set_color('white')
     ax.spines['top'].set_color('white')
     ax.spines['left'].set_color('white')
     ax.spines['right'].set_color('white')
     ax.tick_params(length=0,
                    color='white',
                    labelsize=8,
                    labelcolor='white')
     ax.set_facecolor((0.3, 0.3, 0.3))
     ax.set_xticks([])
     ax.set_yticks([])
     ax.set_xticklabels([])
     ax.set_yticklabels([])
     ax.plot([], linewidth=1)[0]
     ax.plot([], linewidth=1)[0]
     muscle_handle = FigureCanvas(muscle)
     muscle_handle.blit()
     self.add_widget(muscle_handle)
     self.muscle_handle = muscle_handle
Ejemplo n.º 15
0
    def get_fc(self, i):
        """
        Build the figure and connect events to the canvas
        """
        fig1 = plt.figure(facecolor=[0.2, 0.2, 0.2])
        fig1.suptitle('mouse hover over figure or axes to trigger events' +
                      str(i))
        ax1 = fig1.add_subplot(1, 1, 1, axisbg=[0.17, 0.17, 0.17])
        wid = FigureCanvas(fig1)
        fig1.canvas.mpl_connect('figure_enter_event', enter_figure)
        fig1.canvas.mpl_connect('figure_leave_event', leave_figure)
        fig1.canvas.mpl_connect('axes_enter_event', enter_axes)
        fig1.canvas.mpl_connect('axes_leave_event', leave_axes)

        return wid, ax1  #, fig1
Ejemplo n.º 16
0
    def get_spectrogram(self, x, fs):
        #print plt.style.available
        with plt.style.context(('dark_background')):
            figure = plt.figure()
            #figure.set_facecolor('gray')
            #figure.patch.set_alpha(0.3)

            # Compute and plot the spectrogram.
            f, t, Sxx = signal.spectrogram(x, fs)
            plt.ylabel('Frequency [Hz]')
            plt.xlabel('Time [sec]')
            plt.pcolormesh(t, f, Sxx)
            plt.show()
            wid = FigureCanvas(figure)
            self.add_bindings(figure)
        return wid
Ejemplo n.º 17
0
    def get_fc(self, i):
        """
        Build the figure. Adds two axes for flow data and
        SpO2 data.
        """
        fig = plt.figure()
        ax1 = fig.add_subplot(1, 1, 1)
        ax2 = ax1.twinx()

        #fig.text(1, 0.5, 'SpO2', ha = 'center', va = 'center')
        #fig.text(0.5, 0.04, 'Time', ha = 'center', va = 'center')
        ax1.set_ylabel('Flow Data')
        ax2.set_ylabel(r'SpO$_2$')
        wid = FigureCanvas(fig)

        # fig.canvas.mpl_connect('axes_enter_event', enter_axes)
        return wid, ax1, ax2
Ejemplo n.º 18
0
    def get_fc(self, i):
        hfmt = dates.DateFormatter(
            '%H:%M')  #usa matplotlib.dates para formatar o eixo com as datas

        fig1 = plt.figure()  #figura normal do matplotlib
        fig1.suptitle('temperatura interna ')
        #ax1 = fig1.add_subplot(211)
        #ax2 = fig1.add_subplot(212)
        ax = fig1.add_subplot(111)
        datas, temps = dados_para_grafico.fetch_intern_temp()
        ax.plot_date(datas, temps)
        ax.xaxis.set_major_formatter(hfmt)
        plt.setp(ax.get_xticklabels(), rotation=30)

        wid = FigureCanvas(
            fig1)  #acho que é aqui que a mágica do kivy.garden acontece

        return wid
Ejemplo n.º 19
0
    def updateChart(self, clock=0):
        start_time = time.time()
        self.getPosPara()
        self.updateLabel()
        plt.figure(1)

        print(self.X, self.Y)

        self.data = Global.array[self.Y, self.X]

        fig, ax = plt.subplots(facecolor='black')

        my_mpl_kivy_widget = FigureCanvas(fig)

        ax.set_xlabel('time in 14/1024 \u03BCs', fontsize=15)
        ax.set_ylabel('amplitude', fontsize=15)

        print("Here1", time.time() - start_time)
        start_time = time.time()

        major_ticks_x = np.arange(0, 1020, 100)
        major_ticks_y = np.arange(0, 1020, 100)
        minor_ticks = np.arange(0, 1020, 10)

        print("Here2", time.time() - start_time)
        start_time = time.time()

        ax.set_xticks(major_ticks_x)
        #ax.set_xticks(minor_ticks, minor=True)
        ax.set_yticks(major_ticks_y)
        #ax.set_yticks(minor_ticks, minor=True)
        print("Here3", time.time() - start_time)
        start_time = time.time()

        ax.grid()

        CS = ax.plot(self.data)

        nav1 = NavigationToolbar2Kivy(my_mpl_kivy_widget)

        self.my_box.clear_widgets()
        self.my_box.add_widget(nav1.actionbar)
        self.my_box.add_widget(my_mpl_kivy_widget)
Ejemplo n.º 20
0
    def updateChart(self, clock=0):

        self.data, self.X, self.Y = sqlPort.getValuesBySurfaceTest()

        fig, ax = plt.subplots(facecolor='black')

        my_mpl_kivy_widget = FigureCanvas(fig)

        ax.set_xlabel('x', fontsize=15)
        ax.set_ylabel('y', fontsize=15)

        CS = ax.contourf(self.X, self.Y, self.data)
        cbar = plt.colorbar(CS)

        cbar.set_label('amplidtude')

        nav2 = NavigationToolbar2Kivy(my_mpl_kivy_widget)

        self.my_box.clear_widgets()
        self.my_box.add_widget(nav2.actionbar)
        self.my_box.add_widget(my_mpl_kivy_widget)
Ejemplo n.º 21
0
    def draw_my_plot(self):
        self.figure_1 = Figure(figsize=(2, 2))
        self.figure_1.subplots_adjust(left=0.13, right=0.93, bottom=0.25,
                                      top=0.98)  # to expand and occupy full area around imshow
        #self.panel_col = (1,0,0)
        self.x_vals = np.arange(0, 10, 0.01)
        self.y_vals = np.zeros(len(self.x_vals))
        #self.figure_1.set_facecolor(self.rgb_to_hex(self.panel_col))
        self.axes = self.figure_1.add_subplot(111)
        self.canvas_speech = FigureCanvas(self.figure_1)
        self.axes.set_xlim(0, 10)
        self.axes.set_ylim(-1, 1)


        #self.axes.set_facecolor(self.rgb_to_hex(self.panel_col))
        self.axes.grid(True, color='lightgray')
        #self.axes.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
        self.axes.set_xlabel('Time (s)', fontsize=10, labelpad=0)
        self.axes.set_ylabel('Signal (norm)', fontsize=10, labelpad=0)
        self.line11, = self.axes.plot(self.x_vals, self.y_vals, "b", linewidth=0.5)



        self.axes.plot(self.x_vals, self.y_vals, "b", linewidth=0.5)
        self.canvas_speech.draw_idle()
        #self.canvas_speech.Refresh()

        # Draw 2 line on speech graph
        self.line_a = lines.Line2D((0.25, 0.25), (-1, 1), picker=5, color="r", linewidth=2)
        self.line_b = lines.Line2D((9.75, 9.75), (-1, 1), picker=5, color="r", linewidth=2)
        self.a_point = 0.25
        self.b_point = 9.75
        self.draggable_line_a(self.line_a, self.axes)
        self.draggable_line_b(self.line_b, self.axes)

        self.axes.add_line(self.line_a)
        self.axes.add_line(self.line_b)


        self.add_widget(self.canvas_speech, 1) #<==== This adds a graph above the first row (index=1)
Ejemplo n.º 22
0
    def init_plots(self):
        fig = plt.figure(facecolor=(0.3, 0.3, 0.3))
        plt.subplots_adjust(left=0.05, right=0.98, wspace=0.2)
        for side_i in range(0, len(self.sides)):  ## side_i, get it?
            ax = fig.add_subplot(1, 3, side_i + 1)
            ax.spines['bottom'].set_color('white')
            ax.spines['top'].set_color('white')
            ax.spines['left'].set_color('white')
            ax.spines['right'].set_color('white')
            ax.tick_params(length=0,
                           color='white',
                           labelsize=8,
                           labelcolor='white')
            ax.set_title(self.sides[side_i] + ' Recruitment Curve',
                         color='w',
                         pad=2)
            ax.set_facecolor((0.3, 0.3, 0.3))
            ax.set_xticks([])  #np.arange(0, 10000, 1000))
            ax.set_yticks([])  #np.arange(0, 10000, 1000))
            for m in self.muscles:
                ax.plot([], '.', label=m)
            leg = ax.legend(self.muscles,
                            facecolor=(0.3, 0.3, 0.3),
                            edgecolor='white')
            plt.setp(leg.get_texts(), color='white')

        pulse_ax = fig.add_subplot(1, 3, 3)
        pulse_ax.spines['bottom'].set_color('white')
        pulse_ax.spines['top'].set_color('white')
        pulse_ax.spines['left'].set_color('white')
        pulse_ax.spines['right'].set_color('white')
        pulse_ax.tick_params(length=0,
                             color='white',
                             labelsize=8,
                             labelcolor='white')
        pulse_ax.set_title('EMG Stim Pulses', color='w', pad=2)
        pulse_ax.set_facecolor((0.3, 0.3, 0.3))
        pulse_ax.set_xticks([])
        pulse_ax.set_yticks([])
        for i in range(0, NUM_PLOT_PULSES):
            pulse_ax.plot([], '-', linewidth=1, color="#0471A6")
        pulse_ax.plot([], '-', linewidth=1, color="#FB3640")
        fig_handle = FigureCanvas(fig)
        fig_handle.blit()
        fig_handle.draw()
        self.add_widget(fig_handle)
        self.recruitmentHandle = fig_handle
Ejemplo n.º 23
0
    def draw_plot(self, data):
        x_axis = data[1]
        y_axis = data[0]

        plt.close()
        indy = np.arange(len(y_axis))
        indx = [i for i in range(0, len(x_axis), 4)]
        colors = []
        for y in y_axis:
            if y < .2:
                colors.append('green')
            else:
                colors.append('red')

        plt.bar(indy, y_axis, color=colors)
        plt.xticks(indx, [int(x_axis[i]) for i in range(0, len(x_axis), 4)],
                   size=8)
        plt.ylim(min(y_axis), 1.1 * max(y_axis))
        plt.grid(True, which='both', axis='y')
        plt.xlabel('czas od rozpoczęcia picia [h]')
        plt.ylabel('zawartość alkoholu we krwi [promil]')

        return FigureCanvas(plt.gcf())
Ejemplo n.º 24
0
    def updateChart(self, clock):
        plt.figure(1)

        self.Y = np.arange(0, Global.config["scans"])
        self.X = np.arange(0, Global.config["ybounds"])
        self.data = Global.array[self.numberOfLine]

        fig, ax = plt.subplots(facecolor='black')

        my_mpl_kivy_widget = FigureCanvas(fig)

        ax.set_xlabel('x', fontsize=15)
        ax.set_ylabel('time', fontsize=15)

        CS = ax.contourf(np.transpose(self.data))
        cbar = plt.colorbar(CS)

        cbar.set_label('amplidtude')

        nav1 = NavigationToolbar2Kivy(my_mpl_kivy_widget)

        self.my_box.clear_widgets()
        self.my_box.add_widget(nav1.actionbar)
        self.my_box.add_widget(my_mpl_kivy_widget)
Ejemplo n.º 25
0
 def new_canvas(self):
     with plt.style.context(('dark_background')):
         figure, ax = plt.subplots(2, 1, sharex=True)
         plt.subplots_adjust(hspace=.0)
         wid = FigureCanvas(figure)
     return wid
Ejemplo n.º 26
0
    def run_sumulation(self):
        for t in range(1, self.num_timesteps):
            # sample n[t]
            self.n[t] = np.random.multivariate_normal(self.mean, self.cov, 1)
            self.ns[t] = np.random.multivariate_normal(self.mean, self.cov, 1)

            # update s_bar (i.e "observe" s_bar)
            self.s_bar[t] = (np.sqrt(1 - self.ro**2) * self.s_bar[t - 1] +
                             self.ro * self.ns[t].reshape(-1, 1))

            # Make s_ta
            self.s_ta[t] = np.array([
                self.s_bar[t][:self.num_sbar_feats]
                for i in range(self.num_actions)
            ])

            # update eta_bar
            self.eta_bar[t] = (np.sqrt(1 - self.ro**2) * self.eta_bar[t - 1] +
                               self.ro * self.n[t].reshape(-1, 1))

            # Sample theta_prime
            theta_prime = np.random.multivariate_normal(
                self.theta_hat, self.nu**2 * np.linalg.inv(self.B), 1)

            # Which action is optimal?
            opt_action_idx = np.argmax(
                (self.s_ta[t] * theta_prime.reshape(-1, 1)).sum(axis=1))

            # Prob of taking non-zero action
            cdf = norm.cdf(
                0,
                loc=sum((self.s_bar[t][:self.num_sbar_feats] *
                         self.theta_hat.reshape(-1, 1))),
                scale=sum((self.s_bar[t][:self.num_sbar_feats] * self.nu**2 *
                           np.diagonal(np.linalg.inv(self.B)).reshape(-1, 1))))
            self.pi[t] = float(max(self.pi_min, min(self.pi_max, cdf)))

            # Flip biased coin with prob pi[t]
            outcome = np.random.binomial(1, self.pi[t])

            if outcome:
                self.a[t] = opt_action_idx
                a_bar_indicator = 1
            else:
                self.a[t] = 0
                a_bar_indicator = 0
            # Optimal non-zero action
            self.s_ta_bar[t] = self.s_ta[t][opt_action_idx]

            s = np.linalg.norm(self.s_bar[t], 1)
            self.s_ls.append(s)
            if s > 0.8:
                state_indicator = 1
            else:
                state_indicator = 0

            # Simulated reward
            self.reward[t] = sum(
                np.array(self.CONST_THETA).reshape(1, -1) *
                np.concatenate(self.s_ta[t]).reshape(
                    1, -1))[0] + 2 * state_indicator + np.random.normal(0, 1)
            # Update b_hat, B, and theta_hat
            self.B = (self.B + self.pi[t] *
                      (1 - self.pi[t]) * self.s_ta_bar[t] * self.s_ta_bar[t])
            self.b_hat = (self.b_hat + np.concatenate(
                self.s_ta_bar[t] *
                (a_bar_indicator - self.pi[t]) * self.reward[t]))
            self.b_ls.append(self.b_hat)
            self.theta_hat = np.matmul(np.linalg.inv(self.B),
                                       self.b_hat).ravel()
            self.theta_ls.append(self.theta_hat)

        # print("theta_hat:".format(self.theta_hat))
        fig1 = plt.plot([
            np.linalg.norm(self.theta_ls[t] - self.theta_ls[t - 1], 1) /
            np.linalg.norm(self.theta_ls[t], 1)
            for t in range(1, self.num_timesteps - 1)
        ],
                        label='theta_hat')
        plt.title(
            'Norm of difference of adjacent theta_hat iterations by timestep t'
        )
        plt.xlabel('t')
        plt.ylabel('proportional difference of norms')

        fig2 = plt.plot([
            np.linalg.norm(self.b_ls[t] - self.b_ls[t - 1], 1) /
            np.linalg.norm(self.b_ls[t], 1)
            for t in range(1, self.num_timesteps - 1)
        ],
                        label='b_hat')
        plt.title(
            'Norm of difference of adjacent theta_hat & b_hat iterations by timestep t'
        )
        plt.xlabel('t')
        plt.ylabel('proportional difference of norms')

        plt.legend()
        # plt.figure()
        fig3 = plt.plot(self.pi, label='b_hat')
        plt.title('pi[t]')
        plt.xlabel('t')
        plt.ylabel('proportional difference of norms')

        box = BoxLayout()
        box.add_widget(FigureCanvas(plt.gcf()))
        # box.add_widget(FigureCanvas(plt.gcf()))
        # box.add_widget(FigureCanvas(plt.gcf()))

        return box
Ejemplo n.º 27
0
class GUIGraph:
    graphs = {}
    oscope_default_state = {
        'T': {
            'plot_type': 'T',
            'xlabel': 'Time [s]',
            'ylabel': 'ADC count',
            'xlim': [0, 0.01],
            'ylim': [-1., 1.],
            'autoscale': False,
            'ylog': False,
            'xlog': False
        },
        'F': {
            'plot_type': 'F',
            'xlabel': 'Frequency [Hz]',
            'ylabel': '[V/sqrt(Hz)]',
            'xlim': [0, 5e6],
            'ylim': [1e-11, 60000],
            'autoscale': True,
            'ylog': False,
            'xlog': False
        },
        'active_graphs': []
    }

    def __init__(self, ch_id, plot_info, show=False, label='Noname', **kwargs):
        self.ch_id = ch_id
        self.show = show
        self.label = label
        self.fig = plt.figure()
        self.wid = FigureCanvas(self.fig)
        self.ax = self.fig.add_subplot(111, **kwargs)
        self.line = self.ax.plot(range(100), [1 / 2] * 100,
                                 label=self.label)[0]
        self.ax.set_xlabel(plot_info.xlabel)
        self.ax.set_ylabel(plot_info.ylabel)
        self.ax.legend()
        self.ax.grid(True)
        self.carrier_ch_n = int(ch_id[1]) if int(ch_id[0]) < 2 else None
        self.plot_info = plot_info
        self._old_results = []

    def update_data(self):
        if self.ch_id not in carrier.results:
            # Logger.critical('No data found')
            return
        if carrier.results[self.ch_id] is self._old_results:
            return
        if self.plot_info.plot_type == 'T':
            x_data, y_data, y_max, ts = carrier.results[self.ch_id]
        elif self.plot_info.plot_type == 'F':
            x_data, y_data, xargmax, y_max = carrier.results[self.ch_id]
        self.line.set_xdata(x_data)
        self.line.set_ydata(y_data)
        self._old_results = carrier.results[self.ch_id]
        if not self.plot_info.autoscale:
            self.ax.set_xlim(self.plot_info.xlim)
            self.ax.set_ylim(self.plot_info.ylim)
        else:
            self.ax.relim()
            self.ax.autoscale()
        self.wid.draw()
        self.wid.flush_events()

    def set_plot_active(self, b):
        self.show = b

    @staticmethod
    def load_settings(settings_file='oscope_state.json'):
        try:
            with open(settings_file, 'r') as jf:
                oscope_state = json.load(jf)
        except IOError as e:
            Logger.warning(
                f'{e} occured while reading settings_file, loading default settings'
            )
            oscope_state = GUIGraph.oscope_default_state
        except json.JSONDecodeError as e:
            Logger.warning(
                f'{e} occured while reading settings_file, loading default settings'
            )
            oscope_state = GUIGraph.oscope_default_state
        return oscope_state

    @staticmethod
    def save_settings(settings_file='oscope_state.json'):
        GUIGraph.oscope_state['T'] = dataclasses.asdict(
            g_plot_type_limits['T'])
        GUIGraph.oscope_state['F'] = dataclasses.asdict(
            g_plot_type_limits['F'])
        GUIGraph.oscope_state['active_graphs'] = [
            g.ch_id for g in GUIGraph.graphs.values() if g.show
        ]
        try:
            with open(settings_file, 'w') as jf:
                json.dump(GUIGraph.oscope_state, jf)
        except IOError:
            Logger.warning('State of oscope couldn\'t be saved')

    @staticmethod
    def setup_gui_graphs(carrier):
        GUIGraph.oscope_state = GUIGraph.load_settings()
        # Load possible types of limits: For now T for time domain,
        #                                and F for frequency
        g_plot_type_limits['T'] = GUIGraphLimits(**GUIGraph.oscope_state['T'])
        g_plot_type_limits['F'] = GUIGraphLimits(**GUIGraph.oscope_state['F'])
        # Create 2 GUI graphs for each channel of data coming from the carrier
        # 2 graphs, 1 for T and 1 for F
        for i in range(carrier.n_channels):
            ch_id = "0" + str(i)
            GUIGraph.graphs[ch_id] = GUIGraph(
                ch_id,
                g_plot_type_limits['T'],
                show=ch_id in GUIGraph.oscope_state['active_graphs'],
                label='CH{}-TimeDomain'.format(i))
            ch_id = "1" + str(i)
            GUIGraph.graphs[ch_id] = GUIGraph(
                ch_id,
                g_plot_type_limits['F'],
                show=ch_id in GUIGraph.oscope_state['active_graphs'],
                label='CH{}-Frequency'.format(i))
        ch_id = "3"
        GUIGraph.graphs[ch_id] = GUIGraph(
            ch_id,
            g_plot_type_limits['F'],
            show=ch_id in GUIGraph.oscope_state['active_graphs'],
            label='CSD')