def __init__(self, parent, controller):
     tk.Frame.__init__(self, parent)
     f=Figure(figsize=(5, 5), dpi=100)
     a=f.add_subplot(111)
     x=range(len(df1['Actual']))
     t0, =a.plot(x, df1['Actual'], color="red", marker="o", linestyle="-")
     t1, =a.plot(x, df1['Predicted'], color="blue", marker="x", linestyle="-")
    
     a.set_ylabel('Solar power Generated in KW/H')
     a.set_xlabel('Hours')
     a.grid()
     f.legend((t0, t1), ('Actual', 'Predicted'), 'upper right')
     canvas=FigureCanvasTkAgg(f, self)
     canvas.draw()
     canvas.get_tk_widget().pack()
     toolbar=NavigationToolbar2Tk(canvas, self)
     toolbar.update()
     canvas._tkcanvas.pack()
     
     label=tk.Label(self, text=txt)
     label.pack()
     btn=tk.Button(self, text="Back", command=lambda : controller.show_frame(pageone))
     btn.pack()
     btn1=tk.Button(self, text='Go to Home', command=lambda : controller.show_frame(startpage))
     btn1.pack()
Ejemplo n.º 2
0
def history_graph(log, width, unit):
    dpi = 100
    figsize = (width / dpi, 0.3 * width / dpi)
    fg = '#cccccc'
    bg = '#000000'
    fig = Figure(figsize=figsize, dpi=dpi, facecolor=bg, frameon=False)

    taxis = fig.add_axes((0.08, 0.1, 0.68, 0.9), facecolor=bg)
    lines = []
    for sensor in log:
        lines.append(taxis.plot(log[sensor]['time'], log[sensor]['value']))
    taxis.set_ylabel('Temp (%s)' % unit, color=fg)
    taxis.xaxis.set_tick_params(color=fg, labelcolor=fg)
    taxis.yaxis.set_tick_params(color=fg, labelcolor=fg)

    formatter = taxis.xaxis.get_major_formatter()
    formatter.scaled[1. / 24] = '%-I%P'
    formatter.scaled[1.0] = '%e'
    formatter.scaled[30.] = '%b'
    formatter.scaled[365.] = '%Y'
    fig.legend(labels=log.keys())

    canvas = FigureCanvas(fig)
    output = io.BytesIO()
    canvas.print_png(output)
    return output
Ejemplo n.º 3
0
 def _mixing_layer_depth_timeseries(self):
     """Create a time series graph figure object of the mixing
     layer depth on the wind data date and the 6 days preceding it.
     """
     fig = Figure((8, 3), facecolor='white')
     ax = fig.add_subplot(1, 1, 1)
     ax.set_position((0.125, 0.1, 0.775, 0.75))
     predicate = np.logical_and(
         self.mixing_layer_depth['avg_forcing'].mpl_dates >
         date2num(self.config.data_date - datetime.timedelta(days=6)),
         self.mixing_layer_depth['avg_forcing'].mpl_dates <=
         date2num(self.config.data_date + datetime.timedelta(days=1)))
     mpl_dates = self.mixing_layer_depth['avg_forcing'].mpl_dates[predicate]
     dep_data = self.mixing_layer_depth['avg_forcing'].dep_data[predicate]
     ax.plot(mpl_dates, dep_data, color='magenta')
     ax.set_ylabel('Mixing Layer Depth [m]',
                   color='magenta',
                   size='x-small')
     # Add line to mark profile time
     profile_datetime = datetime.datetime.combine(self.config.data_date,
                                                  datetime.time(12))
     profile_datetime_line = ax.axvline(date2num(profile_datetime),
                                        color='black')
     ax.xaxis.set_major_locator(DayLocator())
     ax.xaxis.set_major_formatter(DateFormatter('%j\n%d-%b'))
     ax.xaxis.set_minor_locator(HourLocator(interval=6))
     for label in ax.get_xticklabels() + ax.get_yticklabels():
         label.set_size('x-small')
     ax.set_xlim((int(mpl_dates[0]), math.ceil(mpl_dates[-1])))
     ax.set_xlabel('Year-Day', size='x-small')
     fig.legend([profile_datetime_line], ['Profile Time'],
                loc='upper right',
                prop={'size': 'xx-small'})
     return fig
Ejemplo n.º 4
0
class MatplotlibWidget(FigureCanvas):

    def __init__(self, parent=None):
        super(MatplotlibWidget, self).__init__(Figure())
        #self.hide()
        self.setParent(parent)
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)

        self.ax = self.figure.add_subplot(111)
        self.ax.yaxis.grid(color='gray', linestyle='dashed')

    def add_plot_line(self, x, y):
        self.ax.plot(x, y, 'r')

    def add_legend(self, list):
        #list of strings like "X1 = blaghlbah"
        self.figure.legend([x for x in list], loc='upper left')

    def draw_graph(self):
        self.figure.draw()

    def show_graph(self):
        self.figure.show()

    def plot_bar_graph(self):
        pass
Ejemplo n.º 5
0
def RMP_RHT():
    if len(Frame2.winfo_children()) > 1:
        for i in range(len(Frame2.winfo_children()) - 1):
            Frame2.winfo_children()[1].destroy()
    #Rendement malhonnete pratique
    x = np.linspace(0, 0.5, 100)
    y = np.linspace(0, 0.5, 100)
    for i in range(len(y)):
        RT = simulation_selfish_mining(float(valider()[1]), x[i],
                                       float(valider()[2]))
        y[i] = (RT[0]) / (RT[1])
    #plt.plot(x,y)
    #Rendement honnete theorique
    x1 = np.linspace(0, 0.5, 100)
    y1 = np.linspace(0, 0.5, 100)
    for i in range(len(y1)):
        y1[i] = (x1[i] * 6.25) / 600
    fig = Figure(figsize=(6, 5), dpi=100)
    fig.add_subplot(111).plot(x, y, x1, y1)
    fig.legend(["Rendement malhonnete Pratique", "Rendement Honnete"])
    #fig.add_subplot(111).plot(x1,y1)
    canvas = FigureCanvasTkAgg(fig, master=Frame2)  # A tk.DrawingArea.
    canvas.draw()
    #canvas.get_tk_widget().grid(row=13,column=1)
    toolbar = NavigationToolbar2Tk(canvas, Frame2)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
Ejemplo n.º 6
0
def draw_labels(figure: Figure,
                axes: Axes,
                y_label: str,
                label_rotation=90,
                axes_position='bottom'):

    # text and text parameters
    xlabel_text = r'$incubation\ time\ \slash\ days$'
    ylabel_text = y_label

    ylabel_rotation = label_rotation

    is_bottom = True if ('bottom' in axes_position
                         or axes_position == 'single') else False
    # MRE notation,
    if is_bottom:
        MRE_notation_marks(axes)  # add arrows where MRE was applied

    # remove x axis from top and middle axes
    if not is_bottom:
        axes.get_xaxis().set_visible(False)

    # x label
    figure.text(0.5, 0.03, xlabel_text, ha='center')
    # y label
    figure.text(0.05, 0.5, ylabel_text, va='center', rotation=ylabel_rotation)

    # legend
    axes.get_lines()
    handles = axes.get_lines()
    labels = SOILS
    figure.legend(handles, labels, 'center right')
Ejemplo n.º 7
0
def create_kde_figure():
    # Draw Plot
    fig = Figure(figsize=(13, 10), dpi=80)
    axes = fig.add_subplot(111,
                           ylim=(0, 0.35),
                           title='Density Plot of City Mileage by n_Cylinders')
    sns.kdeplot(mpg_df.loc[mpg_df['cyl'] == 4, "cty"],
                shade=True,
                color="g",
                label="Cyl=4",
                alpha=.7,
                ax=axes)
    sns.kdeplot(mpg_df.loc[mpg_df['cyl'] == 5, "cty"],
                shade=True,
                color="deeppink",
                label="Cyl=5",
                alpha=.7,
                ax=axes)
    sns.kdeplot(mpg_df.loc[mpg_df['cyl'] == 6, "cty"],
                shade=True,
                color="dodgerblue",
                label="Cyl=6",
                alpha=.7,
                ax=axes)
    sns.kdeplot(mpg_df.loc[mpg_df['cyl'] == 8, "cty"],
                shade=True,
                color="orange",
                label="Cyl=8",
                alpha=.7,
                ax=axes)
    # Decoration
    fig.legend()
    return fig
Ejemplo n.º 8
0
def _wchbl_tunujuch(x, tzij, rubi, ochochibäl):
    fig = Figura()
    TelaFigura(fig)
    etajuch = fig.subplots(1, 2)

    etajuch[0].set_title('Jachonem')
    etajuch[1].set_title("Tunujuch'")

    def ruyaik_juch(tz, rb_tz=None):
        y = estad.gaussian_kde(tz)(x)
        etajuch[0].plot(x, y, 'b-', lw=2, alpha=0.6, label=rb_tz, color=None)
        etajuch[1].plot(tz)

    if isinstance(tzij, dict):
        for rb, tzj in tzij.items():
            ruyaik_juch(tzj, rb)
        fig.legend()

    else:
        ruyaik_juch(tz=tzij)

    fig.suptitle(rubi)
    rubi_wuj = 'wchbl_' + rubi + '.png'
    if len(ochochibäl) and not os.path.isdir(ochochibäl):
        os.makedirs(ochochibäl)
    fig.savefig(os.path.join(ochochibäl, rubi_wuj))
Ejemplo n.º 9
0
def add_unique_figure_legend(fig: Figure, axes: Axes) -> None:
    """Add a legend with unique elements sorted by label to a figure.

    The handles and labels are extracted from the ``axes``

    Parameters
    ----------
    fig : Figure
        Figure to add the legend to.
    axes : Axes
        Axes plotted on the figure.

    See Also
    --------
    plot_fit_overview
    """
    handles = []
    labels = []
    for ax in axes.flatten():
        ax_handles, ax_labels = ax.get_legend_handles_labels()
        handles += ax_handles
        labels += ax_labels
    unique = [(h, l) for i, (h, l) in enumerate(zip(handles, labels))
              if l not in labels[:i]]
    unique.sort(key=lambda entry: entry[1])
    fig.legend(*zip(*unique))
Ejemplo n.º 10
0
def create_dotbox_figure():
    sns.set_style("white")
    # Draw Plot
    fig = Figure(figsize=(13, 10), dpi=80)
    axes = fig.add_subplot(
        111, title="Box Plot of Highway Mileage by Vehicle Class")

    sns.boxplot(x='class', y='hwy', data=mpg_df, hue='cyl', ax=axes)
    sns.stripplot(x='class',
                  y='hwy',
                  data=mpg_df,
                  color='black',
                  size=3,
                  jitter=1,
                  ax=axes)

    for i in range(len(mpg_df['class'].unique()) - 1):
        axes.vlines(i + .5,
                    10,
                    45,
                    linestyles='solid',
                    colors='gray',
                    alpha=0.2)

    # Decoration
    fig.legend(title='Cylinders')
    return fig
Ejemplo n.º 11
0
def create_palive_figure(path, path_dates, sp_trans):
    red = '#B6324F'
    blue = '#176BA0'  # '#4580A9'
    lg = 'grey'

    fig = Figure(figsize=(8, 5))
    ax = fig.subplots()
    ax.plot(path_dates, path, c=blue, label='probability of being alive')
    ax.vlines(sp_trans['event_time'], 0, 1, colors=red, label='purchase events', linestyles='dashed')

    ax.set_xlabel('Time', color=lg, fontsize='large')
    ax.set_ylabel('probability of being alive', color=lg, fontsize='large')

    ax.xaxis.set_major_formatter(mdates.DateFormatter("%m-%d"))

    ax.tick_params(axis='x', length=5, colors=lg)
    ax.tick_params(axis='y', length=5, colors=lg)

    ax.spines['bottom'].set_color(lg)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_linewidth(.5)
    ax.spines['left'].set_linewidth(.5)
    ax.spines['left'].set_color(lg)
    ax.spines['bottom'].set_color(lg)

    fig.legend(edgecolor='w', labelcolor=lg, fontsize='large')

    buf = BytesIO()
    fig.savefig(buf, format="png")
    fig_data = base64.b64encode(buf.getbuffer()).decode("utf8")
    return fig_data
Ejemplo n.º 12
0
 def __init__(self, parent, controller):
     tk.Frame.__init__(self, parent)
     #setting up label for the graph
     Label(self, text="Displaying the Graph",
           font=('Arial Bold', 20)).pack()
     f = Figure(figsize=(5, 5), dpi=100)
     a = f.add_subplot(111)
     #plotting the x_values in the graph
     x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
     #Plotting the lines of the graph
     t0, = a.plot(x, [2, 3, 5, 2, 1, 9, 4, 2, 1, 3],
                  color="red",
                  marker="o",
                  linestyle="-")
     t1, = a.plot(x, [5, 5, 3, 2, 8, 1, 9, 3, 2, 1],
                  color="blue",
                  marker="x",
                  linestyle="-")
     #setting up labels for the graph
     a.set_ylabel('y_scattered')
     a.set_xlabel('x_scattered')
     a.grid()
     #creating the legends for the graph
     f.legend((t0, t1), ('line-1', 'line-2'), 'upper right')
     #creating the canvas for the graph
     canvas = FigureCanvasTkAgg(f, self)
     #drawing the canvas
     canvas.draw()
     canvas.get_tk_widget().pack()
     #creating the navigation tool bar for the graph using matplotlib
     toolbar = NavigationToolbar2Tk(canvas, self)
     toolbar.update()
     #packing the whole canvas with navigation tool bar and the graph diagram
     canvas._tkcanvas.pack()
Ejemplo n.º 13
0
def evolution_fallecidos():
    datamodel.updater(data)  # Call to update

    fig = Figure(figsize=(12, 7))

    ax = fig.add_subplot(1, 1, 1)

    xss = [str(i) for i in range(1, len(data.muertes_acc) + 1)]
    xs = range(0, len(data.muertes_acc))

    ax.plot(xss, data.muertes_acc, 'o-', label='Casos acumulados')
    ax.plot(xss, data.muertes, 'o-', label='Casos en el d铆a')

    for x, y in zip(xs, data.muertes_acc):
        label = "{}".format(y)

        ax.annotate(label, (x, y),
                    textcoords='offset points',
                    xytext=(0, 10),
                    ha='center')

    for x, y in zip(xs, data.muertes):
        label = "{}".format(y)

        ax.annotate(label, (x, y),
                    textcoords='offset points',
                    xytext=(0, -15),
                    ha='center')

    ax.set_title('Evoluci贸n de casos por d铆as (Fallecidos)', fontsize=15)
    fig.legend(frameon=True, fontsize=12)

    FigureCanvasAgg(fig).print_png('fallecidos.png')

    return send_file('fallecidos.png')
Ejemplo n.º 14
0
def RMT_RHT():
    if len(Frame2.winfo_children()) > 1:
        for i in range(len(Frame2.winfo_children()) - 1):
            Frame2.winfo_children()[1].destroy()

    #Rendement theorique en fonction de q
    x = np.linspace(0, 0.5, 100)
    y = np.linspace(0, 0.5, 100)
    for i in range(len(y)):
        y[i] = attacker_revenue_ratio(float(valider()[2]), float(valider()[4]),
                                      x[i])
    #Rendement honnete theorique en fonction de q
    x1 = np.linspace(0, 0.5, 100)
    y1 = np.linspace(0, 0.5, 100)
    for i in range(len(y1)):
        y1[i] = (x1[i] * 6.25) / 600
    fig = Figure(figsize=(6, 5), dpi=100)
    fig.suptitle('Comparison of theoritical honest and dishonest performance')
    fig.add_subplot(111).plot(x, y, x1, y1)
    fig.legend(["Rendement malhonnete Theorique", "Rendement Honnete"])
    #fig.add_subplot(111).plot(x1,y1)
    canvas = FigureCanvasTkAgg(fig, master=Frame2)  # A tk.DrawingArea.
    canvas.draw()
    #canvas.get_tk_widget().grid(row=13,column=1)
    toolbar = NavigationToolbar2Tk(canvas, Frame2)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
Ejemplo n.º 15
0
def save_plot(fname, plot_name, plot):
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig = Figure()
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
    ax.set_xlabel("Time")
    ax.set_ylabel(plot_name)
    fig.set_figheight(20)
    fig.set_figwidth(30)
    fig.autofmt_xdate()

    handles = []
    labels = []
    for graph in plot:
        x, y = plot[graph]
        handles.append(ax.plot(x, y))
        labels.append(graph)

    fig.legend(handles, labels, 1, shadow=True)

    canvas = FigureCanvas(fig)
    canvas.print_figure(fname, dpi=80)
Ejemplo n.º 16
0
class PageThree(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Correlation tool", font=FONT_TITLE)
        label.pack(pady=10, padx=10, side=tk.LEFT)
        self.figframe = tk.Frame(self)
        self.figframe.pack()

        self.values = []

        button1 = ttk.Button(
            self,
            text="Add random obs",
            command=lambda: self.addObservations(
                random.choice(["sugar", "bean", "peanuts", "dew", "apple"]),
                [randrange(1, 23, 1)
                 for i in range(8)], [randrange(1, 23, 1) for i in range(8)],
                color=random.choice([
                    'green', 'red', 'blue', 'yellow', 'black', 'orange', 'grey'
                ])))
        button1.pack()

        self.addObservations("coffee", [randrange(1, 23, 1) for i in range(8)],
                             [randrange(1, 23, 1) for i in range(8)],
                             color=random.choice([
                                 'green', 'red', 'blue', 'yellow', 'black',
                                 'orange', 'grey'
                             ]))

    def addvaluesandlabel(self, label, x, y):
        self.values.append((label, x, y))

    def addObservations(self, name, x, y, color="red", alpha=0.5):
        self.figframe.pack_forget()
        self.figframe.destroy()
        self.figframe = tk.Frame(self)
        self.figframe.pack()

        self.f = Figure(figsize=(5, 5), dpi=100)
        self.values.append((name, x, y, color, alpha))
        for row in self.values:
            a = self.f.add_subplot(1, 1, 1)
            rowname, x, y, color, alpha = row
            a.scatter(x,
                      y,
                      alpha=alpha,
                      color=color,
                      edgecolors='none',
                      s=30,
                      label=rowname)
            self.f.legend(rowname)
        canvas = FigureCanvasTkAgg(self.f, self.figframe)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2Tk(canvas, self.figframe)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        print(self.values)
Ejemplo n.º 17
0
def graphs2(exercises):
    """ Scatter (time-distance) plot from exercises"""

    fig = Figure()
    ax = fig.add_subplot(111)
    distances = []
    times = []
    sports = []
    sport_types = []
    for e in exercises:
        distances.append(e.distance)
        times.append(e.time_as_hours)
        sports.append(e.sport)
        sport_types.append(e.sub_sport)

    recs = []
    sport_names = list(set(sports))

    nsports = len(sport_names)

    color_dict = get_color_dict(sport_names)

    if nsports > 1:
        sport_list = get_sport_list()
        coloring_sports = sports

    else:
        s_type = sport_names[0]
        coloring_sports = make_sub_sport_list(sport_types, s_type)
        sub_sport_names = list(set(coloring_sports))

        sport_list = get_sub_sport_list(s_type)

    try:
        # ax.scatter(d,t, c=[ color_dict[i] for i in cc])
        ax.scatter(distances, times, c=[color_dict[i] for i in coloring_sports])
    except KeyError:
        # plot without colors
        ax.scatter(distances, times)

    if nsports > 1:
        for i in sport_names:  # range(0,len(set(cc))):  # legend color for unique sport values
            recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=color_list[sport_list.index(i)]))
        fig.legend(recs, sport_names, 'right')
    else:
        for i in sub_sport_names:
            recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=color_list[sport_list.index(i)]))
        fig.legend(recs, sub_sport_names, 'right')

    title = get_date_title(exercises)
    fig.suptitle(title)

    ax.set_xlabel(dist_label)
    ax.set_ylabel(time_label)

    ax.get_xaxis().get_major_formatter().set_useOffset(False)
    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    # fig.axes(x='distance', y='time')
    return graph_response(fig)
Ejemplo n.º 18
0
    def make_fig(self, start_time, end_time):
        fig = Figure(figsize=(8,8), dpi=72)
        self.lines = []
        N = len(self.channels)
        self.ax = fig.add_subplot(1,1,1) #new singleplot configuration
        colordict = ['#A6D1FF','green','red','cyan','magenta','yellow','white']
        minx = 0
        maxx = 0
        graph = []
        for i, channel in enumerate(self.channels):
            #subplot syntax is numrows, numcolumns, subplot ID
            print "ArrayMapper.make_fig(): self.X is is " , self.X, type(self.X), len(self.X)
            print "ArrayMapper.make_fig(): channel is ", channel
            print "ArrayMapper.make_fig(): self.numSamples=", self.numSamples

            time_range = arange(self.numSamples)
            #print "start_time= ", start_time, "end_time =", end_time
            if ((start_time != None) & (end_time != None)):
                time_range = arange(start_time, end_time, (end_time - start_time)/self.numSamples)
            
            #print "time_range is ", time_range
            x = self.X[channel-1,:]
            if minx > min(x):
                minx = copy.deepcopy(min(x))
            if maxx < max(x):
                maxx = copy.deepcopy(max(x))
            color = colordict[((i-1)%7)]
            newp = self.ax.plot(time_range, x, color, label=("channel " + str(i+1)))
            newp[0].set_linewidth(4)
            graph.append(newp)
            
        self.ax.set_xlabel('index')
        self.ax.set_title('Evoked response')
        #self.ax.legend()
        fig.legend(graph,self.channels,'upper right')
        if ((start_time != None) & (end_time != None)):
            mid = start_time + (end_time - start_time)/2.0
        else:
            mid = self.numSamples/2.0
        #print "setting up line at (([%d, %d], [%d, %d])[0]" % (mid, mid, min(x), max(x))
        LO = self.view3.newLength/2
        #line = self.ax.plot([mid, mid], [minx, maxx],'w')[0]
        #left edge of window:
        line = self.ax.plot([mid-LO, mid-LO], [minx, maxx],'y')[0]
        self.ax.add_line(line)
        self.lines.append(line)
        #middle of window, where the scalar data comes from:
        line = self.ax.plot([mid, mid], [minx, maxx],'r')[0]
        self.ax.add_line(line)
        self.lines.append(line)
        #right edge of window
        line = self.ax.plot([mid+LO, mid+LO], [minx, maxx],'y')[0]
        self.ax.add_line(line)
        self.lines.append(line)
        self.ax.patch.set_facecolor('black') #transparency
        self.finishedFigure = fig
        
        return fig
Ejemplo n.º 19
0
def plot_africa_totals(data, colors=['blue', 'orangered', 'lawngreen']):
    """Create lineplots of coronavirus case totals in Africa.

    Parameters:
    ----------
    data: pd.DateFrame
        A dataframe of historic coronavirus cases in Africa.
    colors: str, valid matplotlib color input
        Colors to apply to the 'confirmed', 'deaths', and 'recovered'
        lineplots, respectively'.
    """
    # Convert Date column values to Timestamps
    data['Date'] = data['Date'].astype('datetime64')

    # Calculate totals for each day. After this, only the columns 'Confirmed'
    # 'Deaths' and 'Recovered' remain, with 'Date' becoming the index.
    data = data.groupby('Date').sum()

    latest_date = data.index.max().strftime('%h %d, %Y')  # used in title

    # Create a matplotlib Figure, with lineplots for 'confirmed', 'recovered',
    # and 'deaths'
    fig = Figure(figsize=(10, 5), dpi=200)
    fig.suptitle(f'Total Coronavirus Cases in Africa as at {latest_date}',
                 size=18)
    ax = fig.subplots()
    for idx, label in enumerate(['Confirmed', 'Deaths', 'Recovered']):
        ax.plot(data[label].index,
                data[label],
                lw=2,
                color=colors[idx],
                label=label)

    # Annotate lineplots with current totals
    for line in ax.lines:
        x_coord, y_coord = line.get_xydata()[-1]  # position of latest totals
        ax.annotate(
            f'{line.get_ydata().max():,}',  # latest total
            xy=(x_coord + 4, y_coord),
            style='oblique')

    ax.tick_params(axis='x', rotation=60)  # rotate x-axis ticks (dates) by 60°
    ax.yaxis.grid()  # draw horizontal gridlines
    ax.set_ylabel('Total Cases', size=14)
    despine(ax)  # remove bordering box

    # Show y-axis ticks as full plain text, instead of in scientific notation
    ax.ticklabel_format(axis='y', style='plain')

    # Set the x-axis to show dates in 2-week intervals
    ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=2))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%h %d'))  # e.g. Jan 20

    fig.legend(loc='right')
    fig.savefig('images/africa_totals.png',
                bbox_inches='tight',
                transparent=True)
Ejemplo n.º 20
0
def evolution():
    datamodel.updater(data)  # Call to update

    fig = Figure(figsize=(12, 8))

    ax = fig.add_subplot(1, 1, 1)

    xss = [str(i) for i in range(1, len(data.diagnosticados_acc) + 1)]
    xs = range(0, len(data.diagnosticados_acc))

    ax.plot(xss,
            data.diagnosticados_acc,
            'o-',
            label='Casos acumulados',
            color=red,
            alpha=0.5)
    ax.plot(xss, data.activos_acc, 'o-', label='Casos activos', color=red)
    ax.plot(xss,
            data.diagnosticados,
            'o-',
            label='Casos en el d铆a',
            color=cyan)

    for x, y in zip(xs, data.diagnosticados_acc):
        label = "{}".format(y)

        ax.annotate(label, (x, y),
                    textcoords='offset points',
                    xytext=(0, 10),
                    ha='center')

    for x, y in zip(xs, data.activos_acc):
        label = "{}".format(y)

        ax.annotate(label, (x, y),
                    textcoords='offset points',
                    xytext=(0, 10),
                    ha='center')

    for x, y in zip(xs, data.diagnosticados):
        label = "{}".format(y)

        ax.annotate(label, (x, y),
                    textcoords='offset points',
                    xytext=(0, -17),
                    ha='center')

    ax.set_title('Evoluci贸n de casos por d铆as', fontsize=20)
    fig.legend(frameon=True, fontsize=12)

    FigureCanvasAgg(fig).print_png('evolution.png')

    apiurl = config.SERVER_URI + '/evolution'
    watermark_text('evolution.png', 'evolution.png', apiurl, (0, 0))

    return send_file('evolution.png')
Ejemplo n.º 21
0
def evolution_graph(data):
    filename = 'evolution_graph.png'

    fig = Figure(figsize=(18, 10))

    ax = fig.add_subplot(1, 1, 1)

    xss = [str(i) for i in range(1, len(data['diagnosticados_acc']) + 1)]
    xs = range(0, len(data['diagnosticados_acc']))

    ax.plot(xss,
            data['diagnosticados_acc'],
            'o-',
            label='Casos acumulados',
            color=red,
            alpha=0.5)
    ax.plot(xss, data['activos_acc'], 'o-', label='Casos activos', color=red)
    ax.plot(xss,
            data['diagnosticados'],
            'o-',
            label='Casos en el día',
            color=cyan)

    for x, y in zip(xs, data['diagnosticados_acc']):
        label = "{}".format(y)

        ax.annotate(label, (x, y),
                    textcoords='offset points',
                    xytext=(0, 10),
                    ha='center')

    for x, y in zip(xs, data['activos_acc']):
        label = "{}".format(y)

        ax.annotate(label, (x, y),
                    textcoords='offset points',
                    xytext=(0, 10),
                    ha='center')

    for x, y in zip(xs, data['diagnosticados']):
        label = "{}".format(y)

        ax.annotate(label, (x, y),
                    textcoords='offset points',
                    xytext=(0, -17),
                    ha='center')

    ax.set_title('Evolución de casos por días', fontsize=18)
    fig.legend(frameon=True, fontsize=12)

    FigureCanvasAgg(fig).print_png(filename)

    apiurl = config.SERVER_URI + '/evolution_graph'
    watermark_text(filename, filename, apiurl, (0, 0))

    return filename
Ejemplo n.º 22
0
def graph():
    """
    Endpoint for generating a graph from the database
    Takes to optional form arguments
    start_time: UNIX timestamp
                earliest data point to retrieve
    end time: UNIX timestamp
              latest data point to retrieve
    """
    # Try to get params request
    params = extract_variables(['start_time', 'end_time', 'sensor_id'],
                               request)
    # Fetch data from database
    results = query_climate_range(**params)

    # Turn it in to lists which can be graphed
    dates = []
    humids = []
    temps = []
    pressures = []
    for result in results:
        dates.append(datetime.datetime.fromtimestamp(result['time']))
        humids.append(result['humid'])
        temps.append(result['temp'])
        pressures.append(result['pressure'])

    # Graph it
    fig = Figure()
    # First y axis (temp and humid)
    axis = fig.add_subplot(1, 1, 1)
    # Plot humidity and temp on the same scale
    axis.plot_date(dates, humids, '-', color=COLORS['blue'])
    axis.plot_date(dates, temps, '-', color=COLORS['red'])
    axis.xaxis.set_major_formatter(DateFormatter('%d/%m/%y %H:%M'))
    axis.set_ylabel('Humidity in % & Temps in C')
    axis.set_xlabel('Time')
    # Second y axis (pressure)
    axis_pressure = axis.twinx()
    # Plot pressure
    axis_pressure.plot_date(dates, pressures, '-', color=COLORS['green'])
    axis_pressure.xaxis.set_major_formatter(DateFormatter('%d/%m/%y %H:%M'))
    axis_pressure.set_ylabel('Pressure in mbar')
    # Configure the figure
    fig.autofmt_xdate()
    fig.legend(['Humidity', 'Temperature', 'Pressure'], loc='lower right')
    fig.set_tight_layout(True)
    canvas = FigureCanvas(fig)
    # Save output
    png_output = BytesIO()
    canvas.print_png(png_output)

    # Create the response and send it
    response = make_response(png_output.getvalue())
    response.headers['Content-Type'] = 'image/png'
    return response
Ejemplo n.º 23
0
    def PlotResults (self, plot_frame, excel_frame):
        
        popup_window = Toplevel(self.window)

        popup_window.title("Results")
        plot_frame = plot_frame.sort_values(by='Cluster Count',ascending=False)
        plot_frame["Cumulative Percentage"] = plot_frame['Cluster Count'].cumsum()/plot_frame['Cluster Count'].sum()*100
        
#        print (f'{plot_frame["Cluster Count"]}  {plot_frame["Cumulative Percentage"]}')
        fig = Figure(figsize=(40,5))
        ax = fig.add_subplot(111)
        ax.bar(plot_frame['Cluster'], plot_frame["Cluster Count"], color="C0")
        ax2 = ax.twinx()
        ax2.plot(plot_frame['Cluster'], plot_frame["Cumulative Percentage"], color="C1", marker="D", ms=7)
        ax2.yaxis.set_major_formatter(PercentFormatter())
        
        ax.tick_params(axis="y", colors="C0")
        ax2.tick_params(axis="y", colors="C1")

        fig.legend()
        ax.set_title ("RESULTS - Summary of categorized Ticket Data (Most contributing to least contributing categories)", fontsize=20)
        ax.set_ylabel("# of Tickets", fontsize=10)
        ax.set_xlabel("Category #", fontsize=10)

        canvas = FigureCanvasTkAgg(fig, master=popup_window )

        tree = ttk.Treeview(popup_window)
        
        tree["columns"]=("one","two")
        tree.column("one", width=500 )
        tree.column("two", width=500)
        tree.heading("one", text="Formatted Input Data")
        tree.heading("two", text="Raw Input Data")
                
        i = 0
        for clusterindex, row in plot_frame.iterrows():
            try:
                id2 = tree.insert("", i, row["Cluster"], text="Category "+ str(clusterindex + 1) + " -> " + str(row["Cluster Count"]) + " tickets"  +" - " + row["Machine Tag"].upper())            
                for excelindex, excelrow in excel_frame.iterrows():
                    if (clusterindex == excelrow['Machine Cluster'] ):
                        tree.insert(id2, "end", excelindex, text=excelindex, values=(excelrow['Transformed Data'],excelrow['Issue']))
            # handles parameters in different way 
            except:
                id2 = tree.insert("", i, row["Cluster"], text="Tag -> " + row["Machine Tag"].upper() +" - " + str(row["Cluster Count"]) + " tickets")            
                for excelindex, excelrow in excel_frame.iterrows():
                    if (clusterindex == excelrow['Machine Tag'] ):
                        tree.insert(id2, "end", excelindex, text=excelindex, values=(excelrow['Transformed Data'],excelrow['Issue']))

            i+= 1

        exportbutton = Button(popup_window, text="Export the Results", command=lambda : self.ExportData(excel_frame))
            
        canvas.get_tk_widget().pack()
        tree.pack()
        exportbutton.pack()
Ejemplo n.º 24
0
def graph():
    button_graph.config(state=tk.DISABLED)
    def enable():
        button_graph.config(state=tk.NORMAL)
        graphwin.destroy()
    conn = sqlite3.connect('CSVDB1.db')
    # create a database connection
    cur = conn.cursor()
    cur.execute("SELECT * FROM record")
    rows = cur.fetchall()
    # list = [i.replace('(','') for i in rows]
    df = pd.DataFrame(rows)
    time = df[0].tolist()
    total = df[1].tolist()
    car = df[2].tolist()
    bus = df[3].tolist()
    person = df[4].tolist()
    bike = df[5].tolist()
    cycle = df[6].tolist()
    truck = df[7].tolist()
    


    # car = df[1].tolist()
    # bike = df[2].tolist()
    # bus = df[3].tolist()
    # cycle = df[4].tolist()
    # truck = df[5].tolist()

    # --------------------------------------------------------------
    fig = Figure(figsize=(10, 6), facecolor='white')
    # --------------------------------------------------------------
    axis = fig.add_subplot(111)
    axis.set_title("Graph plot of different vehicles and their count")
    t0, = axis.plot(time, car)
    t1, = axis.plot(time, bike)
    t2, = axis.plot(time, bus)
    t3, = axis.plot(time, cycle)
    t4, = axis.plot(time, truck)
    # axis.xticks(rotation=90)
    axis.set_ylabel('COUNT')
    axis.set_xlabel('TIME')
    axis.xaxis.set_major_locator(plt.MaxNLocator(4))
    # axis.set_xticklabels(time, rotation=45, ha='right')
    axis.grid()
    fig.legend((t0, t1, t2, t3, t4), ('CAR', 'BIKE', 'BUS', 'CYCLE', 'TRUCK'), 'upper right')

    graphwin = tk.Toplevel()
    graphwin.protocol("WM_DELETE_WINDOW", enable)

    canvas = FigureCanvasTkAgg(fig, master=graphwin)
    canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    graphwin.update()
    graphwin.deiconify()
Ejemplo n.º 25
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self, text="Facebook Stock (Graph)", font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        button1 = ttk.Button(self, text="Back to Home", command=lambda: controller.show_frame(InitialPage))
        button1.pack()

        # GRAPHSSSS

        f = Figure(figsize=(14, 8), dpi=100)
        ax = f.add_subplot(111, label="1")
        ax2 = f.add_subplot(111, label="2", frame_on=False)
        ax3 = f.add_subplot(111, label="3", frame_on=False)

        title = "Facebook Stock Prices\nCurennt Price: " + FacebookCurrentPrice

        # REGULAR PRICE LINE
        ax.plot(FacebookDates, FacebookPrices, 'b', label="Stock Price", linewidth=2)
        ax.set_title(title)
        ax.tick_params('x', labelrotation=90)
        ax.set_ylim([140, 205])

        # 13 DAY MOVING AVERAGE LINE
        ax2.plot(FacebookDailyDates[12:], facebook_moving_averages13, 'g--', label="13 Day Moving Average")
        ax2.axes.get_xaxis().set_visible(False)
        ax2.set_ylim([140, 205])

        # 52 DAY MOVING AVERAGE LINE
        ax3.plot(FacebookDailyDates[51:], facebook_moving_averages52, 'r--', label="52 Day Moving Average")
        ax3.axes.get_xaxis().set_visible(False)
        ax3.set_ylim([140, 205])

        f.legend()

        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        # ALGORITHM

        intersections = intersection(facebook_moving_averages13, facebook_moving_averages52, FacebookDailyDates)

        # ALGORITHM FINDINGS
        def clicked():
            messagebox.showinfo('Algorithm Findings',
                                'Crossing Average Intersections: ' + str(len(intersections)) + '\n'
                                    + "Intersection Dates: " + '\n' + str( intersections))

        button2 = ttk.Button(self, text="Algorithm Findings", command=clicked)
        button2.pack()
Ejemplo n.º 26
0
def buildActivityGraph(year):
    con = db.create_connection()
    df = pd.read_sql_query(
        'SELECT date, activity FROM arrivals WHERE strftime(\'%Y\', date) = "{}" AND activity <> "" ORDER BY date'
        .format(year),
        con,
        parse_dates=['date'],
        index_col=['date'])
    con.close()

    fig = Figure(figsize=(12, 12))
    axis = fig.subplots(1)

    if df.empty == False:
        df_activity = df.groupby(
            'date').activity.value_counts().unstack().fillna(0)

        resampled = df_activity.resample('W').sum()

        columns = resampled.columns
        labels = columns.values.tolist()

        colour_map = cm.get_cmap('tab20', len(columns) + 1)

        x = resampled.index
        bottom = np.zeros(resampled.shape[0])
        for i, column in enumerate(columns, start=0):
            axis.bar(x,
                     resampled[column].values.tolist(),
                     bottom=bottom,
                     label=column,
                     color=colour_map.colors[i])
            bottom += resampled[column].values.tolist()

    date_format = mpl_dates.DateFormatter('%d %b %Y')
    axis.xaxis_date()
    axis.xaxis.set_major_formatter(date_format)
    axis.set_title('Weekly arrival activity at Aberdeen {}'.format(year))
    fig.legend(loc='center right',
               fancybox=True,
               shadow=True,
               fontsize=10,
               ncol=2)

    fig.autofmt_xdate()
    fig.tight_layout()
    fig.subplots_adjust(right=0.75)

    canvas = FigureCanvas(fig)
    output = io.BytesIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
Ejemplo n.º 27
0
def plot_yahoo(root):
    global file_dir
    global ticker_var
    global date_var
    ticker = ticker_var.get()
    file_path = file_dir.get()
    date = date_var.get()
    try:
        prices = pd.read_csv(file_path+'/'+date+'_'+ticker+'.csv')
        prices['formatted_date']=pd.to_datetime(prices['formatted_date'])
        prices.set_index('formatted_date', inplace=True)
        sentiments = pd.read_csv(file_path+'/'+ticker+'_sentiments.csv')
    except:
        messagebox.showerror(title='File Select Error', message='No file present!')
        return
    sentiments['Filing Date'] = pd.to_datetime(sentiments['Filing Date'])

    sentiments.sort_values(by=['Filing Date'], inplace=True, ascending=True)

    info = pd.merge(prices,sentiments,left_index=True,right_on='Filing Date')
    info.set_index('Filing Date', inplace=True)
    info = info.drop(columns=['high','low','open','close','volume','1d returns','2d returns','3d returns','5d returns','10d returns','Symbol_x','Symbol_y','Report Type'])
    info['Total Words'] = info['Positive']+info['Negative']+info['Uncertainty']+info['Litigious']+info['Constraining']+info['Superfluous']+info['Interesting']+info['Modal']
    info[['Positive','Negative','Uncertainty','Litigious','Constraining','Superfluous','Interesting','Modal']]=info[['Positive','Negative','Uncertainty','Litigious','Constraining','Superfluous','Interesting','Modal']].div(info['Total Words'], axis=0)

    normalised_prices=(info['adjclose']-info['adjclose'].min())/(info['adjclose'].max()-info['adjclose'].min())
    normalised_Positive=(info['Positive']-info['Positive'].min())/(info['Positive'].max()-info['Positive'].min())
    normalised_Negative=(info['Negative']-info['Negative'].min())/(info['Negative'].max()-info['Negative'].min())
    normalised_Uncertainty=(info['Uncertainty']-info['Uncertainty'].min())/(info['Uncertainty'].max()-info['Uncertainty'].min())
    normalised_Litigious=(info['Litigious']-info['Litigious'].min())/(info['Litigious'].max()-info['Litigious'].min())
    normalised_Constraining=(info['Constraining']-info['Constraining'].min())/(info['Constraining'].max()-info['Constraining'].min())
    normalised_Superfluous=(info['Superfluous']-info['Superfluous'].min())/(info['Superfluous'].max()-info['Superfluous'].min())
    normalised_Interesting=(info['Interesting']-info['Interesting'].min())/(info['Interesting'].max()-info['Interesting'].min())
    normalised_Modal=(info['Modal']-info['Modal'].min())/(info['Modal'].max()-info['Modal'].min())
    info = info.drop(columns='Total Words')

    dates=info.index
    fig = Figure(figsize=(5, 4), dpi=100)
    a = fig.add_subplot(111)
    a.plot(dates,normalised_prices,label='Price')
    a.plot(dates,normalised_Positive,label='Positive')
    a.plot(dates,normalised_Negative,label='Negative')
    a.plot(dates,normalised_Uncertainty,label='Uncertainty')
    a.plot(dates,normalised_Litigious,label='Litigious')
    a.plot(dates,normalised_Constraining,label='Constraining')
    a.plot(dates,normalised_Superfluous,label='Superfluous')
    a.plot(dates,normalised_Interesting,label='Interesting')
    a.plot(dates,normalised_Modal,label='Modal')
    fig.legend()
    canvas = FigureCanvasTkAgg(fig, master=root)
    canvas.draw()
    canvas.get_tk_widget().grid(row=2,columnspan=4,sticky=N+S+W+E)
Ejemplo n.º 28
0
def plot_spectrum(real, fake):
    x = np.linspace(1, 31, 31, endpoint=True)
    fig = Figure()
    canvas = FigureCanvasAgg(fig)
    ax = fig.gca()
    plot_real,  = ax.plot(x, real)
    plot_fake,  = ax.plot(x, fake)
    fig.legend((plot_real,plot_fake), ('real', 'fake'))
    canvas.draw()
    I = np.fromstring(canvas.tostring_rgb(), dtype='uint8', sep='')
    I = I.reshape(canvas.get_width_height()[::-1]+(3,))
    I = np.transpose(I, [2,0,1])
    return np.float32(I)
Ejemplo n.º 29
0
def create_window_graph(xas,yas,labname):

    window = tk.Toplevel()


    #t = np.arange(5, 10, .01) #plotter x axes
    #t1 = np.arange(10, 15, .01) #plotter x axes


    fig = Figure(figsize=(8, 4), dpi=80)

    ax = fig.add_subplot(111)
    ax.plot(xas,yas, 'r--', label = labname)#plotter y og x axes NB DE MÅ VÆRE LIKE LANGE OM DU VIL HA EN NY LINJE COPY PAST DENNE
    ax.set_xlim(xmin =1 , xmax = 10)



    fig.legend()




    canvas = FigureCanvasTkAgg(fig, master=window)
    canvas.draw()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    toolbar = NavigationToolbar2Tk(canvas, window)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)


    def on_key_press(event):
        print("you pressed {}".format(event.key))
        key_press_handler(event, canvas, toolbar)


    canvas.mpl_connect("key_press_event", on_key_press)


    def _quit():
        #window.quit()
        window.destroy()

    lable32 = tk.Label(master = window, text = "Time")
    lable32.pack()

    sap = tk.Label(master = window, text = "")
    sap.pack()

    button = tk.Button(master=window, text="Quit", command=_quit, bg='red', fg='white', font=('helvetica', 10, 'bold'))
    button.pack()
Ejemplo n.º 30
0
class PlotCanvas(FigureCanvas):
    def __init__(self, parent=None,  width=8.8, height=10.5, dpi=100, title=' '):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, self.fig)
        self.setStyleSheet("background-color:rgb(240,240,240);")
        self.fig.set_facecolor("none")
        self.axes = self.fig.add_subplot(111)
        self.setParent(parent)
        self.title = title
        self.set_up_plot()

        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def set_up_plot(self):
        self.axes.cla()
        self.axes.grid(True, which='both', axis='both')
        self.axes.set_xscale('linear')
        self.axes.set_yscale('linear')
        self.axes.set_title(self.title)

    def plot(self, x, y, do_cla=True, **kwargs):
        if do_cla:
            self.axes.cla()  # Стереть всё предыдущее

        self.axes.grid(True, which='both', axis='both')
        self.axes.plot(x, y, **kwargs)
        if 'label' in kwargs:
            self.fig.legend()
        self.fig.canvas.draw_idle()

    def add_point(self, x, y, **kwargs):
        self.axes.plot(x, y, **kwargs)
        self.fig.canvas.draw_idle()

    def clear(self):
        self.axes.cla()
        #self.axes.clear()

    def set_xlim(self, left, right):
        self.axes.set_xlim(left, right)

    def setFrameShape(self, styled_panel):
        pass  # Этот метод вызывается в автоматически сгенерированном коде от Qt Designer, но нам он не нужен

    def setFrameShadow(self, raised):
        pass  # Этот метод вызывается в автоматически сгенерированном коде от Qt Designer, но нам он не нужен

    def setTitle(self, title):
        self.axes.set_title(title, fontsize=19)
Ejemplo n.º 31
0
    def plot_data(self, x, y1, y2, title, legend_y1, legend_y2):
        for widget in self.draw_frame.winfo_children():
            widget.destroy()
        fig = Figure(figsize=(5, 3.8), dpi=100)
        fig.suptitle(title)
        fig.add_subplot(111).plot(x, y1)
        fig.legend(legend_y1)
        if len(y2) > 0:
            fig.add_subplot(111).plot(x, y2)
            fig.legend((legend_y1, legend_y2))

        canvas = FigureCanvasTkAgg(fig,
                                   master=self.draw_frame)  # A tk.DrawingArea.
        canvas.draw()
        canvas.get_tk_widget().pack()
Ejemplo n.º 32
0
 def plot(self, curveList, starList):
     colors = plt.rcParams["axes.prop_cycle"]()
     fig = Figure(figsize=(10,10))
     n = len(curveList)
     starList = [str(x) for x in starList]
     for i in range(n):
         c = next(colors)["color"]
         plotfig = fig.add_subplot((n//2)+1, 2, i + 1)
         plotfig.plot(curveList[i],label=starList[i],color=c)
     fig.legend()
     canvas = FigureCanvasTkAgg(fig, master=self.master)
     canvas.get_tk_widget().pack()
     canvas.draw()
             
     return None
Ejemplo n.º 33
0
def horizontal_legend(
		fig: Figure,
		handles: Optional[Iterable[Artist]] = None,
		labels: Optional[Iterable[str]] = None,
		*,
		ncol: int = 1,
		**kwargs,
		) -> Legend:
	"""
	Place a legend on the figure, with the items arranged to read right to left rather than top to bottom.

	:param fig: The figure to plot the legend on.
	:param handles:
	:param labels:
	:param ncol: The number of columns in the legend.
	:param kwargs: Addition keyword arguments passed to :meth:`matplotlib.figure.Figure.legend`.
	"""

	if handles is None and labels is None:
		handles, labels = fig.axes[0].get_legend_handles_labels()

	# Rearrange legend items to read right to left rather than top to bottom.
	if handles:
		handles = list(filter(None, transpose(handles, ncol)))
	if labels:
		labels = list(filter(None, transpose(labels, ncol)))

	return fig.legend(handles, labels, ncol=ncol, **kwargs)
Ejemplo n.º 34
0
def generate_figure(samples):
    ohms_styles = (
        ('r', 'r:'),
        ('x', 'y:'),
        ('z', 'g:'),
    )
    x = []
    yswr = []
    handles = []

    for sample in samples:
        x.append(float(sample['frequency'])/10**6)
        yswr.append(sample['swr'])

    fake_file = StringIO()
    figure = Figure(figsize=(9, 6, ), facecolor='white')
    canvas = FigureCanvasAgg(figure)

    axis = figure.add_subplot(111)
    axis.set_ylabel('SWR')
    axis.set_xlabel('Frequency (MHz)')
    axis.set_axis_bgcolor((1, 1, 1,))
    axis_ohms = axis.twinx()
    axis_ohms.set_ylabel('Ohms')

    handles.append(
        axis.plot(x, yswr, 'b', label='SWR')[0]
    )
    for prop, style in ohms_styles:
        sample = [float(v.get(prop)) for v in samples]
        handles.append(
            axis_ohms.plot(x, sample, style, label=prop)[0]
        )

    figure.legend(
        handles=handles,
        labels=[
            'SWR'
        ] + [prop for prop, style in ohms_styles]
    )

    canvas.print_png(fake_file)
    data = fake_file.getvalue()

    return data
Ejemplo n.º 35
0
def CreateCurrentVoltagePlot(t, c, v, title, filename, xlim=(0,60)):
    figure = Figure(figsize=(8,4))
    figure.suptitle(title)
    axis1 = figure.add_subplot(111)
    axis1.grid(True)
    lines = []
    lines.extend(axis1.plot(t, c, 'b'))
    axis1.set_xlabel('Time')
    axis1.set_ylabel('Current [A]')
    axis1.set_xlim(xlim)
    axis1.set_ylim([0, 6])
    axis2 = axis1.twinx()
    lines.extend(axis2.plot(t, v, 'r'))
    axis2.set_ylabel('Voltage [V]')
    axis2.set_ylim([11, 15])
    figure.legend(lines, ('Current', 'Voltage'), 'upper left')
    canvas = FigureCanvasAgg(figure) 
    canvas.print_figure(filename, dpi=80)
def plot_raw_lightcurve(picid, lc0, psc_dir):
    fig = Figure()
    FigureCanvas(fig)

    fig.set_size_inches(12, 7)

    ax = fig.add_subplot(111)

    ax.plot(lc0.loc[lc0.color == 'g'].target.values,
            marker='o', label='Target')  # .plot(marker='o')
    ax.plot(lc0.loc[lc0.color == 'g'].reference.values,
            marker='o', label='Reference')  # .plot(marker='o')

    fig.suptitle(f'Raw Flux - {picid}')
    fig.tight_layout()
    fig.legend()

    plot_fn = os.path.join(psc_dir, 'plots', f'raw-flux-{picid}.png')
    fig.savefig(plot_fn, transparent=False)
Ejemplo n.º 37
0
class Gui:
	def __init__( self ):
		self.root = tk.Tk()
		self.root.wm_title( "Log grapher" )
		matplotlib.rc('font', size=8 )
		self.fig = Figure( figsize=(11,5), dpi=100 )
		self.fig.set_tight_layout( True )
		self.axis = self.fig.add_subplot( 111 )
		self.axis.set_title( 'Graph' )
		self.axis.set_xlabel( 'X axis label' )
		self.axis.set_ylabel( 'Y label' )
		self.canvas = FigureCanvasTkAgg( self.fig, master=self.root )
		self.canvas.show()
		self.canvas.get_tk_widget().pack( side=TOP, fill=BOTH, expand=1 )

	def setLabels( self, labelList ):
		"""setLabels before doing anything else - configures axes etc"""
		self.labels = labelList
		for i in range( 0, len( labelList ) ):
			self.axis.plot( [] )
		self.fig.legend( self.axis.lines, self.labels, 'lower center', ncol=len(self.labels), 
			borderpad=0.3, handletextpad=0.2, columnspacing=0.3 )

	def append( self, xVal, yValList ):
		"""
		yValList must be the same length as labelList, None values will be ignored.
		Call update() afterwards.
		"""
		#print( "gui append " + str( xVal ) + ", " )
		#pprint( yValList )
		for idx, yVal in enumerate( yValList ):
			if yVal is not None:
				hl = self.axis.lines[idx]
				hl.set_xdata( numpy.append( hl.get_xdata(), xVal ) )
				hl.set_ydata( numpy.append( hl.get_ydata(), yVal ) )

	def update( self ):
		self.axis.relim()
		self.axis.autoscale_view()
		self.canvas.draw()
Ejemplo n.º 38
0
class matplot_figure(object):
    """\brief figure to show, which can be closed
    """

    def __init__(self,):
        """\brief constuctor
        """
        self.win = gtk.Window()
        self.win.connect("delete-event", lambda widget, event: False)
        self.win.set_default_size(640, 480)
        self.win.set_title("Plot")
        vbox = gtk.VBox()
        self.win.add(vbox)
        self.fig = Figure(figsize=(5, 4), dpi=100)

        canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        vbox.pack_start(canvas)
        toolbar = NavigationToolbar(canvas, self.win)
        vbox.pack_start(toolbar, False, False)

    def show(self,):
        """\brief show window of the figure
        """
        self.win.show_all()

    def hide(self,):
        """\brief hide window of the figure
        """
        self.win.hide()

    def add_subplot(self, *args, **kargs):
        """\brief 
        \param *args
        \param **kargs
        """
        return self.fig.add_subplot(*args, **kargs)

    def autofmt_xdate(self, *args, **kargs):
        """\brief autoformat date along X
        \param *args
        \param **kargs
        """
        return self.fig.autofmt_xdate(*args, **kargs)

    def legend(self, *args, **kargs):
        """\brief plot legend
        \param *args
        \param **kargs
        """
        return self.fig.legend(*args, **kargs)
Ejemplo n.º 39
0
for p in pl:
    p.set_marker('o')
    p.set_markersize(5)

ax.set_xlabel(r'run number')
ax.set_xlim(56350,57323)

ax.set_ylabel(r'\texttt{DC} residual mean (\textmu m)')
ax.set_ylim(-150,150)

legend_labels = []
for i in numpy.arange(1,7):
    legend_labels += [i]

lgd = fig.legend(pl, legend_labels, title=r'superlayer', loc='right')
lgd.draw_frame(False)

fig.subplots_adjust(right=0.85)

can = FigureCanvas(fig)
can.print_figure('dc_resid_mean.eps')



fig = Figure(figsize=(8,4), dpi=100, facecolor = '#FFFFFF')
ax = fig.add_subplot(111)

pl = []
for i in numpy.arange(7,13):
    pl += ax.plot(d[0], d[i])
class TemperaturePanel(wx.Panel):
    """
    GUI Window for plotting temperature data.
    """
    #--------------------------------------------------------------------------
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        global filePath
        
        global ttempA_list
        global tempA_list
        global ttempB_list
        global tempB_list
        
        self.create_title("Temperature Panel")
        self.init_plot()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.create_control_panel()
        self.create_sizer()
        
        pub.subscribe(self.OnTimeTempA, "Time Temp A")
        pub.subscribe(self.OnTempA, "Temp A")
        pub.subscribe(self.OnTimeTempB, "Time Temp B")
        pub.subscribe(self.OnTempB, "Temp B")

        
        # For saving the plots at the end of data acquisition:
        pub.subscribe(self.save_plot, "Save_All")
        
        self.animator = animation.FuncAnimation(self.figure, self.draw_plot, interval=500, blit=False)
    #end init
    
    #--------------------------------------------------------------------------    
    def create_title(self, name):
        self.titlePanel = wx.Panel(self, -1)
        title = wx.StaticText(self.titlePanel, label=name)
        font_title = wx.Font(16, wx.DEFAULT, wx.NORMAL, wx.BOLD)
        title.SetFont(font_title)
        
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add((0,-1))
        hbox.Add(title, 0, wx.LEFT, 5)
        
        self.titlePanel.SetSizer(hbox)    
    #end def
    
    #--------------------------------------------------------------------------
    def create_control_panel(self):
        
        self.xmin_control = BoundControlBox(self, -1, "t min", 0)
        self.xmax_control = BoundControlBox(self, -1, "t max", 100)
        self.ymin_control = BoundControlBox(self, -1, "T min", 0)
        self.ymax_control = BoundControlBox(self, -1, "T max", 70)
        
        self.hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox1.AddSpacer(10)
        self.hbox1.Add(self.xmin_control, border=5, flag=wx.ALL)
        self.hbox1.Add(self.xmax_control, border=5, flag=wx.ALL)
        self.hbox1.AddSpacer(10)
        self.hbox1.Add(self.ymin_control, border=5, flag=wx.ALL)
        self.hbox1.Add(self.ymax_control, border=5, flag=wx.ALL)     
    #end def

    #--------------------------------------------------------------------------
    def OnTimeTempA(self, msg):
        self.ttA = float(msg)   
        ttempA_list.append(self.ttA)
    #end def
        
    #--------------------------------------------------------------------------
    def OnTempA(self, msg):
        self.tA = float(msg)
        tempA_list.append(self.tA)    
    #end def
    
    #--------------------------------------------------------------------------
    def OnTimeTempB(self, msg):
        self.ttB = float(msg)    
        ttempB_list.append(self.ttB)
    #end def
        
    #--------------------------------------------------------------------------
    def OnTempB(self, msg):
        self.tB = float(msg)
        tempB_list.append(self.tB)    
    #end def

    #--------------------------------------------------------------------------
    def init_plot(self):
        self.dpi = 100
        self.colorTA = 'r'
        self.colorTB = 'b'
        
        self.figure = Figure((6,2), dpi=self.dpi)
        self.subplot = self.figure.add_subplot(111)
        
        self.lineTA, = self.subplot.plot(ttempA_list,tempA_list, color=self.colorTA, linewidth=1)
        self.lineTB, = self.subplot.plot(ttempB_list,tempB_list, color=self.colorTB, linewidth=1)
        
        self.legend = self.figure.legend( (self.lineTA, self.lineTB), (r"$T_A$",r"$T_B$"), (0.15,0.65),fontsize=8)
        #self.subplot.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', \
            #verticalalignment='top', transform = self.subplot.transAxes)
    #end def

    #--------------------------------------------------------------------------
    def draw_plot(self,i):
        self.subplot.clear()
        #self.subplot.set_title("temperature vs. time", fontsize=12)
        self.subplot.set_ylabel(r"temperature ($\degree$C)", fontsize = 8)
        self.subplot.set_xlabel("time (s)", fontsize = 8)
        
        # Adjustable scale:
        if self.xmax_control.is_auto():
            xmax = max(ttempA_list+ttempB_list)
        else:
            xmax = float(self.xmax_control.manual_value())    
        if self.xmin_control.is_auto():            
            xmin = 0
        else:
            xmin = float(self.xmin_control.manual_value())
        if self.ymin_control.is_auto():
            ymin = 0
        else:
            ymin = float(self.ymin_control.manual_value())
        if self.ymax_control.is_auto():
            maxT = max(tempA_list+tempB_list)
            ymax = maxT + abs(maxT)*0.3
        else:
            ymax = float(self.ymax_control.manual_value())
        
        self.subplot.set_xlim([xmin, xmax])
        self.subplot.set_ylim([ymin, ymax])
        
        pylab.setp(self.subplot.get_xticklabels(), fontsize=8)
        pylab.setp(self.subplot.get_yticklabels(), fontsize=8)
        
        self.lineTA, = self.subplot.plot(ttempA_list,tempA_list, color=self.colorTA, linewidth=1)
        self.lineTB, = self.subplot.plot(ttempB_list,tempB_list, color=self.colorTB, linewidth=1)
        
        return (self.lineTA, self.lineTB)
        
    #end def
    
    #--------------------------------------------------------------------------
    def save_plot(self, msg):
        path = filePath + "/Temperature_Plot.png"
        self.canvas.print_figure(path)
        
    #end def
    
    #--------------------------------------------------------------------------
    def create_sizer(self):    
        sizer = wx.GridBagSizer(3,1)
        sizer.Add(self.titlePanel, (0, 0),flag=wx.ALIGN_CENTER_HORIZONTAL)
        sizer.Add(self.canvas, ( 1,0),flag=wx.ALIGN_CENTER_HORIZONTAL)
        sizer.Add(self.hbox1, (2,0),flag=wx.ALIGN_CENTER_HORIZONTAL)
        
        self.SetSizer(sizer)
Ejemplo n.º 41
0
class MplCanvas(FigureCanvas):
    def __init__(self, parent=None, width=8, height=10, dpi=80):
        self.parent = parent
        self.redraw_yticks = True

        self.figure = Figure(figsize=(width, height), dpi=dpi, facecolor='#bbbbbb')
        FigureCanvas.__init__(self, self.figure)

        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)


    def run(self, config_file, server):
        self.mod = Dragonfly_Module(0, 0)
        self.mod.ConnectToMMM(server)
        self.msg_types = ['END_TASK_STATE', 'SESSION_CONFIG', 'EM_DECODER_CONFIGURATION']
        self.msg_types.sort()
        self.mod.Subscribe(MT_EXIT)
        self.mod.Subscribe(rc.MT_PING)
        for i in self.msg_types:
            self.mod.Subscribe(eval('rc.MT_%s' % (i)))
        self.mod.SendModuleReady()
        print "Connected to Dragonfly at", server
        print "mod_id = ", self.mod.GetModuleID()

        self.config_file = config_file
        self.load_config()
        self.init_vars()
        self.init_plot()
        self.init_legend()

        timer = QtCore.QTimer(self)
        QtCore.QObject.connect(timer, QtCore.SIGNAL("timeout()"), self.timer_event)
        timer.start(10)


    def init_vars(self):
        self.num_trials = 0
        self.reset_counters()
        self.msg_cnt = 0
        self.console_disp_cnt = 0


    def reset_counters(self):
        self.trial_sync = 0
        self.num_trials_postcalib = 0
        self.num_trial_started_postcalib = 0
        self.num_trial_givenup_postcalib = 0
        self.num_trial_successful_postcalib = 0
        self.shadow_num_trial_started_postcalib = 0
        self.shadow_num_trial_givenup_postcalib = 0
        self.shadow_num_trial_successful_postcalib = 0
        self.started_window = []
        self.givenup_window = []
        self.success_window = []
        self.shadow_started_window = []
        self.shadow_givenup_window = []
        self.shadow_success_window = []
        self.percent_start = 0
        self.percent_success = 0
        self.percent_givenup = 0
        self.hist_narrow_SUR = []
        self.hist_narrow_GUR = []
        self.hist_narrow_STR = []

        self.hist_wide_SUR = []
        self.hist_wide_GUR = []
        self.hist_wide_STR = []

    def update_gui_label_data(self):
        self.parent.GALL.setText("%d" % self.num_trials_postcalib)
        self.parent.GSTR.setText("%d" % self.num_trial_started_postcalib) 
        self.parent.GGUR.setText("%d" % self.num_trial_givenup_postcalib) 
        self.parent.GSUR.setText("%d" % self.num_trial_successful_postcalib) 


    #def reload_config(self):
    #    self.load_config()
    #    for ax in self.figure.axes:
    #        self.figure.delaxes(ax)
    #    self.figure.clear()
    #    self.draw()
    #    self.init_plot(True)
    #    self.init_legend()
    #    self.redraw_yticks = True

    #def load_config(self):
    #    self.config = ConfigObj(self.config_file, unrepr=True)

    def load_config(self):
        self.config = SafeConfigParser()
        self.config.read(self.config_file)
        self.window_narrow = self.config.getint('general', 'window_narrow')
        self.window_wide = self.config.getint('general', 'window_wide')
        self.task_state_codes = {}
        for k, v in self.config.items('task state codes'):
            self.task_state_codes[k] = int(v)


    def init_plot(self, clear=False):
        self.nDims = 3

        self.figure.subplots_adjust(bottom=.05, right=.98, left=.08, top=.98, hspace=0.07)

        self.ax = []
        self.old_size = []
        self.ax_bkg = []
        self.lines = []

        ax = self.figure.add_subplot(1,1,1)

        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width * 0.85, box.height])

        self.reset_axis(ax)
        self.draw()

        bbox_width = ax.bbox.width
        bbox_height = ax.bbox.height
        if clear == True:   # force to redraw
            bbox_width = 0
            bbox_height = 0

        self.old_size.append( (bbox_width, bbox_height) )
        self.ax_bkg.append(self.copy_from_bbox(ax.bbox))

        self.colors = ['k', 'r', 'g']
        self.styles = ['-', '-', '--']

        for d in range(self.nDims):
            for m in range(3):
                line, = ax.plot([], [], self.colors[d]+self.styles[m], lw=1.5, aa=True, animated=True)
                line.set_ydata([0, 0])
                line.set_xdata([0, 1])
                self.lines.append(line)
                self.draw()

        self.ax.append(ax)


    def reset_axis(self, ax): #, label):
        ax.grid(True)
        ax.set_ylim(-1, 101)
        ax.set_autoscale_on(False)
        ax.get_xaxis().set_ticks([])
        for tick in ax.get_yticklabels():
            tick.set_fontsize(9)


    def init_legend(self):
        legnd = []

        for d in range(self.nDims):
            for m in range(3):
                line = matplotlib.lines.Line2D([0,0], [0,0], color=self.colors[d], ls=self.styles[m], lw=1.5)
                legnd.append(line)

        legend_text = []
        legend_text.append('STR')
        legend_text.append('STR%d' % self.window_narrow)
        legend_text.append('STR%d' % self.window_wide)
        legend_text.append('GUR')
        legend_text.append('GUR%d' % self.window_narrow)
        legend_text.append('GUR%d' % self.window_wide)
        legend_text.append('SUR')
        legend_text.append('SUR%d' % self.window_narrow)
        legend_text.append('SUR%d' % self.window_wide)

        self.figure.legend(legnd, legend_text, loc = 'right', bbox_to_anchor=(1, 0.5),
                           frameon=False, labelspacing=1.5, prop={'size':'11'})
        self.draw()


    def timer_event(self):
        done = False
        while not done:
            msg = CMessage()
            rcv = self.mod.ReadMessage(msg, 0)
            if rcv == 1:
                msg_type = msg.GetHeader().msg_type

                # SESSION_CONFIG => start of session
                if msg_type == rc.MT_SESSION_CONFIG:
                    #self.msg_cnt += 1
                    self.num_trials = 0
                    self.reset_counters()
                    self.update_gui_label_data()


                # EM_DECODER_CONFIGURATION => end of an adaptation round
                elif msg_type == rc.MT_EM_DECODER_CONFIGURATION:
                    #self.msg_cnt += 1
                    self.reset_counters()
                    self.update_gui_label_data()

                # END_TASK_STATE => end of a task
                elif msg_type == rc.MT_END_TASK_STATE:
                    #self.msg_cnt += 1
                    mdf = rc.MDF_END_TASK_STATE()
                    copy_from_msg(mdf, msg)

                    # need to know:
                    #    begin task state code
                    #    final task state code
                    #    intertrial state code

                    if (mdf.id == 1):
                        self.trial_sync = 1
                        self.shadow_started_window.append(0)

                    if (mdf.id == self.task_state_codes['begin']) & (mdf.outcome == 1):
                        if self.trial_sync:
                            #print "*** trial started ***"
                            #self.rewards_given += 1
                            self.shadow_num_trial_started_postcalib += 1
                            self.shadow_success_window.append(0)
                            self.shadow_givenup_window.append(0)
                            self.shadow_started_window[-1] = 1

                    if mdf.reason == "JV_IDLE_TIMEOUT":
                        if self.trial_sync:
                            self.shadow_num_trial_givenup_postcalib += 1
                            self.shadow_givenup_window[-1] = 1

                    if (mdf.id == self.task_state_codes['final']) & (mdf.outcome == 1):
                        if self.trial_sync:
                            #print "*** trial complete and successful"
                            self.shadow_num_trial_successful_postcalib += 1
                            self.shadow_success_window[-1] = 1

                    if (mdf.id == self.task_state_codes['intertrial']):
                        if self.trial_sync:
                            # do end-of-trial stuff here
                            self.num_trials += 1
                            self.num_trials_postcalib += 1
                            self.num_trial_started_postcalib = self.shadow_num_trial_started_postcalib
                            self.num_trial_successful_postcalib = self.shadow_num_trial_successful_postcalib
                            self.num_trial_givenup_postcalib = self.shadow_num_trial_givenup_postcalib

                            if len(self.shadow_success_window) > self.window_wide: #self.window_narrow:
                                self.shadow_success_window.pop(0)

                            if len(self.shadow_givenup_window) > self.window_wide: #self.window_narrow:
                                self.shadow_givenup_window.pop(0)

                            if len(self.shadow_started_window) > self.window_wide: #self.window_narrow:
                                self.shadow_started_window.pop(0)

                            self.success_window = copy.deepcopy(self.shadow_success_window)
                            self.started_window = copy.deepcopy(self.shadow_started_window)
                            self.givenup_window = copy.deepcopy(self.shadow_givenup_window)

                            if self.num_trials_postcalib > 0:
                                self.percent_start = 100 * self.num_trial_started_postcalib / self.num_trials_postcalib
                                self.percent_givenup = 100 * self.num_trial_givenup_postcalib / self.num_trials_postcalib
                                self.percent_success = 100 * self.num_trial_successful_postcalib / self.num_trials_postcalib


                            percent_success_wide_window = np.NAN
                            if len(self.success_window) >= self.window_wide:
                                num_success_window = np.sum(self.success_window)
                                percent_success_wide_window = 100 * num_success_window / len(self.success_window)

                            percent_givenup_wide_window = np.NAN
                            if len(self.givenup_window) >= self.window_wide:
                                num_givenup_window = np.sum(self.givenup_window)
                                percent_givenup_wide_window = 100 * num_givenup_window / len(self.givenup_window)

                            percent_started_wide_window = np.NAN
                            if len(self.started_window) >= self.window_wide:
                                num_started_window = np.sum(self.started_window)
                                percent_started_wide_window = 100 * num_started_window / len(self.started_window)

                            percent_success_narrow_window = np.NAN
                            if len(self.success_window) >= self.window_narrow:
                                success_window_narrow = self.success_window[len(self.success_window)-self.window_narrow:]
                                num_success_window = np.sum(success_window_narrow)
                                percent_success_narrow_window = 100 * num_success_window / len(success_window_narrow)

                            percent_givenup_narrow_window = np.NAN
                            if len(self.givenup_window) >= self.window_narrow:
                                givenup_window_narrow = self.givenup_window[len(self.givenup_window)-self.window_narrow:]
                                num_givenup_window = np.sum(givenup_window_narrow)
                                percent_givenup_narrow_window = 100 * num_givenup_window / len(givenup_window_narrow)

                            if len(self.started_window) >= self.window_narrow:
                                started_window_narrow = self.started_window[len(self.started_window)-self.window_narrow:]
                                num_started_window = np.sum(started_window_narrow)
                                percent_started_narrow_window = 100 * num_started_window / len(started_window_narrow)
                                self.hist_narrow_STR.append(percent_started_narrow_window)
                                self.hist_narrow_SUR.append(percent_success_narrow_window)
                                self.hist_narrow_GUR.append(percent_givenup_narrow_window)

                                self.hist_wide_STR.append(percent_started_wide_window)
                                self.hist_wide_SUR.append(percent_success_wide_window)
                                self.hist_wide_GUR.append(percent_givenup_wide_window)

                            self.update_gui_label_data()


                elif msg_type == rc.MT_PING:
                    respond_to_ping(self.mod, msg, 'TrialStatusDisplay')

                elif msg_type == MT_EXIT:
                    self.exit()
                    done = True

            else:
                done = True

                self.console_disp_cnt += 1
                if self.console_disp_cnt == 50:
                    self.update_plot()
                    self.console_disp_cnt = 0


    def update_plot(self):

        #print "All trials : %d" % (self.num_trials_postcalib)
        #print ""
        #print "GSTR: ", self.percent_start
        #print "GGUR: ", self.percent_givenup
        #print "GSUR: ", self.percent_success
        #print ""
        #print "STR win: ", self.started_window
        #print "GUP win: ", self.givenup_window
        #print "SUC win: ", self.success_window
        #print ""
        #print "nSTR: ", self.hist_narrow_STR
        #print "nGUR: ", self.hist_narrow_GUR
        #print "nSUR :", self.hist_narrow_SUR
        #print ""
        #print "wSTR: ", self.hist_wide_STR
        #print "wGUR: ", self.hist_wide_GUR
        #print "wSUR :", self.hist_wide_SUR
        #print ""
        #print "Msg cnt    : %d" % (self.msg_cnt)
        #print "\n ----------------------- \n"

        i = 0
        ax = self.ax[i]
        current_size = ax.bbox.width, ax.bbox.height
        if self.old_size[i] != current_size:
            self.old_size[i] = current_size
            self.draw()
            self.ax_bkg[i] = self.copy_from_bbox(ax.bbox)
        self.restore_region(self.ax_bkg[i])

        #if len(self.hist_narrow_STR) > 1:
        if not self.hist_narrow_STR:
            self.lines[0].set_ydata([self.percent_start, self.percent_start])
            self.lines[0].set_xdata([0, 1])
            ax.draw_artist(self.lines[0])

            self.lines[3].set_ydata([self.percent_givenup, self.percent_givenup])
            self.lines[3].set_xdata([0, 1])
            ax.draw_artist(self.lines[3])

            self.lines[6].set_ydata([self.percent_success, self.percent_success])
            self.lines[6].set_xdata([0, 1])
            ax.draw_artist(self.lines[6])

        else:
            ax.set_xlim(0, len(self.hist_narrow_STR)-1)

            for k in range(0,9):
                self.lines[k].set_xdata(range(len(self.hist_narrow_STR)))

            self.lines[0].set_ydata([self.percent_start, self.percent_start])
            self.lines[0].set_xdata([0, len(self.hist_narrow_STR)])
            self.lines[1].set_ydata(self.hist_narrow_STR)
            self.lines[2].set_ydata(self.hist_wide_STR)

            ###

            self.lines[3].set_ydata([self.percent_givenup, self.percent_givenup])
            self.lines[3].set_xdata([0, len(self.hist_narrow_STR)])
            self.lines[4].set_ydata(self.hist_narrow_GUR)
            self.lines[5].set_ydata(self.hist_wide_GUR)

            ###

            self.lines[6].set_ydata([self.percent_success, self.percent_success])
            self.lines[6].set_xdata([0, len(self.hist_narrow_STR)])
            self.lines[7].set_ydata(self.hist_narrow_SUR)
            self.lines[8].set_ydata(self.hist_wide_SUR)

            for k in range(0,9):
                ax.draw_artist(self.lines[k])

        self.blit(ax.bbox)

        # need to redraw once to update y-ticks
        if self.redraw_yticks == True:
            self.draw()
            self.redraw_yticks = False


    def exit(self):
        print "exiting"
        self.parent.exit_app()

    def stop(self):
        print 'disconnecting'
        self.mod.SendSignal(rc.MT_EXIT_ACK)
        self.mod.DisconnectFromMMM()
yValues0 = [6,7.5,8,7.5]
yValues1 = [5.5,6.5,50,6]           # one very high value (50)
yValues2 = [6.5,7,8,7]

axis.set_ylim(5, 8)                 # limit the vertical display

t0, = axis.plot(xValues, yValues0)
t1, = axis.plot(xValues, yValues1)
t2, = axis.plot(xValues, yValues2)

axis.set_ylabel('Vertical Label')
axis.set_xlabel('Horizontal Label')

axis.grid()
          
fig.legend((t0, t1, t2), ('First line', 'Second line', 'Third line'), 'upper right')

#--------------------------------------------------------------
def _destroyWindow():
    root.quit()
    root.destroy() 
#--------------------------------------------------------------
root = tk.Tk() 
root.withdraw()
root.protocol('WM_DELETE_WINDOW', _destroyWindow)   
#--------------------------------------------------------------  
canvas = FigureCanvasTkAgg(fig, master=root)
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)         
#--------------------------------------------------------------  
root.update()
root.deiconify()
Ejemplo n.º 43
0
def plot_linear_relation(x, y, x_err=None, y_err=None, title=None, point_label=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, y_2_label=None, marker_style='-o', log_x=False, log_y=False, size=None, filename=None):
    ''' Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation to this line is also plotted, showing the offset.

     Parameters
    ----------
    x, y, x_err, y_err: iterable

    filename: string, PdfPages object or None
        PdfPages file object: plot is appended to the pdf
        string: new plot file with the given filename is created
        None: the plot is printed to screen
    '''
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if x_err is not None:
        x_err = [x_err, x_err]
    if y_err is not None:
        y_err = [y_err, y_err]
    ax.set_title(title)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.set_xscale('log')
    if log_y:
        ax.set_yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        fig.legend(legend, 0)
    ax.grid(True)
    ax.errorbar(x, y, xerr=x_err, yerr=y_err, fmt='o', color='black')  # plot points
    # label points if needed
    if point_label is not None:
        for X, Y, Z in zip(x, y, point_label):
            ax.annotate('{}'.format(Z), xy=(X, Y), xytext=(-5, 5), ha='right', textcoords='offset points')
    line_fit, _ = np.polyfit(x, y, 1, full=False, cov=True)
    fit_fn = np.poly1d(line_fit)
    ax.plot(x, fit_fn(x), '-', lw=2, color='gray')
    setp(ax.get_xticklabels(), visible=False)  # remove ticks at common border of both plots

    divider = make_axes_locatable(ax)
    ax_bottom_plot = divider.append_axes("bottom", 2.0, pad=0.0, sharex=ax)

    ax_bottom_plot.bar(x, y - fit_fn(x), align='center', width=np.amin(np.diff(x)) / 2, color='gray')
#     plot(x, y - fit_fn(x))
    ax_bottom_plot.grid(True)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_2_label is not None:
        ax.set_ylabel(y_2_label)

    ax.set_ylim((-np.amax(np.abs(y - fit_fn(x)))), (np.amax(np.abs(y - fit_fn(x)))))

    ax.plot(ax.set_xlim(), [0, 0], '-', color='black')
    setp(ax_bottom_plot.get_yticklabels()[-2:-1], visible=False)

    if size is not None:
        fig.set_size_inches(size)

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    elif filename:
        fig.savefig(filename, bbox_inches='tight')

    return fig
Ejemplo n.º 44
0
class Plot_Traces(Tk.Tk):
    def __init__(self, root, folder):
        Tk.Tk.__init__(self)
        self.title("traces - " + folder)

        self.root = root
        self.folder = folder
        self.protocol("WM_DELETE_WINDOW", self.closeGUI)
        self.createTracesGUI()

    def createTracesGUI(self):

        # declare button variables
        # control variables for neuron
        self.neuronNumber = Tk.StringVar()
        self.Vm_neuron = Tk.BooleanVar()
        self.g_excit = Tk.BooleanVar()
        self.g_inhib = Tk.BooleanVar()
        self.G_ref = Tk.BooleanVar()
        self.BPAP = Tk.BooleanVar()
        self.spikesSelf = Tk.BooleanVar()
        self.spikesTC = Tk.BooleanVar()
        self.spikesRS = Tk.BooleanVar()
        self.spikesFS = Tk.BooleanVar()
        self.neuronAvail = True

        # control variables for synapses
        self.synapseNumber = Tk.StringVar()
        self.Vm_syn = Tk.BooleanVar()
        self.g = Tk.BooleanVar()
        self.calcium = Tk.BooleanVar()
        self.Mg = Tk.BooleanVar()
        self.I_syn = Tk.BooleanVar()
        self.I_NMDA = Tk.BooleanVar()
        self.I_VGCC = Tk.BooleanVar()
        self.P = Tk.BooleanVar()
        self.B = Tk.BooleanVar()
        self.D = Tk.BooleanVar()
        self.V = Tk.BooleanVar()

        # control variables for axes
        self.y_min = Tk.StringVar()
        self.y_max = Tk.StringVar()
        self.x_min = Tk.StringVar()
        self.x_max = Tk.StringVar()
        self.step_y = 10
        #         self.step_x        = 100
        self.offValue = False  # False = use provided values
        self.legend = False  # True = display label info

        # create plotframe widget
        mainFrame = Tk.Frame(self)
        mainFrame.grid(column=0, row=0)
        plotFrame = Tk.Frame(mainFrame, borderwidth=5, relief="sunken", width=500, height=500)
        plotFrame.grid(column=0, row=0, columnspan=3, rowspan=2, sticky=(N, W, E), padx=(10, 10), pady=(10, 10))
        selectionFrame = Tk.Frame(mainFrame, borderwidth=5, relief="sunken", width=500, height=125)
        selectionFrame.grid(column=0, row=3, columnspan=7, rowspan=5, sticky=(N, S, E, W), padx=(10, 10), pady=(10, 10))

        # create main figure
        self.mainFig = Figure()

        # create main plot canvas
        self.canvas = FigureCanvasTkAgg(self.mainFig, master=plotFrame)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        # create control for neuron variables
        Tk.Label(selectionFrame, text="neuron: ").grid(column=0, row=0, sticky=(W))
        self.neuronInput = Tk.Entry(selectionFrame, textvariable=self.neuronNumber, width=11)
        self.neuronInput.grid(column=1, row=0, sticky=(W))
        self.neuronNumber.set("0")
        self.neuronInput.insert(0, "0")
        self.neuronInput.bind("<Return>", self.renewCanvas)
        self.neuronInput.bind("<Up>", lambda unit: self.nextUnit("neuron", +1))
        self.neuronInput.bind("<Down>", lambda unit: self.nextUnit("neuron", -1))

        check = Tk.Checkbutton(
            selectionFrame,
            text="neuron Vm",
            command=lambda: self.checked(self.Vm_neuron),
            variable=self.Vm_neuron,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=0, row=1, sticky=(W), padx=(0, 10))
        self.Vm_neuron.set(False)

        check = Tk.Checkbutton(
            selectionFrame,
            text="g excit",
            command=lambda: self.checked(self.g_excit),
            variable=self.g_excit,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=0, row=2, sticky=(W))
        self.g_excit.set(False)

        check = Tk.Checkbutton(
            selectionFrame,
            text="g inhib",
            command=lambda: self.checked(self.g_inhib),
            variable=self.g_inhib,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=0, row=3, sticky=(W))
        self.g_inhib.set(False)

        check = Tk.Checkbutton(
            selectionFrame,
            text="G ref",
            command=lambda: self.checked(self.G_ref),
            variable=self.G_ref,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=0, row=4, sticky=(W))
        self.G_ref.set(False)

        check = Tk.Checkbutton(
            selectionFrame,
            text="BPAP",
            command=lambda: self.checked(self.BPAP),
            variable=self.BPAP,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=0, row=5, sticky=(W))
        self.BPAP.set(False)

        check = Tk.Checkbutton(
            selectionFrame,
            text="spikes",
            command=lambda: self.checked(self.spikesSelf),
            variable=self.spikesSelf,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=1, row=1, sticky=(W), padx=(0, 10))
        self.spikesSelf.set(False)

        check = Tk.Checkbutton(
            selectionFrame,
            text="spikes TC",
            command=lambda: self.checked(self.spikesTC),
            variable=self.spikesTC,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=1, row=2, sticky=(W))
        self.spikesTC.set(False)

        check = Tk.Checkbutton(
            selectionFrame,
            text="spikes RS",
            command=lambda: self.checked(self.spikesRS),
            variable=self.spikesRS,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=1, row=3, sticky=(W))
        self.spikesRS.set(False)

        check = Tk.Checkbutton(
            selectionFrame,
            text="spikes FS",
            command=lambda: self.checked(self.spikesFS),
            variable=self.spikesFS,
            onvalue=True,
            offvalue=False,
        )
        check.grid(column=1, row=4, sticky=(W))
        self.spikesFS.set(False)

        s = ttk.Separator(selectionFrame, orient=VERTICAL)
        s.grid(column=2, row=0, rowspan=6, sticky="snew", pady=(2, 2), padx=(2, 3))

        # create controls for synapse variables
        Tk.Label(selectionFrame, text="synapse: ").grid(column=3, row=0, sticky=(W))
        self.synapseInput = Tk.Entry(selectionFrame, textvariable=self.synapseNumber, width=14)
        self.synapseInput.grid(column=4, row=0, columnspan=2, sticky=(W))
        self.synapseNumber.set("0")
        self.synapseInput.insert(0, "0")
        self.synapseInput.bind("<Return>", self.renewCanvas)
        self.synapseInput.bind("<Up>", lambda unit: self.nextUnit("synapse", +1))
        self.synapseInput.bind("<Down>", lambda unit: self.nextUnit("synapse", -1))

        self.CB_Vm_syn = Tk.Checkbutton(
            selectionFrame,
            text="syn Vm",
            command=lambda: self.checked(self.Vm_syn),
            variable=self.Vm_syn,
            onvalue=True,
            offvalue=False,
        )
        self.CB_Vm_syn.grid(column=3, row=1, sticky=(W), padx=(0, 10))
        self.Vm_syn.set(False)

        self.CB_g = Tk.Checkbutton(
            selectionFrame,
            text="g syn",
            command=lambda: self.checked(self.g),
            variable=self.g,
            onvalue=True,
            offvalue=False,
        )
        self.CB_g.grid(column=3, row=2, sticky=(W))
        self.g.set(False)

        self.CB_calcium = Tk.Checkbutton(
            selectionFrame,
            text="calcium",
            command=lambda: self.checked(self.calcium),
            variable=self.calcium,
            onvalue=True,
            offvalue=False,
        )
        self.CB_calcium.grid(column=3, row=3, sticky=(W))
        self.calcium.set(False)

        self.CB_Mg = Tk.Checkbutton(
            selectionFrame,
            text="Mg",
            command=lambda: self.checked(self.Mg),
            variable=self.Mg,
            onvalue=True,
            offvalue=False,
        )
        self.CB_Mg.grid(column=3, row=4, sticky=(W))
        self.Mg.set(False)

        self.CB_I_syn = Tk.Checkbutton(
            selectionFrame,
            text="I syn",
            command=lambda: self.checked(self.I_syn),
            variable=self.I_syn,
            onvalue=True,
            offvalue=False,
        )
        self.CB_I_syn.grid(column=4, row=1, sticky=(W))
        self.I_syn.set(False)

        self.CB_I_NMDA = Tk.Checkbutton(
            selectionFrame,
            text="I NMDA",
            command=lambda: self.checked(self.I_NMDA),
            variable=self.I_NMDA,
            onvalue=True,
            offvalue=False,
        )
        self.CB_I_NMDA.grid(column=4, row=2, sticky=(W), padx=(0, 10))
        self.I_NMDA.set(False)

        self.CB_I_VGCC = Tk.Checkbutton(
            selectionFrame,
            text="I VGCC",
            command=lambda: self.checked(self.I_VGCC),
            variable=self.I_VGCC,
            onvalue=True,
            offvalue=False,
        )
        self.CB_I_VGCC.grid(column=4, row=3, sticky=(W))
        self.I_VGCC.set(False)

        self.CB_P = Tk.Checkbutton(
            selectionFrame,
            text="P",
            command=lambda: self.checked(self.P),
            variable=self.P,
            onvalue=True,
            offvalue=False,
        )
        self.CB_P.grid(column=5, row=1, sticky=(W), padx=(0, 10))
        self.P.set(False)

        self.CB_B = Tk.Checkbutton(
            selectionFrame,
            text="B",
            command=lambda: self.checked(self.B),
            variable=self.B,
            onvalue=True,
            offvalue=False,
        )
        self.CB_B.grid(column=5, row=2, sticky=(W), padx=(0, 10))
        self.B.set(False)

        self.CB_D = Tk.Checkbutton(
            selectionFrame,
            text="D",
            command=lambda: self.checked(self.D),
            variable=self.D,
            onvalue=True,
            offvalue=False,
        )
        self.CB_D.grid(column=5, row=3, sticky=(W), padx=(0, 10))
        self.D.set(False)

        self.CB_V = Tk.Checkbutton(
            selectionFrame,
            text="V",
            command=lambda: self.checked(self.V),
            variable=self.V,
            onvalue=True,
            offvalue=False,
        )
        self.CB_V.grid(column=5, row=4, sticky=(W), padx=(0, 10))
        self.V.set(False)

        s = ttk.Separator(selectionFrame, orient=VERTICAL)
        s.grid(column=6, row=0, rowspan=6, sticky="snew", pady=(2, 2), padx=(2, 3))

        # create controls for time variables
        self.offButton = Tk.Button(selectionFrame, command=self.disable, width=3)
        self.offButton.grid(column=7, row=0, rowspan=2, sticky=(N, S))

        self.y_upButton = Tk.Button(selectionFrame, text="^", command=lambda: self.move("y_up"), width=3)
        self.y_upButton.grid(column=8, row=0)

        self.y_downButton = Tk.Button(selectionFrame, text="v", command=lambda: self.move("y_down"), width=3)
        self.y_downButton.grid(column=8, row=1)

        self.ymaxInput = Tk.Entry(selectionFrame, textvariable=self.y_max, width=8)
        self.ymaxInput.grid(column=9, row=0, columnspan=2, sticky=(E, W))
        self.y_max.set("80")
        self.ymaxInput.insert(0, self.y_max.get())
        self.ymaxInput.bind("<Return>", self.moveReturn)

        self.yminInput = Tk.Entry(selectionFrame, textvariable=self.y_min, width=8)
        self.yminInput.grid(column=9, row=1, columnspan=2, sticky=(E, W))
        self.y_min.set("-100")
        self.yminInput.insert(0, self.y_min.get())
        self.yminInput.bind("<Return>", self.moveReturn)

        s = ttk.Separator(selectionFrame, orient=HORIZONTAL)
        s.grid(column=7, row=2, columnspan=5, sticky="nsew", pady=(2, 2), padx=(2, 2))

        self.xminInput = Tk.Entry(selectionFrame, textvariable=self.x_min, width=12)
        self.xminInput.grid(column=7, row=3, columnspan=2, sticky=(E, W))
        self.x_min.set("0")
        self.xminInput.insert(0, self.x_min.get())
        self.xminInput.bind("<Return>", self.moveReturn)

        self.xmaxInput = Tk.Entry(selectionFrame, textvariable=self.x_max, width=12)
        self.xmaxInput.grid(column=9, row=3, columnspan=2, sticky=(E, W))
        self.x_max.set("200")
        self.xmaxInput.insert(0, self.x_max.get())
        self.xmaxInput.bind("<Return>", self.moveReturn)

        button = Tk.Button(selectionFrame, text="<", command=lambda: self.move("x_left"), width=6)
        button.grid(column=7, row=4, columnspan=2, sticky=(E, W))

        button = Tk.Button(selectionFrame, text=">", command=lambda: self.move("x_right"), width=6)
        button.grid(column=9, row=4, columnspan=2, sticky=(E, W))

        self.legendButton = Tk.Button(selectionFrame, text="info ON", command=self.legendClicked, width=6)
        self.legendButton.grid(column=7, row=5, columnspan=2, sticky=(EW))

        self.offValue = not self.offValue
        self.disable()

    #         self.renewCanvas(False)

    def legendClicked(self):
        self.legend = not self.legend
        if self.legend:
            self.legendButton.config(text="info OFF")
        else:
            self.legendButton.config(text="info ON")
        self.renewCanvas(False)

    def checked(self, var):
        var.set(not var.get())
        self.renewCanvas(False)

    def disable(self):
        self.offValue = not self.offValue
        if self.offValue:
            self.offButton.config(text="ON")
            self.y_upButton.config(state=DISABLED)
            self.y_downButton.config(state=DISABLED)
            self.yminInput.config(state=DISABLED)
            self.ymaxInput.config(state=DISABLED)
        else:
            self.offButton.config(text="OFF")
            self.y_upButton.config(state=NORMAL)
            self.y_downButton.config(state=NORMAL)
            self.yminInput.config(state=NORMAL)
            self.ymaxInput.config(state=NORMAL)

            self.yminInput.delete(0, END)
            self.yminInput.insert(0, self.y_min.get())

            self.ymaxInput.delete(0, END)
            self.ymaxInput.insert(0, self.y_max.get())
        self.renewCanvas(False)

    def moveReturn(self, event):
        self.y_min.set(self.yminInput.get())
        self.y_max.set(self.ymaxInput.get())
        self.x_min.set(self.xminInput.get())
        self.x_max.set(self.xmaxInput.get())
        self.renewCanvas(False)

    def move(self, moveDir):
        self.step_x = int((float(self.x_max.get()) - float(self.x_min.get())) / 4)
        if moveDir == "y_up":
            self.y_min.set(str(int(self.y_min.get()) + self.step_y))
            self.y_max.set(str(int(self.y_max.get()) + self.step_y))
        if moveDir == "y_down":
            self.y_min.set(str(int(self.y_min.get()) - self.step_y))
            self.y_max.set(str(int(self.y_max.get()) - self.step_y))
        if moveDir == "x_left":
            self.x_min.set(str(int(self.x_min.get()) - self.step_x))
            self.x_max.set(str(int(self.x_max.get()) - self.step_x))
        if moveDir == "x_right":
            self.x_min.set(str(int(self.x_min.get()) + self.step_x))
            self.x_max.set(str(int(self.x_max.get()) + self.step_x))

        self.yminInput.delete(0, END)
        self.yminInput.insert(0, self.y_min.get())

        self.ymaxInput.delete(0, END)
        self.ymaxInput.insert(0, self.y_max.get())

        self.xminInput.delete(0, END)
        self.xminInput.insert(0, self.x_min.get())

        self.xmaxInput.delete(0, END)
        self.xmaxInput.insert(0, self.x_max.get())

        self.renewCanvas(False)

    def nextUnit(self, unit, d):
        if unit == "synapse":
            newNumber = int(self.synapseNumber.get()) + d
            if newNumber >= 0 and newNumber < self.root.neurons[self.folder]["TC"].size:
                self.synapseNumber.set(str(newNumber))
                self.synapseInput.delete(0, END)
                self.synapseInput.insert(0, self.synapseNumber.get())
            else:
                self.mainFig.text(
                    0.5,
                    0.5,
                    "synapse out-of-bound",
                    bbox=dict(facecolor="red", alpha=0.8),
                    horizontalalignment="center",
                    verticalalignment="center",
                )
                self.canvas.show()
        if (
            unit == "neuron"
        ):  # if the neuron that is looked at now doesn't have synapse info, than jump to next neuron; else jump to next neuron with synapse info
            if self.neuronNumber.get() not in self.root.genParam[self.folder]["neuronsToTrack"]:
                newNumber = int(self.neuronNumber.get()) + d
                if newNumber >= 0 and newNumber < np.size(
                    self.root.neurons[self.folder]["RS"].g_excit, 0
                ):  # makes sure that index won't go out of bound
                    self.neuronNumber.set(str(newNumber))
                    self.neuronInput.delete(0, END)
                    self.neuronInput.insert(0, self.neuronNumber.get())
                else:
                    self.mainFig.text(
                        0.5,
                        0.5,
                        "neuron out-of-bound",
                        bbox=dict(facecolor="red", alpha=0.8),
                        horizontalalignment="center",
                        verticalalignment="center",
                    )
                    self.canvas.show()
            else:
                index = self.root.genParam[self.folder]["neuronsToTrack"].index(self.neuronNumber.get())
                if index + d >= 0 and index + d < np.size(
                    self.root.genParam[self.folder]["neuronsToTrack"]
                ):  # makes sure that index won't go out of bound
                    self.neuronNumber.set(str(int(self.root.genParam[self.folder]["neuronsToTrack"][index + d])))
                    self.neuronInput.delete(0, END)
                    self.neuronInput.insert(0, self.neuronNumber.get())
                else:
                    self.mainFig.text(
                        0.5,
                        0.5,
                        "neuron out-of-bound",
                        bbox=dict(facecolor="red", alpha=0.8),
                        horizontalalignment="center",
                        verticalalignment="center",
                    )
                    self.canvas.show()
        self.renewCanvas(False)

    def rasterPlotSelf(self, n):
        spikesRS = np.argwhere(self.root.neurons[self.folder]["RS"].spikeTimes[n, :])
        self.plt.plot(
            spikesRS * self.root.genParam[self.folder]["dt"],
            (self.root.neurons[self.folder]["TC"].size + 5) * np.ones(len(spikesRS)),
            "d",
            markerfacecolor="y",
            markeredgecolor="k",
            markeredgewidth=2,
            markersize=6,
        )

    def rasterPlotTC(self, pop):
        colorPlot = np.array(["k" for neuron in range(self.root.neurons[self.folder][pop].size)])
        colorPlot[self.root.genParam[self.folder]["allPats"]["pat1"]] = "r"
        colorPlot[self.root.genParam[self.folder]["allPats"]["pat2"]] = "b"
        colorPlot[self.root.genParam[self.folder]["allPats"]["pat3"]] = "y"
        colorPlot[self.root.genParam[self.folder]["allPats"]["pat4"]] = "c"
        for neuron in range(self.root.neurons[self.folder][pop].size):
            spikes = np.argwhere(self.root.neurons[self.folder][pop].spikeTimes[neuron, :])
            self.plt.scatter(
                spikes * self.root.genParam[self.folder]["dt"],
                neuron * np.ones(len(spikes)),
                marker="d",
                color=colorPlot[neuron],
            )

    def rasterPlotRSFS(self, pop):
        colorPlot = {"RS": "|r", "FS": "|b"}
        compress = 0.5
        offSet = self.root.neurons[self.folder]["TC"].size + 10
        if pop == "FS":
            offSet += self.root.neurons[self.folder]["TC"].size * compress + 5
        for neuron in range(self.root.neurons[self.folder][pop].size):
            spikes = np.argwhere(self.root.neurons[self.folder][pop].spikeTimes[neuron, :])
            self.plt.plot(
                spikes * self.root.genParam[self.folder]["dt"],
                neuron * np.ones(len(spikes)) * compress + offSet,
                colorPlot[pop],
            )

    def renewCanvas(self, event):
        # clear previous figure
        self.mainFig.clf()
        self.plt = self.mainFig.add_subplot(111)

        # get input variables
        self.neuronNumber.set(self.neuronInput.get())
        self.synapseNumber.set(self.synapseInput.get())

        n, s = self.checkAvail(int(self.neuronNumber.get()), int(self.synapseNumber.get()))

        # plot variables
        p1 = p2 = p3 = p4 = p5 = p6 = p7 = p8 = p9 = p10 = p11 = p12 = p13 = p14 = p15 = []
        # neuron variables:
        if self.Vm_neuron.get():
            p1, = self.plt.plot(
                self.root.genParam[self.folder]["timeArray"], self.root.neurons[self.folder]["RS"].Vm[n, :], "k"
            )
        if self.g_excit.get():
            p2, = self.plt.plot(
                self.root.genParam[self.folder]["timeArray"], self.root.neurons[self.folder]["RS"].g_excit[n, :], "r"
            )
        if self.g_inhib.get():
            p3, = self.plt.plot(
                self.root.genParam[self.folder]["timeArray"], self.root.neurons[self.folder]["RS"].g_inhib[n, :], "b"
            )
        if self.G_ref.get():
            p4, = self.plt.plot(
                self.root.genParam[self.folder]["timeArray"], self.root.neurons[self.folder]["RS"].Gref[n, :] * 8, "k"
            )
        if self.BPAP.get():
            p4, = self.plt.plot(
                self.root.genParam[self.folder]["timeArray"], self.root.neurons[self.folder]["RS"].BPAP[n, :] * 30, "k"
            )
        if self.spikesSelf.get():
            self.rasterPlotSelf(n)
        if self.spikesTC.get():
            self.rasterPlotTC("TC")
        if self.spikesRS.get():
            self.rasterPlotRSFS("RS")
        if self.spikesFS.get():
            self.rasterPlotRSFS("FS")

        # synapse variables
        if self.neuronAvail:
            if self.Vm_syn.get():
                p5, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"], self.root.synapses[self.folder][str(n)].Vm[s, :], "k"
                )
            if self.g.get():
                p6, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].g[s, :] * 100,
                    "k",
                )
            if self.calcium.get():
                p7, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].calcium[s, :] * 8,
                    "k",
                )
            if self.Mg.get():
                p8, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].Mg[s, :] * 50,
                    "k",
                )
            if self.I_syn.get():
                p9, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].I[s, :] * 5,
                    "k",
                )
            if self.I_NMDA.get():
                p10, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].I_NMDA[s, :] * 50,
                    "k",
                )
            if self.I_VGCC.get():
                p11, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].I_VGCC[s, :] * 50,
                    "k",
                )
            if self.P.get():
                p12, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].P[s, :] * 1000,
                    "k",
                )
            if self.B.get():
                p13, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].B[s, :] * 10,
                    "k",
                )
            if self.D.get():
                p14, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].D[s, :] * 500,
                    "k",
                )
            if self.V.get():
                p15, = self.plt.plot(
                    self.root.genParam[self.folder]["timeArray"],
                    self.root.synapses[self.folder][str(n)].V[s, :] * 30,
                    "k",
                )

        # plot parameters
        self.plt.set_xlabel("time (ms)")
        self.plt.set_xlim(int(self.x_min.get()), int(self.x_max.get()))
        if not self.offValue:
            self.plt.set_ylim(int(self.y_min.get()), int(self.y_max.get()))
        # make plot legend
        legendPlots = np.array([p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15])
        legendNames = np.array(
            [
                "Vm",
                "g excit",
                "g inhib",
                "G ref",
                "Vm syn",
                "g",
                "calcium",
                "Mg",
                "I syn",
                "I NMDA",
                "I VGCC",
                "P",
                "V",
                "B",
                "D",
            ]
        )
        legendMask = np.array(
            map(
                bool,
                [
                    self.Vm_neuron.get(),
                    self.g_excit.get(),
                    self.g_inhib.get(),
                    self.G_ref.get(),
                    self.Vm_syn.get(),
                    self.g.get(),
                    self.calcium.get(),
                    self.Mg.get(),
                    self.I_syn.get(),
                    self.I_NMDA.get(),
                    self.I_VGCC.get(),
                    self.P.get(),
                    self.V.get(),
                    self.B.get(),
                    self.D.get(),
                ],
            )
        )
        if self.legend:
            self.mainFig.legend(legendPlots[legendMask], legendNames[legendMask], mode="expand", ncol=6)

        self.canvas.show()

    def checkAvail(self, n, s):
        # check for out-of-bound neuron
        if n >= np.size(self.root.neurons[self.folder]["RS"].g_excit, 0):
            n = np.size(self.root.neurons[self.folder]["RS"].g_excit, 0) - 1
            self.neuronNumber.set(str(n))
            self.neuronInput.delete(0, END)
            self.neuronInput.config(foreground="red")
            self.neuronInput.insert(0, str(n))
            self.mainFig.text(
                0.5,
                0.5,
                "neuron out-of-bound",
                bbox=dict(facecolor="red", alpha=0.8),
                horizontalalignment="center",
                verticalalignment="center",
            )
            self.canvas.show()
        else:
            self.neuronInput.config(foreground="black")

        # check for out-of-bound neuron
        if s >= self.root.neurons[self.folder]["TC"].size:
            s = self.root.neurons[self.folder]["TC"].size - 1
            self.synapseNumber.set(str(s))
            self.synapseInput.delete(0, END)
            self.synapseInput.config(foreground="red")
            self.synapseInput.insert(0, str(s))
            self.mainFig.text(
                0.5,
                0.5,
                "synapse out-of-bound",
                bbox=dict(facecolor="red", alpha=0.8),
                horizontalalignment="center",
                verticalalignment="center",
            )
            self.canvas.show()
        else:
            self.synapseInput.config(foreground="black")

        # check for neuron with unavailable synapse information
        if self.neuronNumber.get() not in self.root.genParam[self.folder]["neuronsToTrack"]:
            tt = "synapse information not available; use neurons "
            for k in self.root.genParam[self.folder]["neuronsToTrack"]:
                tt += k + " "
            self.mainFig.text(0.02, 0.95, tt, bbox=dict(facecolor="red", alpha=0.35))
            self.canvas.show()
            self.neuronAvail = False
            self.CB_Vm_syn.config(state=DISABLED)
            self.CB_g.config(state=DISABLED)
            self.CB_calcium.config(state=DISABLED)
            self.CB_Mg.config(state=DISABLED)
            self.CB_I_syn.config(state=DISABLED)
            self.CB_I_NMDA.config(state=DISABLED)
            self.CB_I_VGCC.config(state=DISABLED)
            self.CB_P.config(state=DISABLED)
            self.CB_B.config(state=DISABLED)
            self.CB_D.config(state=DISABLED)
            self.CB_V.config(state=DISABLED)
            self.synapseInput.config(state=DISABLED)
        else:
            self.neuronAvail = True
            self.CB_Vm_syn.config(state=NORMAL)
            self.CB_g.config(state=NORMAL)
            self.CB_calcium.config(state=NORMAL)
            self.CB_Mg.config(state=NORMAL)
            self.CB_I_syn.config(state=NORMAL)
            self.CB_I_NMDA.config(state=NORMAL)
            self.CB_I_VGCC.config(state=NORMAL)
            self.CB_P.config(state=NORMAL)
            self.CB_B.config(state=NORMAL)
            self.CB_D.config(state=NORMAL)
            self.CB_V.config(state=NORMAL)
            self.synapseInput.config(state=NORMAL)

        return n, s

    def closeGUI(self, allGUI=False):
        if not allGUI:
            self.root.allGUI.remove(self)
        self.destroy()
Ejemplo n.º 45
0
class SimulationGui(QMainWindow):
    def __init__(self, net=None, parent=None, fname=None):
        QMainWindow.__init__(self)

        self.ui = Ui_SimulationWindow()
        self.ui.setupUi(self)

        if fname:
            self.set_title(fname)

        # context menu
        self.ui.nodeInspector.addAction(self.ui.actionCopyInspectorData)
        self.ui.nodeInspector.addAction(self.ui.actionShowLocalizedSubclusters)
        # callbacks
        self.ui.actionCopyInspectorData.activated\
            .connect(self.on_actionCopyInspectorData_triggered)
        self.ui.actionShowLocalizedSubclusters.activated\
            .connect(self.on_actionShowLocalizedSubclusters_triggered)

        self.dpi = 72
        # take size of networDisplayWidget
        self.fig = Figure((700 / self.dpi, 731 / self.dpi), self.dpi,
                          facecolor='0.9')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.ui.networkDisplayWidget)
        self.nav = NavigationToolbar(self.canvas, self.ui.networkDisplayWidget,
                                     coordinates=True)
        self.nav.setGeometry(QRect(0, 0, 651, 36))
        self.nav.setIconSize(QSize(24, 24))

        self.axes = self.fig.add_subplot(111)
        # matplotlib.org/api/figure_api.html#matplotlib.figure.SubplotParams
        self.fig.subplots_adjust(left=0.03, right=0.99, top=0.92)

        if net:
            self.init_sim(net)

        self.connect(self.ui.showNodes, SIGNAL('stateChanged(int)'),
                     self.refresh_visibility)
        self.connect(self.ui.showEdges, SIGNAL('stateChanged(int)'),
                     self.refresh_visibility)
        self.connect(self.ui.showMessages, SIGNAL('stateChanged(int)'),
                     self.refresh_visibility)
        self.connect(self.ui.showLabels, SIGNAL('stateChanged(int)'),
                     self.refresh_visibility)
        self.connect(self.ui.redrawNetworkButton, SIGNAL('clicked(bool)'),
                     self.redraw)
        self.connect(self.ui.treeGroupBox, SIGNAL('toggled(bool)'),
                     self.refresh_visibility)
        self.connect(self.ui.treeKey, SIGNAL('textEdited(QString)'),
                     self.redraw)
        self.connect(self.ui.propagationError, SIGNAL('toggled(bool)'),
                     self.refresh_visibility)
        self.connect(self.ui.locKey, SIGNAL('textEdited(QString)'),
                     self.redraw)
        # callbacks
        self.ui.actionOpenNetwork.activated\
            .connect(self.on_actionOpenNetwork_triggered)
        self.ui.actionSaveNetwork.activated\
            .connect(self.on_actionSaveNetwork_triggered)
        self.ui.actionRun.activated.connect(self.on_actionRun_triggered)
        self.ui.actionStep.activated.connect(self.on_actionStep_triggered)
        self.ui.actionReset.activated.connect(self.on_actionReset_triggered)

        self.canvas.mpl_connect('pick_event', self.on_pick)

    def handleInspectorMenu(self, pos):
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def init_sim(self, net):
        self.net = net
        self.sim = Simulation(net)
        self.connect(self.sim, SIGNAL("redraw()"), self.redraw)
        self.connect(self.sim, SIGNAL("updateLog(QString)"), self.update_log)
        self.redraw()

    def update_log(self, text):
        """ Add item to list widget """
        print "Add: " + text
        self.ui.logListWidget.insertItem(0, text)
        # self.ui.logListWidget.sortItems()

    def redraw(self):
        self.refresh_network_inspector()
        self.draw_network()
        self.reset_zoom()
        self.refresh_visibility()

    def draw_network(self, net=None, clear=True, subclusters=None,
                     drawMessages=True):
        if not net:
            net = self.net
        currentAlgorithm = self.net.get_current_algorithm()
        if clear:
            self.axes.clear()
        self.axes.imshow(net.environment.im, vmin=0, cmap='binary_r',
                         origin='lower')

        self.draw_tree(str(self.ui.treeKey.text()), net)
        self.draw_edges(net)
        self.draw_propagation_errors(str(self.ui.locKey.text()), net)
        if subclusters:
            node_colors = self.get_node_colors(net, subclusters=subclusters)
        else:
            node_colors = self.get_node_colors(net, algorithm=currentAlgorithm)
        self.node_collection = self.draw_nodes(net, node_colors)
        if drawMessages:
            self.draw_messages(net)
        self.draw_labels(net)
        self.drawnNet = net
        step_text = ' (step %d)' % self.net.algorithmState['step'] \
                    if isinstance(currentAlgorithm, NodeAlgorithm) else ''
        self.axes.set_title((currentAlgorithm.name
                             if currentAlgorithm else '') + step_text)

        self.refresh_visibility()
        # To save multiple figs of the simulation uncomment next two lines:
        #self.fig.savefig('network-alg-%d-step-%d.png' %
        #                 (self.net.algorithmState['index'], self.net.algorithmState['step']))

    def draw_nodes(self, net=None, node_colors={}, node_radius={}):
        if not net:
            net = self.net
        if type(node_colors) == str:
            node_colors = {node: node_colors for node in net.nodes()}
        nodeCircles = []
        for n in net.nodes():
            c = NodeCircle(tuple(net.pos[n]), node_radius.get(n, 8.0),
                           color=node_colors.get(n, 'r'),
                       ec='k', lw=1.0, ls='solid', picker=3)
            nodeCircles.append(c)
        node_collection = PatchCollection(nodeCircles, match_original=True)
        node_collection.set_picker(3)
        self.axes.add_collection(node_collection)
        return node_collection

    def get_node_colors(self, net, algorithm=None, subclusters=None,
                        drawLegend=True):
            COLORS = 'rgbcmyw' * 100
            node_colors = {}
            if algorithm:
                color_map = {}
                if isinstance(algorithm, NodeAlgorithm):
                    for ind, status in enumerate(algorithm.STATUS.keys()):
                        if status == 'IDLE':
                            color_map.update({status: 'k'})
                        else:
                            color_map.update({status: COLORS[ind]})
                    if drawLegend:
                        proxy = []
                        labels = []
                        for status, color in color_map.items():
                            proxy.append(Circle((0, 0), radius=8.0,
                                                color=color, ec='k',
                                                lw=1.0, ls='solid'))
                            labels.append(status)
                        self.fig.legends = []
                        self.fig.legend(proxy, labels, loc=8,
                                        prop={'size': '10.0'}, ncol=len(proxy),
                                        title='Statuses for %s:'
                                                % algorithm.name)
                for n in net.nodes():
                    if n.status == '' or not n.status in color_map.keys():
                        node_colors[n] = 'r'
                    else:
                        node_colors[n] = color_map[n.status]
            elif subclusters:
                for i, sc in enumerate(subclusters):
                    for n in sc:
                        if n in node_colors:
                            node_colors[n] = 'k'
                        else:
                            node_colors[n] = COLORS[i]
            return node_colors

    def draw_edges(self, net=None):
        if not net:
            net = self.net
        self.edge_collection = nx.draw_networkx_edges(net, net.pos, alpha=0.6,
                                                      edgelist=None,
                                                      ax=self.axes)

    def draw_messages(self, net=None):
        if not net:
            net = self.net
        self.messages = []
        msgCircles = []
        for node in net.nodes():
            for msg in node.outbox:
                # broadcast
                if msg.destination is None:
                    for neighbor in net.adj[node].keys():
                        nbr_msg = msg.copy()
                        nbr_msg.destination = neighbor
                        c = MessageCircle(nbr_msg, net, 'out', 3.0, lw=0,
                                          picker=3, zorder=3, color='b')
                        self.messages.append(nbr_msg)
                        msgCircles.append(c)
                else:
                    c = MessageCircle(msg, net, 'out', 3.0, lw=0, picker=3,
                                      zorder=3, color='b')
                    self.messages.append(msg)
                    msgCircles.append(c)
            for msg in node.inbox:
                c = MessageCircle(msg, net, 'in', 3.0, lw=0, picker=3,
                                  zorder=3, color='g')
                self.messages.append(msg)
                msgCircles.append(c)
        if self.messages:
            self.message_collection = PatchCollection(msgCircles,
                                                      match_original=True)
            self.message_collection.set_picker(3)
            self.axes.add_collection(self.message_collection)

    def draw_labels(self, net=None):
        if not net:
            net = self.net
        label_pos = {}
        for n in net.nodes():
            label_pos[n] = net.pos[n].copy() + 10
        self.label_collection = nx.draw_networkx_labels(net, label_pos,
                                                        labels=net.labels,
                                                        ax=self.axes)

    def refresh_visibility(self):
        try:
            self.node_collection.set_visible(self.ui.showNodes.isChecked())
            self.edge_collection.set_visible(self.ui.showEdges.isChecked())
            for label in self.label_collection.values():
                label.set_visible(self.ui.showLabels.isChecked())
            self.tree_collection.set_visible(self.ui.treeGroupBox.isChecked())
            self.ini_error_collection.set_visible(self.ui.propagationError\
                                                    .isChecked())
            self.propagation_error_collection.set_visible(self.ui\
                                                          .propagationError\
                                                          .isChecked())
            # sould be last, sometimes there are no messages
            self.message_collection.set_visible(self.ui.showMessages\
                                                    .isChecked())
        except AttributeError:
            print 'Refresh visibility warning'
        self.canvas.draw()

    def draw_tree(self, treeKey, net=None):
        """
        Show tree representation of network.

        Attributes:
            treeKey (str):
                key in nodes memory (dictionary) where tree data is stored
                storage format can be a list off tree neighbors or a dict:
                    {'parent': parent_node,
                     'children': [child_node1, child_node2 ...]}
        """
        if not net:
            net = self.net
        treeNet = net.get_tree_net(treeKey)
        if treeNet:
            self.tree_collection = draw_networkx_edges(treeNet, treeNet.pos,
                                                       treeNet.edges(),
                                                       width=1.8, alpha=0.6,
                                                       ax=self.axes)

    def draw_propagation_errors(self, locKey, net):
        SCALE_FACTOR = 0.6
        if not net:
            net = self.net
        if any([not locKey in node.memory for node in net.nodes()]):
            self.propagation_error_collection = []
            self.ini_error_collection = []
            return

        rms = {'iniRms': {}, 'stitchRms': {}}
        for node in net.nodes():
            rms['iniRms'][node] = get_rms(self.net.pos,
                                          (node.memory['iniLocs']), True) * \
                                          SCALE_FACTOR
            rms['stitchRms'][node] = get_rms(self.net.pos, node.memory[locKey],
                                             True) * SCALE_FACTOR
        self.propagation_error_collection = \
                            self.draw_nodes(net=net, node_colors='g',
                                            node_radius=rms['stitchRms'])
        self.ini_error_collection = self.draw_nodes(net=net, node_colors='b',
                                                    node_radius=rms['iniRms'])

    def reset_zoom(self):
        self.axes.set_xlim((0, self.net.environment.im.shape[1]))
        self.axes.set_ylim((0, self.net.environment.im.shape[0]))

    def set_title(self, fname):
        new = ' - '.join([str(self.windowTitle()).split(' - ')[0], str(fname)])
        self.setWindowTitle(new)

    def refresh_network_inspector(self):
        niModel = DictionaryTreeModel(dic=self.net.get_dic())
        self.ui.networkInspector.setModel(niModel)
        self.ui.networkInspector.expandToDepth(0)

    """
    Callbacks
    """

    def on_actionRun_triggered(self):
        self.ui.logListWidget.clear()
        print 'running ...',
        self.sim.stepping = True
        self.sim.run_all()

    def on_actionStep_triggered(self):
        print 'next step ...',
        self.sim.run(self.ui.stepSize.value())

    def on_actionReset_triggered(self):
        print 'reset ...',
        self.sim.reset()
        self.redraw()

    def on_actionCopyInspectorData_triggered(self):
        string = 'Node inspector data\n-------------------'
        # raise()
        for qModelIndex in self.ui.nodeInspector.selectedIndexes():
            string += '\n' + qModelIndex.internalPointer().toString('    ')

        clipboard = app.clipboard()
        clipboard.setText(string)
        event = QEvent(QEvent.Clipboard)
        app.sendEvent(clipboard, event)

    def on_actionShowLocalizedSubclusters_triggered(self):
        if len(self.ui.nodeInspector.selectedIndexes()) == 1:
            qModelIndex = self.ui.nodeInspector.selectedIndexes()[0]
            treeItem = qModelIndex.internalPointer()
            assert(isinstance(treeItem.itemDataValue, Positions))

            estimated = deepcopy(treeItem.itemDataValue)
            estimatedsub = estimated.subclusters[0]
            # rotate, translate and optionally scale
            # w.r.t. original positions (pos)
            align_clusters(Positions.create(self.net.pos), estimated, True)
            net = self.net.subnetwork(estimatedsub.keys(), pos=estimatedsub)

            self.draw_network(net=net, drawMessages=False)

            edge_pos = numpy.asarray([(self.net.pos[node], estimatedsub[node][:2])
                                       for node in net])
            error_collection = LineCollection(edge_pos, colors='r')
            self.axes.add_collection(error_collection)

            rms = get_rms(self.net.pos, estimated, scale=False)
            self.update_log('rms = %.3f' % rms)
            self.update_log('localized = %.2f%% (%d/%d)' %
                            (len(estimatedsub) * 1. / len(self.net.pos) * 100,
                            len(estimatedsub), len(self.net.pos)))

    def on_actionSaveNetwork_triggered(self, *args):
        default_filetype = 'gz'
        start = datetime.now().strftime('%Y%m%d') + default_filetype

        filters = ['Network pickle (*.gz)', 'All files (*)']
        selectedFilter = 'Network pickle (gz)'
        filters = ';;'.join(filters)

        fname = QFileDialog.getSaveFileName(self, "Choose a filename",
                                            start, filters, selectedFilter)[0]
        if fname:
            try:
                write_pickle(self.net, fname)
            except Exception, e:
                QMessageBox.critical(
                    self, "Error saving file", str(e),
                    QMessageBox.Ok, QMessageBox.NoButton)
            else:
                self.set_title(fname)
Ejemplo n.º 46
0
class dpph_measurement:
    '''
    '''

    def __init__(self, pype, toplevel=False, **runargs):
        '''
        '''
        self.pype = pype
        self.runargs = runargs
        self.toplevel = toplevel
        self.sweep_result = {}

        self.powerVar = DoubleVar(value=20) #dBm
        self.set_power_BoolVar = BooleanVar(value=True)
        self.start_freq_Var = DoubleVar(value=26350) #MHz
        self.stop_freq_Var = DoubleVar(value=26600) #MHz
        self.start_search_freq_Var = DoubleVar(value=26450) #MHz
        self.stop_search_freq_Var = DoubleVar(value=26510) #MHz
        self.sweep_time_Var = DoubleVar(value=15) #s
        self.num_points_Var = IntVar(value=400) #ms
        self.spanVar = DoubleVar(value=100)
        self.stepVar = DoubleVar(value=4)
        #self.fit_channel_Var = StringVar(value='xdata')
        self.result_str_Var = StringVar(value='')

        self._BuildGui()

    def _BuildGui(self):
        '''
            Dpph popup window
        '''
        row = 0
        ##################################################################
        # Lockin Scan
        Label(self.toplevel, text='Input Power'
              ).grid(row=row, column=0, sticky='ew')
        Entry(self.toplevel, textvariable=self.powerVar
              ).grid(row=row, column=1, sticky='ew')
        Label(self.toplevel, text='[dBm]', justify='left'
              ).grid(row=row, column=2, sticky='w')
        Checkbutton(self.toplevel, text="Don't Change",
                    variable=self.set_power_BoolVar).grid(row=row, column=3)
        row += 1

        Label(self.toplevel, text='Scan Frequency Range'
              ).grid(row=row, column=0, sticky='ew')
        Entry(self.toplevel, textvariable=self.start_freq_Var
              ).grid(row=row, column=1, sticky='ew')
        Entry(self.toplevel, textvariable=self.stop_freq_Var
              ).grid(row=row, column=2, columnspan=2, sticky='ew')
        Label(self.toplevel, text='[MHz]').grid(row=row, column=4, sticky='w')
        row += 1

        Label(self.toplevel, text='Sweep Time'
              ).grid(row=row, column=0, sticky='ew')
        Entry(self.toplevel, textvariable=self.sweep_time_Var
              ).grid(row=row, column=1, sticky='ew')
        Label(self.toplevel, text='[s]').grid(row=row, column=2, sticky='w')
        row += 1

        Label(self.toplevel, text='Number of Points'
              ).grid(row=row, column=0, sticky='ew')
        Entry(self.toplevel, textvariable=self.num_points_Var
              ).grid(row=row, column=1, sticky='ew')
        row += 1

        Button(self.toplevel, text='take data', command=self._CollectSweep
               ).grid(row=row, column=0)
        row += 1

        Label(self.toplevel, text='-'*50).grid(row=row, column=0, columnspan=4, sticky='ew')
        row += 1


        ##################################################################
        # Resonance Search
        Label(self.toplevel, text='Search Frequency Range'
              ).grid(row=row, column=0, sticky='ew')
        Entry(self.toplevel, textvariable=self.start_search_freq_Var
              ).grid(row=row, column=1, sticky='ew')
        Entry(self.toplevel, textvariable=self.stop_search_freq_Var
              ).grid(row=row, column=2, columnspan=2, sticky='ew')
        Label(self.toplevel, text='[MHz]').grid(row=row, column=4, sticky='w')
        row += 1

        #ch_options = ['xdata', 'ydata']
        #OptionMenu(self.toplevel, self.fit_channel_Var, *ch_options
        #           ).grid(row=row, column=0, rowspan=2, sticky='ew')
        Button(self.toplevel, text='find resonance', command=self._FindResonance
               ).grid(row=row, column=1, rowspan=2, sticky='ew')
        Label(self.toplevel, textvariable=self.result_str_Var
              ).grid(row=row, column=2, rowspan=2, columnspan=3, sticky='ew')
        row += 2

        Button(self.toplevel, text='Dump To json', command=self._SaveJson
               ).grid(row=row, column=0)
        Button(self.toplevel, text='Save Image', command=self._SaveFigure
               ).grid(row=row, column=1)
        Button(self.toplevel, text='Log DPPH', command=self._LogDPPH
               ).grid(row=row, column=2)

        self._SetupPlot(row=0, column=5)

    def _SetupPlot(self, row, column):
        '''
            Initialize the plot in the gui
        '''
        self.figure = Figure()
        self.figure.subplots_adjust(left=0.15, bottom=0.2)
        self.subfigure = self.figure.add_subplot(1, 1, 1)
        self.subfigure.plot([0], [0])
        self.subfigure.plot([0], [0])
        self.subfigure.set_xlabel('Freq [MHz]')
        self.canvas = FigureCanvasTkAgg(self.figure, master=self.toplevel)
        self.canvas.show()
        self.canvas.get_tk_widget().grid(row=row, column=column, rowspan=10)

    def _CollectSweep(self):
        '''
        '''
        tmp_power = self.powerVar.get()
        if self.set_power_BoolVar.get():
            tmp_power = False
        while True:
            sweep = _GetSweptVoltages(pype=self.pype,
                                  start_freq=self.start_freq_Var.get(),
                                  stop_freq=self.stop_freq_Var.get(),
                                  sweep_time=self.sweep_time_Var.get(),
                                  power=tmp_power,
                                  num_points=self.num_points_Var.get())
            self.sweep_result = sweep.copy()
            freqdata = array(sweep['frequency_curve'])
            magdata = sweep['amplitude_curve']
            if type(magdata[0]) is unicode:
                print('Warning: _GetSweptVoltages failed;')
                print('magdata:')
                print(magdata)
                print('Acquiring data again...')
            elif type(magdata[0]) is int:
                break
        if not sweep['frequencies_confirmed']:
            showwarning('Warning', 'Communication with lockin amp failed. Frequencies data may be wrong')
        magdata = magdata - mean(magdata)
        #ydata = sweep['y_curve']
        print('freq range is ', min(freqdata), ' to ', max(freqdata))
        #xdata = sweep['x_curve']
        y_del = max((max(magdata) - min(magdata)) * .05, 1)
        self.subfigure.set_xlim(left=freqdata[0], right=freqdata[-1])
        self.subfigure.set_ylim(bottom=(min(magdata) - y_del), top=(max(magdata) + y_del))
        line = self.subfigure.get_lines()[0]
        line.set_xdata(array(freqdata))
        line.set_ydata(array(magdata))
        line.set_label('lockin output')
        #line = self.subfigure.get_lines()[1]
        #line.set_xdata(array(freqdata))
        #line.set_ydata(array(ydata))
        #line.set_label('y output')
        self.figure.legends = []
        self.figure.legend(*self.subfigure.get_legend_handles_labels())
        self.figure.legends[0].draggable(True)
        self.canvas.draw()
        self.canvas.show()
        print('Searching for resonance...')
        self._FindResonance()

    def _FindResonance(self):
        '''
        '''
        #if self.fit_channel_Var.get() == 'xdata':
        #    line = self.subfigure.get_lines()[0]
        #elif self.fit_channel_Var.get() == 'ydata':
        #    line = self.subfigure.get_lines()[1]
        line = self.subfigure.get_lines()[0]
        #else:
        #    raise ValueError('not a valid dataset selection')
        xdata = line.get_xdata()
        ydata = line.get_ydata()
        fit = _FindFieldFFT(min_freq=self.start_search_freq_Var.get(),
                            max_freq=self.stop_search_freq_Var.get(),
                            freq_data=xdata,
                            volts_data=ydata)
        outline = self.subfigure.get_lines()[1]
        factor = max(ydata) / max(fit['result'])
        scaled_data = [val * factor for val in fit['result']]
        scaled_data = scaled_data - mean(scaled_data)
        outline.set_xdata(fit['freqs'])
        outline.set_ydata(scaled_data)
        outline.set_label('filter result')
        self.figure.legends = []
        self.figure.legend(*self.subfigure.get_legend_handles_labels())
        self.figure.legends[0].draggable(True)
        self.canvas.draw()
        self.canvas.show()
        res_freq = max(zip(fit['result'], fit['freqs']))[1]
        res_unct = fit['freqs'][1] - fit['freqs'][0]
        print('resonance found at:', res_freq, 'MHz')
        print('err is:', res_unct)
        geff = 2.0036
        chargemass = 1.758e11
        freq_to_field = 4 * pi * 10 ** 7 / (geff * chargemass)
        res_field = freq_to_field * res_freq
        res_field_unct = freq_to_field * res_unct
        print('for a field of', res_field)
        print('field unct of', res_field_unct)
        self.result_str_Var.set('{:.4E} +/- {:.1E} MHz \n({:.4E} +/- {:.1E} kG)'.format(
            res_freq, res_unct, res_field, res_field_unct))
        self.sweep_result.update({'res_freq': res_freq,
                                  'res_freq_unct': res_unct,
                                  'res_field': res_field,
                                  'res_field_unct': res_field_unct})

    def _SaveJson(self):
        '''
        '''
        if not self.sweep_result:
            print('no result stored')
            return
        outfile = asksaveasfile(defaultextension='.json')
        dump(self.sweep_result, outfile, indent=4)
        outfile.close()

    def _SaveFigure(self):
        '''
        '''
        file_extensions = [('vectorized', '.eps'), ('adobe', '.pdf'), ('image', '.png'), ('all', '.*')]
        outfile = asksaveasfilename(defaultextension='.pdf',
                                    filetypes=file_extensions)
        self.figure.savefig(outfile)

    def _LogDPPH(self):
        if not self.sweep_result:
            print('no dpph_result stored')
            return
        result = {
                  'uncal': self.sweep_result['res_freq'],
                  'uncal_err': self.sweep_result['res_freq_unct'],
                  'uncal_units': 'MHz',
                  'cal': self.sweep_result['res_field'],
                  'cal_err': self.sweep_result['res_field_unct'],
                  'cal_units': 'kG',
                 }
        dpph_result = {'uncal_val': ' '.join([str(result['uncal']), '+/-', str(result['uncal_err']), result['uncal_units']]),
                       'cal_val': ' '.join([str(result['cal']), '+/-', str(result['cal_err']), result['cal_units']]),
                       'timestamp': datetime.utcnow()}
        self.pype.LogValue(sensor='dpph_field', **dpph_result)
        print('dpph_result stored')
Ejemplo n.º 47
0
class XratersWindow(gtk.Window):
    __gtype_name__ = "XratersWindow"
    
    def __init__(self):
        """__init__ - This function is typically not called directly.
        Creation a XratersWindow requires redeading the associated ui
        file and parsing the ui definition extrenally,
        and then calling XratersWindow.finish_initializing().

        Use the convenience function NewXratersWindow to create
        XratersWindow object.

        """
        self._acc_cal = ((128, 128, 128),
                         (255, 255, 255))
        self._acc = [0, 0, 0]
        self._connected = False
        self._wiiMote = None
        self._resetData()
        self._dataLock = threading.Lock()
        
    isConnected = property(lambda self: self._connected)
    
    def callback(funct):
        """A decorator used to require connection to the Wii Remote
        
        This decorator is used to implement the precondition that 
        the Wii Remote must be connected. 
        """
        def _callback(cls, *args, **kwds):
            if cls.isConnected:
                funct(cls, *args, **kwds)
                return True
            else:
                return False
        return _callback
    
    def _connectCallback(self, connectionMaker):
        """Callback function called upon successful connection to the Wiimote
        """
        if connectionMaker.connected:
            self._connected = True
            self._wiiMote = connectionMaker.wiiMote
            self._resetData()
            gobject.timeout_add(45, self._drawAcc)
            self.widget('actionDisconnect').set_sensitive(True)
            self.widget('actionSave').set_sensitive(True)
            self.widget('actionReset').set_sensitive(True)
            self.widget('actionPause').set_sensitive(True)
            self.widget('toolbutton1').set_related_action(self.widget('actionDisconnect'))
            self._acc_cal = connectionMaker.acc_cal
            self._wiiMote.mesg_callback = self._getAcc
            self._updBatteryLevel()
            gobject.timeout_add_seconds(60, self._updBatteryLevel)
        else:
            self.widget('actionWiiConnect').set_sensitive(True)
            
    @callback
    def _upd_background(self, event):
        """Keep a copy of the figure background
        """
        self.__background = self._accCanvas.copy_from_bbox(self._accAxis.bbox)
    
    def _getAcc(self, messages, theTime=0):
        """Process acceleration messages from the Wiimote
        
        This function is intended to be set as cwiid.mesg_callback
        """
        if self._Paused:
            return
        for msg in messages:
            if msg[0] == cwiid.MESG_ACC:
                # Normalize data using calibration info
                for i, axisAcc in enumerate(msg[1]):
                    self._acc[i] = float(axisAcc-self._acc_cal[0][i])
                    self._acc[i] /=(self._acc_cal[1][i]\
                                    -self._acc_cal[0][i])
                with self._dataLock:
                    # Store time and acceleration in the respective arrays
                    self._time.append(theTime-self._startTime)
                    [self._accData[i].append(self._acc[i]) for i in threeAxes]
                # We only keep about 6 seconds worth of data
                if (self._time[-1] - self._time[0] > 6):
                    with self._dataLock:
                        self._time.pop(0)
                        [self._accData[i].pop(0) for i in threeAxes]

    @callback
    def _drawAcc(self):
        """Update the acceleration graph
        
        """
        # Do nothing while paused or there's no data available
        if self._Paused or len(self._time)==0:
            return
        draw_flag = False
        # Update axes limits if the data fall out of range 
        lims = self._accAxis.get_xlim()
        if self._time[-1] > lims[1]:
            self._accAxis.set_xlim(lims[0], lims[1]+2)
            lims = self._accAxis.get_xlim()
            draw_flag = True
        if (self._time[-1] - lims[0] > 6):
            self._accAxis.set_xlim(lims[0]+2, lims[1])
            draw_flag = True
        if draw_flag:
            gobject.idle_add(self._accCanvas.draw)
        # Do the actual update of the background
        if self.__background != None:
            self._accCanvas.restore_region(self.__background)
        # Do the actual update of the lines
        with self._dataLock:
            [self._lines[i].set_data(self._time, self._accData[i]) for i in threeAxes]
        [self._accAxis.draw_artist(self._lines[i]) for i in threeAxes]
        self._accCanvas.blit(self._accAxis.bbox)

    @callback
    def _updBatteryLevel(self):
        """Callback to update the battery indicator in the status bar
        
        """
        self._wiiMote.request_status()
        self._setBatteryIndicator(float(self._wiiMote.state['battery']) / 
                                  cwiid.BATTERY_MAX)
        
    def _setBatteryIndicator(self, level):
        """Actually update the battery indicator in the status bar
        
        """
        progressBar = self.widget("progressbarBattery")
        progressBar.set_fraction(level)
        progressBar.set_text("Battery: %.0f%%" % (level * 100))
    
    def _resetData(self):
        """Reset stored data and status flags to their defaults
        
        """
        self._accData = [list(), list(), list()]
        self._time = list()
        self._startTime = time.time()
        self._moveTime = self._startTime
        self._Paused = False
        
    def widget(self, name):
        """Helper function to retrieve widget handlers
        
        """ 
        return self.builder.get_object(name)

    def finish_initializing(self, builder):
        """finish_initalizing should be called after parsing the ui definition
        and creating a XratersWindow object with it in order to finish
        initializing the start of the new XratersWindow instance.

        """
        #get a reference to the builder and set up the signals
        self.builder = builder
        self.builder.connect_signals(self)
        
        #uncomment the following code to read in preferences at start up
        dlg = PreferencesXratersDialog.NewPreferencesXratersDialog()
        self.preferences = dlg.get_preferences()

        #code for other initialization actions should be added here
        self._accFigure = Figure(figsize=(8,6), dpi=72)
        self._accAxis = self._accFigure.add_subplot(111)
        self._accAxis.set_xlabel("time (s)")
        self._accAxis.set_ylabel("acceleration (g)")
        self._lines = self._accAxis.plot(self._time, self._accData[X],
                                         self._time, self._accData[Y],
                                         self._time, self._accData[Z], 
                                         animated=True)
        self._accFigure.legend(self._lines, ("X", "Y", "Z"), 
                             'upper center', 
                             ncol=3)
        self._accAxis.set_xlim(0, 2)
        self._accAxis.set_ylim(-3, 3)
        self._accCanvas = FigureCanvas(self._accFigure)
        self._accCanvas.mpl_connect("draw_event", self._upd_background)
        self.__background = self._accCanvas.copy_from_bbox(self._accAxis.bbox)
        self._accCanvas.show()
        self._accCanvas.set_size_request(600, 400)
        vbMain = self.widget("vboxMain")
        vbMain.pack_start(self._accCanvas, True, True)
        vbMain.show()
        vbMain.reorder_child(self._accCanvas, 2)
        self._setBatteryIndicator(0)
        
    def about(self, widget, data=None):
        """about - display the about box for xraters """
        about = AboutXratersDialog.NewAboutXratersDialog()
        response = about.run()
        about.destroy()

    def preferences(self, widget, data=None):
        """preferences - display the preferences window for xraters """
        prefs = PreferencesXratersDialog.NewPreferencesXratersDialog()
        response = prefs.run()
        if response == gtk.RESPONSE_OK:
            #make any updates based on changed preferences here
            self.preferences = prefs.get_preferences()
        prefs.destroy()

    def quit(self, widget, data=None):
        """quit - signal handler for closing the XratersWindow"""
        self.destroy()

    def on_destroy(self, widget, data=None):
        """on_destroy - called when the XratersWindow is close. """
        #clean up code for saving application state should be added here
        if self.isConnected:
            self.on_wiiDisconnect(widget, data)
        gtk.main_quit()
        
    def on_wiiConnect(self, widget, data=None):
        """Signal handler for the WiiConnect action
        
        """
        self.widget('actionWiiConnect').set_sensitive(False)
        connectionMaker = WiiConnectionMaker(self.preferences['wiiAddress'],
                                             self.widget("statusbar"),
                                             self._connectCallback)
        self._accAxis.set_xlim(0, 2)
        gobject.idle_add(self._accCanvas.draw)
        connectionMaker.start()
        
    def on_wiiDisconnect(self, widget, data=None):
        """Signal handler for the WiiDisconnect action
        
        """
        self._wiiMote.close()
        self._connected = False
        self.widget('actionDisconnect').set_sensitive(False)
        self.widget('actionWiiConnect').set_sensitive(True)
        self.widget('actionReset').set_sensitive(False)
        self.widget('actionPause').set_sensitive(False)
        self.widget('toolbutton1').set_related_action(self.widget('actionWiiConnect'))
        self.widget('actionSave').set_sensitive(True)
        self.widget('statusbar').pop(self.widget("statusbar").get_context_id(''))
        self._setBatteryIndicator(0)
        
    def on_Reset(self, widget, data=None):
        """Signal handler for the reset action
        
        """
        self._resetData()
        self._accAxis.set_xlim(0, 2)
        gobject.idle_add(self._accCanvas.draw)
        
    def on_Pause(self, widge, data=None):
        """Signal handler for the pause action
        
        """
        if not self._Paused:
            self.widget('actionPause').set_short_label("Un_pause")
        else:
            self.widget('actionPause').set_short_label("_Pause")
        self._Paused = not (self._Paused)        

    def save(self, widget, data=None):
        """Signal handler for the save action
        
        """
        fileName = os.sep.join([self.preferences['outputDir'], 
                                "acceleration_" + 
                                time.strftime("%Y-%m-%d_%H-%M-%S") + 
                                ".dat"]) 
        try:
            with open(fileName, 'wb') as outFile:
                writer = csv.writer(outFile, 'excel-tab')
                outFile.write(writer.dialect.delimiter.join(("#time",
                                                          "Ax",
                                                          "Ay",
                                                          "Az")))
                outFile.write(writer.dialect.lineterminator)
                outFile.write(writer.dialect.delimiter.join(("#s",
                                                          "g",
                                                          "g",
                                                          "g")))
                outFile.write(writer.dialect.lineterminator)
                with self._dataLock:
                    writer.writerows(zip(self._time, *self._accData))
        except IOError as error:
            dialog = gtk.MessageDialog(parent   = None,
                                       flags    = gtk.DIALOG_DESTROY_WITH_PARENT,
                                       type     = gtk.MESSAGE_ERROR,
                                       buttons  = gtk.BUTTONS_OK,
                                       message_format = str(error))
            dialog.set_title(error[1])
            dialog.connect('response', lambda dialog, response: dialog.destroy())
            dialog.show()
Ejemplo n.º 48
0
class OldGraph(object):
    """
    Class for matplotlib graphs, i.e. for popups, krw graphs

    - calculates correct size
    - horizontal axis = dates
    - vertical axis = user defined
    - outputs httpresponse for png
    """

    def __init__(self,
                 start_date, end_date,
                 width=None, height=None,
                 today=datetime.datetime.now(),
                 restrict_to_month=None):
        self.restrict_to_month = restrict_to_month
        self.start_date = start_date
        self.end_date = end_date
        self.today = today

        self.figure = Figure()
        if width is None or not width:
            width = 380.0
        if height is None or not height:
            height = 250.0
        self.width = float(width)
        self.height = float(height)
        self.figure.set_size_inches((_inches_from_pixels(self.width),
                                     _inches_from_pixels(self.height)))
        self.figure.set_dpi(SCREEN_DPI)
        # Figure color
        self.figure.set_facecolor('white')
        # Axes and legend location: full width is "1".
        self.legend_width = 0.08
        # ^^^ No legend by default, but we *do* allow a little space to the
        # right of the graph to prevent the rightmost label from being cut off
        # (at least, in a reasonable percentage of the cases).
        self.left_label_width = LEFT_LABEL_WIDTH / self.width
        self.bottom_axis_location = BOTTOM_LINE_HEIGHT / self.height
        self.x_label_height = 0.08
        self.legend_on_bottom_height = 0.0
        self.axes = self.figure.add_subplot(111)
        self.axes.grid(True)

        # Fixup_axes in init, so axes can be customised (for example set_ylim).
        self.fixup_axes()

        #deze kan je zelf zetten
        self.ax2 = None

    def add_today(self):
        # Show line for today.
        self.axes.axvline(self.today, color='orange', lw=1, ls='--')

    def set_ylim_margin(self, top=0.1, bottom=0.0):
        """Adjust y-margin of axes.

        The standard margin is sometimes zero. This method sets the margin
        based on already present data in the visible part of the plot, so
        call it after plotting and before http_png().

        Note that it is assumed here that the y-axis is not reversed.

        From matplotlib 1.0 on there is a set_ymargin method
        like this already."""

        lines = self.axes.lines
        arrays = [numpy.array(l.get_data()) for l in lines]

        # axhline and axvline give trouble - remove short lines from list
        big_arrays = [a for a in arrays if a.size > 4]
        if len(big_arrays) > 0:
            data = numpy.concatenate(big_arrays, axis=1)
            if len(data[0]) > 0:
                # Datatimes from database may have timezone information.
                # In that case, start_date and end_date cannot be naive.
                # Assume all datetimes do have the same timezone, so we
                # can do the comparison.
                start_date_tz =\
                    self.start_date.replace(tzinfo=data[0][0].tzinfo)
                end_date_tz =\
                    self.end_date.replace(tzinfo=data[0][0].tzinfo)
            index_in_daterange = ((data[0] < end_date_tz) &
                                  (data[0] > start_date_tz))
            if index_in_daterange.any():
                data_low = numpy.min(data[1, index_in_daterange])
                data_high = numpy.max(data[1, index_in_daterange])
                data_span = data_high - data_low
                view_low = data_low - data_span * bottom
                view_high = data_high + data_span * top
                self.axes.set_ylim(view_low, view_high)
        return None

    def suptitle(self, title):
        self.figure.suptitle(title,
                             x=self.left_label_width,
                             horizontalalignment='left')

    def set_xlabel(self, xlabel):
        self.axes.set_xlabel(xlabel)
        self.x_label_height = BOTTOM_LINE_HEIGHT / self.height

    def fixup_axes(self, second=False):
        """Fix up the axes by limiting the amount of items."""

        axes_to_change = self.axes
        if second:
            if self.ax2 is None:
                return
            else:
                axes_to_change = self.ax2

#        available_width = self.width - LEFT_LABEL_WIDTH - LEGEND_WIDTH
#        approximate_characters = int(available_width / (FONT_SIZE / 2))
#        max_number_of_ticks = approximate_characters // 20
#        if max_number_of_ticks < 2:
#            max_number_of_ticks = 2
        if not self.restrict_to_month:
            major_locator = LessTicksAutoDateLocator()
            axes_to_change.xaxis.set_major_locator(major_locator)

            major_formatter = MultilineAutoDateFormatter(
                major_locator, axes_to_change)
            axes_to_change.xaxis.set_major_formatter(major_formatter)

        available_height = (self.height -
                            BOTTOM_LINE_HEIGHT -
                            self.x_label_height -
                            self.legend_on_bottom_height)
        approximate_lines = int(available_height / (FONT_SIZE * 1.5))
        max_number_of_ticks = approximate_lines
        if max_number_of_ticks < 2:
            max_number_of_ticks = 2
        locator = MaxNLocator(nbins=max_number_of_ticks - 1)
        if not second:
            axes_to_change.yaxis.set_major_locator(locator)
            axes_to_change.yaxis.set_major_formatter(
                ScalarFormatter(useOffset=False))

    def legend_space(self):
        """reserve space for legend (on the right side). even when
        there is no legend displayed"""
        self.legend_width = LEGEND_WIDTH / self.width

    def legend(self, handles=None, labels=None, ncol=1):
        """
        Displays legend. Default is right side, but if the width is
        too small, it will display under the graph.

        handles is list of matplotlib objects (e.g. matplotlib.lines.Line2D)
        labels is list of strings
        """
        # experimental update: do not reserve space for legend by
        # default, just place over graph. use legend_space to manually
        # add space

        if handles is None and labels is None:
            handles, labels = self.axes.get_legend_handles_labels()
        if handles and labels:
            # Determine 'small' or 'large'
            if self.width < 500:
                legend_loc = 4  # lower right
                # approximation of legend height
                self.legend_on_bottom_height = min(
                    (len(labels) / ncol + 2) * BOTTOM_LINE_HEIGHT /
                    self.height,
                    0.5)
            else:
                legend_loc = 1  # Upper right'

            return self.figure.legend(
                handles,
                labels,
                bbox_to_anchor=(1 - self.legend_width,
                                0,  # self.bottom_axis_location
                                self.legend_width,
                                # 1 = Upper right of above bbox. Use 0 for
                                # 'best'
                                1),
                loc=legend_loc,
                ncol=ncol,
                fancybox=True,
                shadow=True,)
         #legend.set_size('medium')
         # TODO: get rid of the border around the legend.

    def init_second_axes(self):
        """ init second axes """
        self.ax2 = self.axes.twinx()
        self.fixup_axes(second=True)

    def http_png(self):
        """Output plot to png. Also calculates size of plot and put 'now'
        line."""

        axes_left = self.left_label_width
        axes_bottom = (self.bottom_axis_location + self.x_label_height +
                       self.legend_on_bottom_height)
        axes_width = 1 - self.legend_width - self.left_label_width
        axes_height = (1 - 2 * self.bottom_axis_location -
                       self.x_label_height - self.legend_on_bottom_height)

        self.axes.set_position((axes_left, axes_bottom,
                                axes_width, axes_height))

        if self.ax2 is not None:
            self.ax2.set_position((axes_left, axes_bottom,
                                axes_width, axes_height))

        # Set date range
        # Somehow, the range cannot be set in __init__
        if not self.restrict_to_month:
            self.axes.set_xlim(date2num((self.start_date, self.end_date)))
            try:
                self.set_ylim_margin(top=0.1, bottom=0.0)
            except:
                pass

        canvas = FigureCanvas(self.figure)
        response = HttpResponse(content_type='image/png')
        canvas.print_png(response)
        return response
Ejemplo n.º 49
0
class PlotPanel(wx.Panel):
    def __init__(self, parent, data, title, page):
        wx.Panel.__init__(self, parent, -1)

        self.parent = page

        self.data = data
        self.title = title
        self.fig = Figure((3.0, 3.0), dpi=100)
        self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
        # TODO (minor): exact value according to mouse position
        """
        http://matplotlib.sourceforge.net/users/event_handling.html

        def onmove(event):
            if event.inaxes:
                logging.debug('x=%d, y=%d, xdata=%f, ydata=%f' % (event.x, event.y,
                    event.xdata, event.ydata))

        self.canvas.mpl_connect('motion_notify_event', onmove)
        """
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        self.init_controls()
        self.init_plot()

        self.lcol = wx.BoxSizer(wx.VERTICAL)
        self.lcol.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.lcol.Add(self.toolbar, 0, wx.GROW)
        self.rcol = wx.BoxSizer(wx.VERTICAL)
        self.rcol.Add(self.controls, 0, wx.EXPAND)

        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer.Add(self.lcol, 1, wx.EXPAND)
        self.sizer.Add(self.rcol, 0)

        self.SetSizer(self.sizer)
        self.Fit()

    def init_plot(self):
        self.axes = self.fig.add_subplot(111)

        self.axes.set_title(self.title, size=12)
        self.axes.set_xlabel("Time [GMT]", labelpad=20)
        self.axes.set_ylabel("Signal strength [dB]", labelpad=20)

        clist = settings.plot_color_cycle.split(" ")
        self.axes.set_color_cycle(clist)
        self.axes.grid(True, color=settings.plot_grid_color)
        self.axes.set_axis_bgcolor(settings.plot_bg_color)

        def format_date(x, pos=None):
            dt = dates.num2date(x)
            main = dt.strftime("%H:%M:%S.")
            zeros_missing = 6 - len(str(dt.microsecond))
            flo = float(".%s%d" % (zeros_missing * "0", dt.microsecond))
            return main + ("%.03f" % round(flo, 3))[2:]

        self.axes.xaxis.set_major_locator(ticker.LinearLocator())
        self.axes.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
        self.axes.yaxis.set_major_locator(ticker.AutoLocator())
        # unused
        # self.axes.format_xdata = dates.DateFormatter('%H:%M:%S')
        self.fig.autofmt_xdate()

        self.plot(self.first_dtype)

        xmin = self.data["_times"][0]
        xmax = self.data["_times"][-1]
        self.axes.set_xbound(lower=xmin, upper=xmax)

        self.axes.set_autoscale_on(False)
        self.autoscale = False

        self.rescale()
        self.toolbar.update()

    def init_controls(self):
        self.controls = wx.Panel(self)
        csizer = wx.BoxSizer(wx.VERTICAL)
        dtypes = self.data.keys()
        dtypes.sort()
        fst = True
        add = paply(csizer.Add, border=5, flag=wx.ALL)
        add_cb = paply(csizer.Add, border=5, flag=wx.LEFT | wx.RIGHT)

        btn = wx.Button(self.controls, -1, label="Close file")
        add(btn)
        self.Bind(wx.EVT_BUTTON, self.parent.on_cancel, btn)

        label = wx.StaticText(self.controls, label="Bands:")
        add(label)

        for dtype in dtypes:
            if dtype[0] != "_":
                cbox = wx.CheckBox(self.controls, label=dtype)
                if fst:
                    fst = False
                    self.first_dtype = dtype
                    cbox.SetValue(True)
                add_cb(cbox)
                self.Bind(wx.EVT_CHECKBOX, paply(self.on_band, dtype), cbox)
        btn = wx.Button(self.controls, -1, label="Re-scale")
        add(btn)
        self.Bind(wx.EVT_BUTTON, self.rescale, btn)

        auto = wx.CheckBox(self.controls, label="Autoscale")
        add_cb(auto)
        self.Bind(wx.EVT_CHECKBOX, self.on_autoscale, auto)

        live_label = wx.StaticText(self.controls, label="Live mode:")
        choices = ["Update", "Follow", "Scale x"]
        live_mode = wx.Choice(self.controls, -1, choices=choices)

        self.controls.live_mode = live_mode

        add(live_label)
        add(live_mode)

        self.controls.SetSizer(csizer)

    def rescale(self, event=None):
        ymin = 99999
        ymax = -ymin
        for dtype in self.data.keys():
            if hasattr(self, dtype):
                ymin = min(ymin, self.data["_bounds"][dtype][0])
                ymax = max(ymax, self.data["_bounds"][dtype][1])

        # 1% spacing
        corr = (ymax - ymin) / 100
        self.axes.set_ybound(lower=ymin - corr, upper=ymax + corr)
        self.redraw()

    def on_autoscale(self, event=None):
        if event is not None:
            obj = event.GetEventObject()
            self.autoscale = obj.IsChecked()

    def on_band(self, which, event=None):
        if event is not None:
            obj = event.GetEventObject()
            if obj.IsChecked():
                self.plot(which)
                if self.autoscale:
                    self.rescale()
            else:
                line = getattr(self, which)
                for index, _line in enumerate(self.axes.lines):
                    if _line == line:
                        break

                self.axes.lines.pop(index)
                delattr(self, which)
                if self.autoscale:
                    self.rescale()
                self.redraw()

    def plot(self, which):
        x = self.data["_times"]
        y = self.data[which]
        t = self.data["_time_bounds"][which]

        if t != x[0]:
            logging.warning("Data type %s appeared later" % which)
            start = x.index(self.data["_time_bounds"][which])
            x = x[start:]

        if len(y) != len(x):
            x = x[: len(y)]

        line = self.axes.plot(x, y, scaley=False)[0]
        #            marker='|', markerfacecolor='red')[0]

        setattr(self, which, line)
        self.redraw()

    def redraw(self):
        # update legend
        handles = []
        dtypes = []
        for dtype in self.data.keys():
            if hasattr(self, dtype):
                handles.append(getattr(self, dtype))
                dtypes.append(dtype)

        self.fig.legends = []
        if len(handles) != 0:
            self.fig.legend(handles, dtypes, "right")

        # update tick style
        allticks = self.axes.xaxis.get_ticklines() + self.axes.yaxis.get_ticklines()
        for line in allticks:
            line.set_color("gray")
        # redraw
        self.canvas.draw()

    def GetToolBar(self):
        return self.toolbar

    def onEraseBackground(self, evt):
        # this is supposed to prevent redraw flicker on some X servers...
        pass
Ejemplo n.º 50
0
def load_and_plot_diurnal(address, password, daysback):
	address=address+'@gmail.com'
	#print address, password
	#Customizing Variables

	### HOW FAR BACK? ###
	daysback = int(daysback)
	notsince = 0
	since = (date.today() - timedelta(daysback)).strftime("%d-%b-%Y")
	before = (date.today() - timedelta(notsince)).strftime("%d-%b-%Y")

	SEARCH = '(SENTSINCE {si} SENTBEFORE {bf})'.format(si=since, bf=before)
	BODY = '(BODY.PEEK[TEXT])'
	ALL_HEADERS = '(BODY.PEEK[HEADER.FIELDS (DATE TO CC FROM SUBJECT)])'
	DATE = '(BODY.PEEK[HEADER.FIELDS (DATE)])'

	tyler = GmailAccount(username=address,password=password)
	out = tyler.login()



	#LOAD GMAIL EMAILS
	received = tyler.load_parse_query(SEARCH, ALL_HEADERS, 'inbox')
	#print 'loaded received...'
	sent = tyler.load_parse_query(SEARCH, ALL_HEADERS, '[Gmail]/Sent Mail')
	#print 'loaded received and sent mail!'

	xr, yr = diurnalCompute(received)
	xs, ys = diurnalCompute(sent)

	fig=Figure(figsize=(14,8))
	ax=fig.add_subplot(111)

	p1, = ax.plot_date(xr, yr, '.', alpha=0.5, color='b', markersize=marker_size(len(xr)))
	p2, = ax.plot_date(xs, ys, '.', alpha=0.7, color='r', markersize=marker_size(len(xr)))
	fig.autofmt_xdate()

	fig.legend((p1, p2,), ('Received','Sent'), 'upper center', numpoints=1, markerscale=4, fancybox=True)
	ax.set_xlabel("Specific Date")
	ax.set_ylabel("Time Of Day")

	fig.tight_layout(pad=2)
	#legend(('Received','Sent'), numpoints=1)
	#ax.title("Received data for %s las %s days"%(address, str(daysback)))

	#ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))


	'''
	fig = figure()
	plot_date(xr, yr, '.', alpha=0.7, color='b', markersize=marker_size(len(xr)))
	#plot_date(xs, ys, '.', alpha=0.7, color='r', markersize=marker_size(len(xs)))
	legend(('Received','Sent'), numpoints=1)
	out = plt.setp(plt.xticks()[1], rotation=30)
	'''


	canvas=FigureCanvas(fig)
	response=django.http.HttpResponse(content_type='image/png')
	canvas.print_png(response)

	return response


	'''
Ejemplo n.º 51
0
class GraphFrame(wx.Frame):
    """ The main frame of the application
    """
    title = 'Demo: dynamic matplotlib graph'
    
    def __init__(self, port, baud, chan):
        wx.Frame.__init__(self, None, -1, self.title)
        
        self.chan = chan
        self.datagen = DataGen.SerialData(port=port, baud=baud)        
        self.data = []
        for i in range(0, self.chan):
            self.data.append([0.0])
        self.formatter = VSP_format.Formatter(self.chan*4, ">" + "I"*self.chan)
        self.paused = False
        
        self.create_menu()
        self.create_status_bar()
        self.create_main_panel()
        
        self.redraw_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)        
        self.redraw_timer.Start(REFRESH_INTERVAL_MS)
        self.Bind(wx.EVT_CLOSE, self.on_exit)
                
        if self.datagen.get_port_info() != None:
            self.flash_status_message("%s : %s " % self.datagen.get_port_info())
        else:
            self.flash_status_message("Failed to connect")   

    def create_menu(self):
        self.menubar = wx.MenuBar()
        
        menu_file = wx.Menu()
        m_expt = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file")
        self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt)
        menu_file.AppendSeparator()
        m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit")
        self.Bind(wx.EVT_MENU, self.on_exit, m_exit)
                
        self.menubar.Append(menu_file, "&File")
        self.SetMenuBar(self.menubar)

    def create_main_panel(self):
        self.panel = wx.Panel(self)

        self.init_plot()
        self.canvas = FigCanvas(self.panel, -1, self.fig)

        self.xmin_control = BoundControlBox(self.panel, -1, "X min", 0)
        self.xmax_control = BoundControlBox(self.panel, -1, "X max", 50)
        self.ymin_control = BoundControlBox(self.panel, -1, "Y min", 0)
        self.ymax_control = BoundControlBox(self.panel, -1, "Y max", 4)
        
        self.pause_button = wx.Button(self.panel, -1, "Pause")
        self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button)
        self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button)
        
        self.cb_grid = wx.CheckBox(self.panel, -1, 
            "Show Grid",
            style=wx.ALIGN_RIGHT)
        self.Bind(wx.EVT_CHECKBOX, self.on_cb_grid, self.cb_grid)
        self.cb_grid.SetValue(True)
        
        self.cb_xlab = wx.CheckBox(self.panel, -1, 
            "Show X labels",
            style=wx.ALIGN_RIGHT)
        self.Bind(wx.EVT_CHECKBOX, self.on_cb_xlab, self.cb_xlab)        
        self.cb_xlab.SetValue(True)
        
        self.hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
        self.hbox1.AddSpacer(20)
        self.hbox1.Add(self.cb_grid, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
        self.hbox1.AddSpacer(10)
        self.hbox1.Add(self.cb_xlab, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
        
        self.hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox2.Add(self.xmin_control, border=5, flag=wx.ALL)
        self.hbox2.Add(self.xmax_control, border=5, flag=wx.ALL)
        self.hbox2.AddSpacer(24)
        self.hbox2.Add(self.ymin_control, border=5, flag=wx.ALL)
        self.hbox2.Add(self.ymax_control, border=5, flag=wx.ALL)
        
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.EXPAND)        
        self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP)
        self.vbox.Add(self.hbox2, 0, flag=wx.ALIGN_LEFT | wx.TOP)
        
        self.panel.SetSizer(self.vbox)
        self.vbox.Fit(self)
    
    def create_status_bar(self):
        self.statusbar = self.CreateStatusBar()

    def init_plot(self):
        self.dpi = 100
        self.fig = Figure((3.0, 3.0), dpi=self.dpi)

        self.axes = self.fig.add_subplot(111)
        self.axes.set_axis_bgcolor('black')
        self.axes.set_title('Put title here', size=12)
        self.axes.set_xlabel('Time (s)', fontsize=10)
        self.axes.set_ylabel('CDC value', fontsize=10)
        
        pylab.setp(self.axes.get_xticklabels(), fontsize=8)
        pylab.setp(self.axes.get_yticklabels(), fontsize=8)

        # plot the data as a line series, and save the reference 
        # to the plotted line series
        #
        self.plot_data = []
        
        for i in range(0, self.chan):
            self.plot_data.append(self.axes.plot(
            self.data, 
            linewidth=1,
            color=numpy.random.rand(3,1),
            )[0])

        self.fig.legend(self.plot_data, ["Differential"]*6, prop={'size':10})

    def set_background_color(self, color):
        self.axes.set_axis_bgcolor(color)

    def draw_plot(self):
        """ Redraws the plot
        """
        # when xmin is on auto, it "follows" xmax to produce a 
        # sliding window effect. therefore, xmin is assigned after
        # xmax.
        #
        if self.xmax_control.is_auto():
            xmax = len(self.data[0]) if len(self.data[0]) > 50 else 50
        else:
            xmax = int(self.xmax_control.manual_value())
            
        if self.xmin_control.is_auto():            
            xmin = xmax - 50
        else:
            xmin = int(self.xmin_control.manual_value())

        # for ymin and ymax, find the minimal and maximal values
        # in the data set and add a mininal margin.
        # 
        # note that it's easy to change this scheme to the 
        # minimal/maximal value in the current display, and not
        # the whole data set.
        # 
        if self.ymin_control.is_auto():
            ymin = round(min(self.data[0]), 0) - 1
        else:
            ymin = int(self.ymin_control.manual_value())
        
        if self.ymax_control.is_auto():
            ymax = round(max(self.data[0]), 0) + 1
        else:
            ymax = int(self.ymax_control.manual_value())        

        self.axes.set_xbound(lower=xmin, upper=xmax)
        self.axes.set_ybound(lower=ymin, upper=ymax)
        
        # anecdote: axes.grid assumes b=True if any other flag is
        # given even if b is set to False.
        # so just passing the flag into the first statement won't
        # work.
        #
        if self.cb_grid.IsChecked():
            self.axes.grid(True, color='gray')
        else:
            self.axes.grid(False)

        # Using setp here is convenient, because get_xticklabels
        # returns a list over which one needs to explicitly 
        # iterate, and setp already handles this.
        #  
        pylab.setp(self.axes.get_xticklabels(), 
            visible=self.cb_xlab.IsChecked())
        for i in range(0, len(self.plot_data)):
            self.plot_data[i].set_xdata(np.arange(len(self.data[i])))
            self.plot_data[i].set_ydata(np.array(self.data[i]))
        
        self.canvas.draw()
    
    def on_pause_button(self, event):
        self.paused = not self.paused
    
    def on_update_pause_button(self, event):
        label = "Resume" if self.paused else "Pause"
        self.pause_button.SetLabel(label)
    
    def on_cb_grid(self, event):
        self.draw_plot()
    
    def on_cb_xlab(self, event):
        self.draw_plot()
    
    def on_save_plot(self, event):
        file_choices = "PNG (*.png)|*.png"
        
        dlg = wx.FileDialog(
            self, 
            message="Save plot as...",
            defaultDir=os.getcwd(),
            defaultFile="plot.png",
            wildcard=file_choices,
            style=wx.SAVE)
        
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self.canvas.print_figure(path, dpi=self.dpi)
            self.flash_status_message("Saved to %s" % path)

    def get_data(self):
        new_data = self.datagen.next()
        data = self.formatter.parse(new_data)
        if data == None and len(self.formatter.raw_data) != 0:
            data = self.formatter.parse(None, True)
        return data
                    
    def on_redraw_timer(self, event):
        # if paused do not add data, but still redraw the plot
        # (to respond to scale modifications, grid change, etc.)
        #
        if not self.paused:
            try:
                data = self.get_data()                
                if data == None and len(self.formatter.raw_data) != 0:
                    data = self.formatter.parse(None, True)           
                if data != None:                                          
                    for i in range(0, self.chan):
                        print data
                        self.data[i].append(data[i])                      
            except Queue.Empty:
                print "Queue empty"
        self.draw_plot()        
        
    def on_exit(self, event):
        self.datagen.quit()        
        self.Destroy()
    
    def flash_status_message(self, msg, flash_len_ms=1500):
        self.statusbar.SetStatusText(msg)
        self.timeroff = wx.Timer(self)
        self.Bind(
            wx.EVT_TIMER, 
            self.on_flash_status_off, 
            self.timeroff)
        self.timeroff.Start(flash_len_ms, oneShot=True)
    
    def on_flash_status_off(self, event):
        self.statusbar.SetStatusText('')
Ejemplo n.º 52
0
def create_graph():
    """Create graph of code quality evolution
    """
    t0 = time()
    cwd = getcwd()
    project_name = cwd.split('/')[-1]
    # We copy project to tmp (for security)
    tmp_directory = '%s/ipkg_quality.git' % mkdtemp()
    call(['git', 'clone',  cwd, tmp_directory])
    chdir(tmp_directory)
    # First step: we create a list of statistics
    statistics = {}
    commit_ids = git.get_revisions()
    commit_ids.reverse()
    print 'Script will analyse %s commits.' % len(commit_ids)
    for commit_id in commit_ids:
        # We move to a given commit
        call(['git', 'reset', '--hard', commit_id])
        # Print script evolution
        stdout.write('.')
        stdout.flush()
        # We list files
        filenames = git.get_filenames()
        filenames = [ x for x in filenames if x.endswith('.py') ]
        # We get code quality for this files
        stats, files_db = analyse(filenames, ignore_errors=True)
        metadata = git.get_metadata()
        date_time = metadata['committer'][1]
        commit_date = date(date_time.year, date_time.month, date_time.day)
        if commit_date not in statistics:
            statistics[commit_date] = stats
        else:
            # Same day => Avg
            for key in statistics[commit_date]:
                avg = (statistics[commit_date][key] + stats[key])/2
                statistics[commit_date][key] = avg
    print
    # Get dates
    values = []
    dates = statistics.keys()
    dates.sort()
    for a_date in dates:
        values.append(statistics[a_date])
    # Base graph informations
    base_title = '[%s %s]' % (project_name, git.get_branch_name())
    # We generate graphs
    chdir(cwd)
    for problem_dict in ['code_length', 'aesthetics_problems',
                         'exception_problems', 'import_problems']:
        current_problems = eval(problem_dict)
        graph_title = '%s %s' % (base_title, current_problems['title'])
        lines = []
        labels = []
        fig = Figure()
        graph = fig.add_subplot(111)
        for key in current_problems['keys']:
            if current_problems['pourcent']:
                problem_values = [((x[key]*100.0)/x['lines']) for x in values]
            else:
                problem_values = [x[key] for x in values]
            lines.append(graph.plot_date(dates, problem_values, '-'))
            labels.append(current_problems['keys'][key])
        graph.set_title(graph_title)
        graph.xaxis.set_major_formatter(DateFormatter("%b '%y'"))
        if current_problems['pourcent']:
            graph.set_ylabel('Pourcent')
            graph.yaxis.set_major_formatter(FormatStrFormatter("%5.02f %%"))
        else:
            graph.set_ylabel('Quantity')
        graph.set_xlabel('')
        graph.autoscale_view()
        graph.grid(True)
        fig.autofmt_xdate()
        fig.set_figheight(fig.get_figheight()+5)
        legend = fig.legend(lines, labels, loc=8, axespad=0.0)
        legend.get_frame().set_linewidth(0)
        canvas = FigureCanvasAgg(fig)
        destination = 'graph_%s.png' % problem_dict
        canvas.print_figure(destination, dpi=80)
        print '%s -> %s ' % (graph_title, destination)
    t1 = time()
    print 'Generation time: %d minutes.' % ((t1 - t0)/60)
Ejemplo n.º 53
0
class mplchart(chart):
    colours = dict(zip('red green blue yellow magenta black'.split(),
                       'r   g     b    y      m       k'.split()))

    def __init__(self, spurset, fef, parent):
        chart.__init__(self, spurset, fef, parent)

        # make the figure blend in with the native application look
        bgcol = parent.palette().window().color().toRgb()
        bgcol = [bgcol.redF(), bgcol.greenF(), bgcol.blueF()]

        self.fig = Figure()
        self.fig.set_facecolor(bgcol)
        
        # a FigureCanvas can be added as a QWidget, so we use that
        self.plot = FigureCanvas(self.fig)
        self.plot.setParent(parent)

        self.ax = self.fig.add_subplot(111)
        # TODO skip this, just do a redraw() after initialization?
        self.ax.set_xlim(self.spurset.RFmin, self.spurset.RFmax)
        self.ax.set_ylim(-0.5*self.spurset.dspan, 0.5*self.spurset.dspan)
        self.ax.grid(True)
        self.fig.tight_layout()

        # a second figure to hold the legend
        self.legendFig = Figure()
        self.legendFig.set_facecolor(bgcol)
        self.legendCanvas = FigureCanvas(self.legendFig)
        self.legendFig.legend(*self.ax.get_legend_handles_labels(),
                              loc='upper left')

        # connect up the picker watching
        self.picked_obj = None
        self._pick = self.plot.mpl_connect('pick_event', self.onpick)
        self._drag = self.plot.mpl_connect('motion_notify_event', self.ondrag)
        self._drop = self.plot.mpl_connect('button_release_event', self.ondrop)

    def legend(self):
        return self.legendCanvas

    def mkline(self, xdata, ydata, style, title):
        return mpl.lines.Line2D(xdata, ydata, label=title,
                                color=self.colours[style[0]], ls=style[1])

    def add_line(self, line):
        self.ax.add_line(line)

    def del_line(self, line):
        self.ax.lines.remove(line)

    def draw_spurs(self, obj):
        chart.draw_spurs(self, obj)

    def redraw(self):
        self.ax.set_ylim(-0.5*self.spurset.dspan, 0.5*self.spurset.dspan)
        self.ax.set_xlim(self.spurset.RFmin, self.spurset.RFmax)
        # WHO WANTS TO BET THIS IS UNSUPPORTED?
        # but damn, it works :/
        self.legendFig.legends = []
        self.legendFig.legend(*self.ax.get_legend_handles_labels(),
                              loc='upper left')
        self.legendCanvas.draw()
        self.plot.draw()

    def draw_fef(self, obj):
        chart.draw_fef(self, obj)
        self.feflines[0].set_picker(10)
        self.feflines[1].set_picker(10)

    def onpick(self, event):
        if event.mouseevent.button != 1:
            # only picking on left-click atm
            return
        obj, x, y = event.artist, event.mouseevent.xdata, event.mouseevent.ydata
        self.picked_obj = obj
        self.pick(obj, x, y)
        self.drag(obj, x, y)

    def ondrag(self, event):
        self.drag(self.picked_obj, event.xdata, event.ydata)

    def ondrop(self, event):
        if event.button != 1:
            # only picking on left-click atm
            return
        self.drop(self.picked_obj, event.xdata, event.ydata)
        self.picked_obj = None
Ejemplo n.º 54
0
class MplCanvas(FigureCanvas):
    subscriptions = [rc.MT_PING, MT_EXIT,
                     rc.MT_TASK_STATE_CONFIG,
                     rc.MT_ROBOT_CONTROL_SPACE_ACTUAL_STATE,
                     rc.MT_GROBOT_SEGMENT_PERCEPTS,
                     rc.MT_GROBOT_RAW_FEEDBACK,
                     rc.MT_END_TASK_STATE]

    def __init__(self, parent=None, width=8, height=10, dpi=80):
        self.parent = parent
        self.paused = False
        self.LiveData = None
        self.fdbk_actual_pos = None
        self.fdbk_actual_cori = None
        self.tsc_mdf = None
        self.ets_mdf = None
        self.fdbk_percepts = [0] * 16
        self.fdbk_torques = [0] * 16
        self.redraw_yticks = True

        self.figure = Figure(figsize=(width, height), dpi=dpi, facecolor='#bbbbbb')
        FigureCanvas.__init__(self, self.figure)

        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        

    def init_judge_display(self):
        N = self.config['config']['number_of_data_points']

        self.LiveData = {'ActualPos': {},
                         'ThreshUpper': {},
                         'ThreshLower': {},
                         'JudgingMethod': {},
                         'JudgingPolarity': {},
                         'max_scale': {},
                         'min_scale': {} }
        
        allDims = 1 + 1 + 10 + 15 + 28  # trans + ori + finger + force + torque
        
        for d in range(allDims):
            self.LiveData['ActualPos'][d] = np.zeros(N)
            self.LiveData['ThreshUpper'][d] = nan_array(N)
            self.LiveData['ThreshLower'][d] = nan_array(N)
            self.LiveData['JudgingMethod'][d] = nan_array(N)
            self.LiveData['JudgingPolarity'][d] = nan_array(N)
            self.LiveData['max_scale'][d] = np.finfo(float).eps
            self.LiveData['min_scale'][d] = -np.finfo(float).eps #

        self.LiveData['TaskStateNo'] = np.zeros(N)
        self.LiveData['TaskStateVerdict'] = np.ones(N)

    def run(self, config_file, server):
        self.mod = RTMA_Module(0, 0)
        self.mod.ConnectToMMM(server)
        for sub in self.subscriptions:
            self.mod.Subscribe(sub)
        self.mod.SendModuleReady()
        print "Connected to RTMA at", server

        self.config_file = config_file
        self.load_config()

        self.init_judge_display()
        self.init_plot()
        self.init_legend()

        timer = QtCore.QTimer(self)
        QtCore.QObject.connect(timer, QtCore.SIGNAL("timeout()"), self.timer_event)
        timer.start(10)     

    def update_scales(self, d):
        min_data = np.nanmin(self.LiveData['ActualPos'][d])
        if min_data < self.LiveData['min_scale'][d]:
            self.LiveData['min_scale'][d] = min_data;

        max_data = np.nanmax(self.LiveData['ActualPos'][d])
        if max_data > self.LiveData['max_scale'][d]:
            self.LiveData['max_scale'][d] = max_data;
    
    
    def update_judging_data(self):
        # this loop is so we can update finger pos data even if we haven't
        # received any TASK_STATE_CONFIG msg
        for i in range(self.nDims):
            d = self.dims[i] - 1
            if d > 1:        # fingers
                finger_idx = d-2
                actual_pos = self.fdbk_actual_pos[8+finger_idx];
                self.LiveData['ActualPos'][d] = self.add_to_windowed_array(self.LiveData['ActualPos'][d], actual_pos)
                self.update_scales(d)

        if self.tsc_mdf is None:
            return

        trans_thresh = self.tsc_mdf.trans_threshold
        ori_threshold = self.tsc_mdf.ori_threshold
        finger_thresh = np.array(self.tsc_mdf.finger_threshold, dtype=float)
        finger_dofs_to_judge = np.where(~np.isnan(finger_thresh)==True)[0]

        for i in range(self.nDims):
            d = self.dims[i] - 1

            threshU = np.NAN
            threshL = np.NAN
            method = np.NAN
            polarity = np.NAN

            if d == 0:   # trans
                tgt_pos = np.array(self.tsc_mdf.target[0:3])
                act_pos = np.array(self.fdbk_actual_pos[0:3])
                tgt_disp = tgt_pos - act_pos;
                tgt_dist = np.sqrt(np.sum(np.power(tgt_disp,2)))

                self.LiveData['ActualPos'][d] = self.add_to_windowed_array(self.LiveData['ActualPos'][d], tgt_dist)
                self.update_scales(d)
                
                threshU = trans_thresh
                threshL = -trans_thresh
                method = 1      # dist
                polarity = 2    # less than (inverted)

            elif d == 1: # ori
            
                tgt_cori = np.array(self.tsc_mdf.coriMatrix).reshape((3,3)).T
                act_cori = np.array(self.fdbk_actual_cori).reshape((3,3)).T
                cori_diff_matrix = tgt_cori * act_cori.T
                [diff_rotaxis, diff_angle] = rotmat2rotvec( cori_diff_matrix)

                self.LiveData['ActualPos'][d] = self.add_to_windowed_array(self.LiveData['ActualPos'][d], diff_angle)
                self.update_scales(d)
                
                print diff_angle
                print ori_threshold
                print "-----"

                threshU = ori_threshold
                threshL = -ori_threshold
                method = 1      # dist
                polarity = 2    # less than (inverted)

            else:        # fingers
                finger_idx = d-2
                if np.where(finger_dofs_to_judge == finger_idx)[0].size > 0:

                    thresh = self.tsc_mdf.finger_threshold[finger_idx]
                    method = self.tsc_mdf.finger_threshold_judging_method[finger_idx]
                    polarity = self.tsc_mdf.finger_threshold_judging_polarity[finger_idx]

                    # invert polarities (because we plot "keep out" zones)
                    if (polarity > 0) and (self.tsc_mdf.timed_out_conseq == 0):
                        polarity = ~polarity & 3;

                    # finger_threshold_judging_method: 1=distance (default), 2=absolute
                    if method == 1:  # dist
                        target = self.tsc_mdf.target[8+finger_idx]
                        threshU = target + thresh
                        threshL = target - thresh
                    else:            # abs
                        threshU = thresh
                
            # insert new data to plotting arrays
            self.LiveData['ThreshUpper'][d] = self.add_to_windowed_array(self.LiveData['ThreshUpper'][d], threshU)
            self.LiveData['ThreshLower'][d] = self.add_to_windowed_array(self.LiveData['ThreshLower'][d], threshL)
            self.LiveData['JudgingMethod'][d] = self.add_to_windowed_array(self.LiveData['JudgingMethod'][d], method)
            self.LiveData['JudgingPolarity'][d] = self.add_to_windowed_array(self.LiveData['JudgingPolarity'][d], polarity)

        self.LiveData['TaskStateNo'] = self.add_to_windowed_array(self.LiveData['TaskStateNo'], self.tsc_mdf.id)

        if self.ets_mdf is not None:
            self.LiveData['TaskStateVerdict'][-2] = self.ets_mdf.outcome
            self.LiveData['TaskStateVerdict'][-1] = self.ets_mdf.outcome
            self.LiveData['TaskStateVerdict'] = self.add_to_windowed_array(self.LiveData['TaskStateVerdict'], self.ets_mdf.outcome)
            self.ets_mdf = None
        else:
            self.LiveData['TaskStateVerdict'] = self.add_to_windowed_array(self.LiveData['TaskStateVerdict'], 1)

    def add_to_windowed_array(self, arr, data):
        arr = np.append(arr, data)
        arr = np.delete(arr, 0)
        return arr

    def load_config(self):
        self.config = ConfigObj(self.config_file, unrepr=True)

    def reload_config(self):
        self.load_config()
        for ax in self.figure.axes:
            self.figure.delaxes(ax)
        self.figure.clear()
        self.draw()
        self.init_plot(True)
        self.init_legend()
        self.redraw_yticks = True

 
    def init_plot(self, clear=False):
        self.figure.subplots_adjust(bottom=.05, right=.98, left=.08, top=.98, hspace=0.07)
        
        trans_dim = 0
        if 'plot_translation' in self.config['config']:
            trans_dim = self.config['config']['plot_translation']
       
        ori_dim = 0
        if 'plot_orientation' in self.config['config']:
            ori_dim = self.config['config']['plot_orientation']
            
        finger_dims = []
        if 'active_finger_dims' in self.config['config']:
            finger_dims = self.config['config']['active_finger_dims'] 
        
        force_dims = []
        if 'active_force_dims' in self.config['config']:
            force_dims = self.config['config']['active_force_dims'] 

        torque_dims = []
        if 'active_torque_dims' in self.config['config']:
            torque_dims = self.config['config']['active_torque_dims'] 
        
        axis_labels = []
        self.dims = []
        if trans_dim == 1:
            self.dims.append(1)
            axis_labels.extend(['XYZ tgt dist'])
        if ori_dim == 1:
            self.dims.append(2)
            axis_labels.extend(['ORI tgt dist'])
        if finger_dims:
            for f in finger_dims:
                if (f>0) and (f<=10):
                    self.dims.extend([f+2])
                    axis_labels.extend(['finger #%d' % f])
                else:
                    print "Warning: invalid finger dim specified: %f, skipping.." % f
        if force_dims:
            force_labels = ['ifx', 'ify', 'ifz', 'mfx', 'mfy', 'mfz', 'rfx', \
                            'rfy', 'rfz', 'lfx', 'lfy', 'lfz', 'tfx', 'tfy', 'tfz']
            for f in force_dims:
                if (f>0) and (f<=15):
                    self.dims.extend([f+12])
                    axis_labels.extend(['force #%d (%s)' % (f, force_labels[f-1])])
                else:
                    print "Warning: invalid force dim specified: %d, skipping.." % f
        if torque_dims:
            for f in torque_dims:
                if (f>0) and (f<=28):
                    self.dims.extend([f+27])
                    axis_labels.extend(['trq #%d' % f])
                else:
                    print "Warning: invalid torque dim specified: %d, skipping.." % f
      
        self.nDims = trans_dim + ori_dim + len(finger_dims) + len(force_dims) + len(torque_dims)
        self.xN = self.config['config']['number_of_data_points']
        self.bg = self.config['marked_task_states'].keys()

        self.max_scale = self.config['config']['max_scale']
        if len(self.max_scale) < self.nDims:
            self.max_scale.extend([np.finfo(float).eps] * (self.nDims - len(self.max_scale)))
        
        self.min_scale = self.config['config']['min_scale']
        if len(self.min_scale) < self.nDims:
            self.min_scale.extend([-np.finfo(float).eps] * (self.nDims - len(self.min_scale)))
        

        self.ax = []
        self.old_size = []
        self.ax_bkg = []
        self.finger_pos = []
        self.zones = {}
        self.zone_idx = []

        for d in range(self.nDims):
            ax = self.figure.add_subplot(self.nDims,1,d+1)
            self.reset_axis(ax, axis_labels[d])
            self.draw()
            
            bbox_width = ax.bbox.width
            bbox_height = ax.bbox.height
            if clear == True:
                # force to redraw
                bbox_width = 0  
                bbox_height = 0

            self.old_size.append( (bbox_width, bbox_height) )
            self.ax_bkg.append(self.copy_from_bbox(ax.bbox))

            line, = ax.plot([], [], 'k-', lw=1.0, aa=None, animated=True)
            line.set_xdata(range(self.xN))
            line.set_ydata([0.0]*self.xN)
            self.finger_pos.append(line)
            self.draw()
    
            self.zones[d] = []
            self.zone_idx.append(0)
            for z in range(60):
                patch = ax.add_patch(Polygon([[0, 1e-12],[1e-12, 0],[1e-12, 1e-12],[0, 1e-12]], fc='none', ec='none', fill=True, closed=True, aa=None, animated=True))
                self.zones[d].append(patch)
                self.draw()

            self.ax.append(ax)


    def reset_axis(self, ax, label):
        ax.grid(True)
        ax.set_xlim(0, self.xN-1)
        ax.set_autoscale_on(False)
        ax.set_ylabel(label, fontsize='small')
        ax.get_xaxis().set_ticks([])
        ax.yaxis.set_major_formatter(FormatStrFormatter('%.02f'))
        for tick in ax.get_yticklabels():
            tick.set_fontsize(9) 

        
    def init_legend(self):
        legnd = []

        line = matplotlib.lines.Line2D([0,0], [0,0], color='k')
        legnd.append(line)

        for d in range(len(self.bg)):
            b_color = self.config['marked_task_states'][self.bg[d]]['color']
            patch = Polygon([[0,0],[0, 0],[0, 0],[0, 0]], fc=b_color, ec='none', fill=True, closed=True, alpha=0.65)
            legnd.append(patch)

        self.figure.legend(legnd, ['Position']+self.bg, loc='lower center', frameon=False, ncol=20, prop={'size':'11'}, columnspacing=.5)
        self.draw()
        
        
    def plot_bg_mask(self, ax, idx, x, mask, ylim, fc, ec, hatch, alpha):
        # Find starts and ends of contiguous regions of true values in mask because
        # we want just one patch object per contiguous region
        _mask = np.asarray(np.insert(mask, 0, 0), dtype=int)
        begin_indices = np.where( np.diff( _mask) == 1)[0]

        _mask = np.asarray(np.append(mask, 0), dtype=int)
        end_indices = np.where( np.diff( _mask) == -1)[0]

        # Get DeltaX
        dx = np.mean( np.diff(x))

        # Get YLim if it was not given
        if len(ylim) == 0:
            ylim = ax.get_ylim()

        z = self.zones[idx]
        a = self.zone_idx[idx]

        for i in range(len( begin_indices)):
            b = begin_indices[i]
            e = end_indices[i]
            xb = x[b] - dx/2;
            xe = x[e] + dx/2;
            
            patch = z[a]
            patch.set_xy([[xb, ylim[0]],[xe, ylim[0]],[xe, ylim[1]],[xb, ylim[1]]])
            patch.set_edgecolor(ec)
            patch.set_facecolor(fc)
            patch.set_hatch(hatch)
            patch.set_alpha(alpha)

            ax.draw_artist(patch)
            a = a + 1
            
        self.zone_idx[idx] = a


    def timer_event(self):
        done = False
        while not done:
            msg = CMessage()
            rcv = self.mod.ReadMessage(msg, 0)
            if rcv == 1:
                msg_type = msg.GetHeader().msg_type

                if msg_type == rc.MT_TASK_STATE_CONFIG:
                    self.tsc_mdf = rc.MDF_TASK_STATE_CONFIG()
                    copy_from_msg(self.tsc_mdf, msg)

                elif msg_type == rc.MT_ROBOT_CONTROL_SPACE_ACTUAL_STATE:
                    mdf = rc.MDF_ROBOT_CONTROL_SPACE_ACTUAL_STATE()
                    copy_from_msg(mdf, msg)

                    self.fdbk_actual_cori = mdf.CoriMatrix

                    self.fdbk_actual_pos = []
                    self.fdbk_actual_pos.extend(mdf.pos)
                    self.fdbk_actual_pos.extend(self.fdbk_percepts)
                    self.fdbk_actual_pos.extend(self.fdbk_torques)
                   
                    self.update_judging_data()

                elif msg_type == rc.MT_GROBOT_SEGMENT_PERCEPTS:
                    mdf = rc.MDF_GROBOT_SEGMENT_PERCEPTS()
                    copy_from_msg(mdf, msg)
                    self.fdbk_percepts = []
                    self.fdbk_percepts.extend(mdf.ind_force[:])
                    self.fdbk_percepts.extend(mdf.mid_force[:]) 
                    self.fdbk_percepts.extend(mdf.rng_force[:]) 
                    self.fdbk_percepts.extend(mdf.lit_force[:]) 
                    self.fdbk_percepts.extend(mdf.thb_force[:])

                elif msg_type == rc.MT_GROBOT_RAW_FEEDBACK:
                    mdf = rc.MDF_GROBOT_RAW_FEEDBACK()
                    copy_from_msg(mdf, msg)
                    self.fdbk_torques = mdf.j_trq
                    
                elif msg_type == rc.MT_END_TASK_STATE:
                    self.ets_mdf = rc.MDF_END_TASK_STATE()
                    copy_from_msg(self.ets_mdf, msg)

                elif msg_type == rc.MT_PING:
                    respond_to_ping(self.mod, msg, 'SimpleJudgeDisplay')

                elif msg_type == MT_EXIT:
                    self.exit()
                    done = True
                    
            else:
                done = True

        self.update_plot()
        
        
        
    def update_plot(self):
        if self.paused == False:
            LiveData = self.LiveData
        else:
            LiveData = self.PausedData

        for i in range(self.nDims):
            ax = self.ax[i]
            d = self.dims[i] - 1

            current_size = ax.bbox.width, ax.bbox.height
            if self.old_size[i] != current_size:
                self.old_size[i] = current_size
                self.draw()
                self.ax_bkg[i] = self.copy_from_bbox(ax.bbox)

            self.restore_region(self.ax_bkg[i])

            self.zone_idx[i] = 0
            
            min_scale = LiveData['min_scale'][d];
            if 'min_scale' in self.config['config']:
                min_scale = self.min_scale[i]
            max_scale = LiveData['max_scale'][d];
            if 'max_scale' in self.config['config']:
                max_scale = self.max_scale[i]
            ax.set_ylim(min_scale, max_scale)
            yLimG = ax.get_ylim()

            for b in range(len(self.bg)):
                b_id = self.config['marked_task_states'][self.bg[b]]['id']
                b_color = self.config['marked_task_states'][self.bg[b]]['color']

                mask = np.where(LiveData['TaskStateNo']==b_id, 1, 0)
                if np.sum(mask) > 0:
                    self.plot_bg_mask(ax, i, range(self.xN), mask, [], b_color, 'none', None, 0.65)
                else:
                    # always draw patch for all colors so that they will always show up in the legend
                    z = self.zones[i]
                    patch = z[self.zone_idx[i]]
                    patch.set_xy([[0, 0],[0, 0],[0, 0],[0, 0]])
                    ax.draw_artist(patch)
                    self.zone_idx[i] = self.zone_idx[i] + 1


            # finger_threshold_judging_method: 1=distance, 2=absolute
            # finger threshold_judging_polarity: 1 = <, 2 = >
            methods = ~np.isnan(LiveData['JudgingMethod'][d])
            if np.sum(methods) > 0:
                methods = np.unique(LiveData['JudgingMethod'][d][methods])
                for m in range(len(methods)):
                    method = methods[m]
                    met_mask = np.where(LiveData['JudgingMethod'][d] == method, True, False)
                    polaritys = np.unique(LiveData['JudgingPolarity'][d][met_mask])

                    for p in range(len(polaritys)):
                        polarity = polaritys[p]
                        pol_mask = np.where(LiveData['JudgingPolarity'][d] == polarity, True, False)
                        mask = met_mask & pol_mask

                        yLimUs = np.unique(LiveData['ThreshUpper'][d][mask])

                        for b in range(len(yLimUs)):
                            yLimU = yLimUs[b]
                            submask = np.where(LiveData['ThreshUpper'][d] == yLimU, True, False) & mask

                            if method == 1: # dist
                                yLimLs = np.unique(LiveData['ThreshLower'][d][submask])

                                for k in range(len(yLimLs)):
                                    yLimL = yLimLs[k]
                                    submask2 = np.where(LiveData['ThreshLower'][d] == yLimL, True, False) & submask

                                    if polarity == 1:  # <
                                        self.plot_bg_mask(ax, i, range(self.xN), submask2, [yLimL, yLimU], 'none', 'black', '//', 1)
                                    else:
                                        self.plot_bg_mask(ax, i, range(self.xN), submask2, [yLimG[0], yLimL], 'none', 'black', '//', 1)
                                        self.plot_bg_mask(ax, i, range(self.xN), submask2, [yLimU, yLimG[1]], 'none', 'black', '//', 1)

                            else:           # abs
                                if polarity == 1: # <
                                    self.plot_bg_mask(ax, i, range(self.xN), submask, [yLimG[0], yLimU], 'none', 'black', '//', 1)
                                else:
                                    self.plot_bg_mask(ax, i, range(self.xN), submask, [yLimU, yLimG[1]], 'none', 'black', '//', 1)

            fail_mask = np.where(LiveData['TaskStateVerdict']==0, True, False)
            self.plot_bg_mask(ax, i, range(self.xN), fail_mask, [], 'red', 'none', None, 0.65)

            self.finger_pos[i].set_ydata(LiveData['ActualPos'][d])
            ax.draw_artist(self.finger_pos[i])

            self.blit(ax.bbox)

            if self.zone_idx[i] > 60:
                print "ERROR: too many zones! Increase number of preallocated patches"

        # need to redraw once to update y-ticks
        if self.redraw_yticks == True:
            self.draw() 
            self.redraw_yticks = False


    def pause(self, pause_state):
        self.paused = pause_state
        self.PausedData = copy.deepcopy(self.LiveData)


    def exit(self):
        print "exiting"
        self.parent.exit_app()


    def stop(self):
        print 'disconnecting'
        self.mod.SendSignal(rc.MT_EXIT_ACK)
        self.mod.DisconnectFromMMM()
Ejemplo n.º 55
0
def show_fit_at_position(mcmc_set, fit_value, position, fit_name):
    """Create the result page showing the fit quality at the given position.

    Parameters
    ----------
    mcmc_set : MCMCSet object
        The set of MCMC chains
    fit_value : float
        The quality of fit at the given position.
    position : numpy.array
        Array of (log10-transformed) parameter values at the given position.
    fit_name : string
        A shorthand name for the fit position, e.g., "max_likelihood". Should
        conform to rules of Python variable naming (no spaces, doesn't
        start with a number, etc.).

    Returns
    -------
    A result object containing the fit value and the link to the accompanying
    HTML plot page, if any.
    """

    # If the MCMC object does not have a fit_plotting_function defined
    # (for example, if it is a base MCMC object), then don't create a
    # plot for visualization.
    if not hasattr(mcmc_set.chains[0], 'fit_plotting_function'):
        return Result(fit_value, None)

    # Prepare html for page showing plots at position
    html_str = "<html><head><title>Simulation of %s " \
               "with %s parameter values</title></head>\n" \
               % (mcmc_set.name, fit_name)
    html_str += "<body><p>Simulation of %s with %s " \
                "parameter values</p>\n" % (mcmc_set.name, fit_name)

    # Show the plot vs. the data at the position
    fig = mcmc_set.chains[0].fit_plotting_function(position=position)
    img_filename = '%s_%s_plot.png' % (mcmc_set.name, fit_name)
    fig.savefig(img_filename)
    html_str += '<p><img src="%s" /></p>' % img_filename

    # Show the plot of all observables at the position
    chain0 = mcmc_set.chains[0]
    tspan = chain0.options.tspan
    observables = chain0.options.model.observables
    x = chain0.simulate(position=position, observables=True)

    fig = Figure()
    ax = fig.gca()
    lines = []
    for o in observables:
        line = ax.plot(tspan, x[o.name])
        lines += line
    ax.set_title("Observables at %s" % fit_name)
    fig.legend(lines, [o.name for o in observables], 'lower right')
    canvas = FigureCanvasAgg(fig)
    fig.set_canvas(canvas)

    img_filename = '%s_%s_species.png' % (mcmc_set.name, fit_name)
    fig.savefig(img_filename)
    html_str += '<p><img src="%s" /></p>' % img_filename

    # Print the parameter values for the position as a dict that can be
    # used to override the initial values
    html_str += '<pre>%s_params = {\n' % fit_name
    for i, p in enumerate(chain0.options.estimate_params):
        html_str += "\t'%s': %.17g,\n" % \
                    (p.name, 10 ** position[i])
    html_str += '}</pre>'

    html_str += '</body></html>'

    # Create the html file
    html_filename = '%s_%s_plot.html' % (mcmc_set.name, fit_name)
    with open(html_filename, 'w') as f:
        f.write(html_str)

    return Result(fit_value, html_filename)
Ejemplo n.º 56
0
def getLegendGraphic(request, dataset):
    """
    Parse parameters from request that looks like this:

    http://webserver.smast.umassd.edu:8000/wms/NecofsWave?
    ELEVATION=1
    &LAYERS=hs
    &TRANSPARENT=TRUE
    &STYLES=facets_average_jet_0_0.5_node_False
    &SERVICE=WMS
    &VERSION=1.1.1
    &REQUEST=GetLegendGraphic
    &FORMAT=image%2Fpng
    &TIME=2012-06-20T18%3A00%3A00
    &SRS=EPSG%3A3857
    &LAYER=hs
    """
    styles = request.GET["styles"].split("_")
    try:
        climits = (float(styles[3]), float(styles[4]))
    except:
        climits = (None, None)
    variables = request.GET["layer"].split(",")
    plot_type = styles[0]
    colormap = styles[2].replace('-', '_')

    # direct the service to the dataset
    # make changes to server_local_config.py
    if settings.LOCALDATASET:
        url = settings.LOCALDATASETPATH[dataset]
    else:
        url = Dataset.objects.get(name=dataset).path()
    nc = netCDF4.Dataset(url)

    """
    Create figure and axes for small legend image
    """
    #from matplotlib.figure import Figure
    from matplotlib.pylab import get_cmap
    fig = Figure(dpi=100., facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figwidth(1*1.3)
    fig.set_figheight(1.5*1.3)

    """
    Create the colorbar or legend and add to axis
    """
    v = cf.get_by_standard_name(nc, variables[0])

    try:
        units = v.units
    except:
        units = ''
    # vertical level label
    if v.ndim > 3:
        units = units + '\nvertical level: %s' % _get_vertical_level(nc, v)
    if climits[0] is None or climits[1] is None:  # TODO: NOT SUPPORTED RESPONSE
            #going to have to get the data here to figure out bounds
            #need elevation, bbox, time, magnitudebool
            CNorm = None
            ax = fig.add_axes([0, 0, 1, 1])
            ax.grid(False)
            ax.text(.5, .5, 'Error: No Legend\navailable for\nautoscaled\ncolor styles!', ha='center', va='center', transform=ax.transAxes, fontsize=8)
    elif plot_type not in ["contours", "filledcontours"]:
        #use limits described by the style
        ax = fig.add_axes([.01, .05, .2, .8])  # xticks=[], yticks=[])
        CNorm = matplotlib.colors.Normalize(vmin=climits[0],
                                            vmax=climits[1],
                                            clip=False,
                                            )
        cb = matplotlib.colorbar.ColorbarBase(ax,
                                              cmap=get_cmap(colormap),
                                              norm=CNorm,
                                              orientation='vertical',
                                              )
        cb.set_label(units, size=8)

    else:  # plot type somekind of contour
        if plot_type == "contours":
            #this should perhaps be a legend...
            #ax = fig.add_axes([0,0,1,1])
            fig_proxy = Figure(frameon=False, facecolor='none', edgecolor='none')
            ax_proxy = fig_proxy.add_axes([0, 0, 1, 1])
            CNorm = matplotlib.colors.Normalize(vmin=climits[0], vmax=climits[1], clip=True)
            #levs = numpy.arange(0, 12)*(climits[1]-climits[0])/10
            levs = numpy.linspace(climits[0], climits[1], 11)
            x, y = numpy.meshgrid(numpy.arange(10), numpy.arange(10))
            cs = ax_proxy.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(colormap))

            proxy = [plt.Rectangle((0, 0), 0, 0, fc=pc.get_facecolor()[0]) for pc in cs.collections]

            fig.legend(proxy, levs,
                       #bbox_to_anchor = (0, 0, 1, 1),
                       #bbox_transform = fig.transFigure,
                       loc = 6,
                       title = units,
                       prop = { 'size' : 8 },
                       frameon = False,
                       )
        elif plot_type == "filledcontours":
            #this should perhaps be a legend...
            #ax = fig.add_axes([0,0,1,1])
            fig_proxy = Figure(frameon=False, facecolor='none', edgecolor='none')
            ax_proxy = fig_proxy.add_axes([0, 0, 1, 1])
            CNorm = matplotlib.colors.Normalize(vmin=climits[0], vmax=climits[1], clip=False,)
            #levs = numpy.arange(1, 12)*(climits[1]-(climits[0]))/10
            levs = numpy.linspace(climits[0], climits[1], 10)
            levs = numpy.hstack(([-99999], levs, [99999]))

            x, y = numpy.meshgrid(numpy.arange(10), numpy.arange(10))
            cs = ax_proxy.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(colormap))

            proxy = [plt.Rectangle((0, 0), 0, 0, fc=pc.get_facecolor()[0]) for pc in cs.collections]

            levels = []
            for i, value in enumerate(levs):
                #if i == 0:
                #    levels[i] = "<" + str(value)
                if i == len(levs)-2 or i == len(levs)-1:
                    levels.append("> " + str(value))
                elif i == 0:
                    levels.append("< " + str(levs[i+1]))
                else:
                    #levels.append(str(value) + "-" + str(levs[i+1]))
                    text = '%.2f-%.2f' % (value, levs[i+1])
                    levels.append(text)
            fig.legend(proxy, levels,
                       #bbox_to_anchor = (0, 0, 1, 1),
                       #bbox_transform = fig.transFigure,
                       loc = 6,
                       title = units,
                       prop = { 'size' : 6 },
                       frameon = False,
                       )

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    nc.close()
    return response
Ejemplo n.º 57
0
class channel_plot:
    '''
    '''

    def __init__(self, interface, toplevel=False, start_t=False, stop_t=False):
        '''
        '''
        self.abort = False
        if not start_t:
            start_t = datetime.utcnow() - timedelta(hours=2)
        if not stop_t:
            stop_t = datetime.utcnow()
        self.update_pending = False
        self.pype = interface
        self.plot_dicts = {}
        if isinstance(start_t, datetime):
            self.start_t = StringVar(value=start_t.strftime(time_format))
        elif isinstance(start_t, str):
            self.start_t = StringVar(value=start_t)
        else:
            raise TypeError('start_t must be string or datetime')
        if isinstance(stop_t, datetime):
            self.stop_t = StringVar(value=stop_t.strftime(time_format))
        elif isinstance(stop_t, str):
            self.stop_t = StringVar(value=stop_t)
        else:
            raise TypeError('stop_t must be string or datetime')
        self.time_interval = [self.start_t.get(), self.stop_t.get()]
        self.ymin = DoubleVar()
        self.ymax = DoubleVar()
        if toplevel:
            self.toplevel = toplevel
        else:
            self.toplevel = Tk.Tk()
        self.status_var = StringVar(value='initializing')
        self._SetupCanvas()
        self._BuildGui()
        if not toplevel:
            Tk.mainloop()

    def _BuildGui(self):
        '''
        '''
        self.removei = IntVar(value=0)
        self.relative_start_time = BooleanVar(value=False)
        self.relative_stop_time = BooleanVar(value=False)
        self.continuous_updates = BooleanVar(value=False)
        self.ManualLimits = BooleanVar(value=False)
        self.LogYScale = BooleanVar(value=False)
        self.ShowGrid = BooleanVar(value=False)
        self.ConnectedPts = BooleanVar(value=True)
        Button(self.toplevel, text="Add Line", command=self._AddSubplot
               ).grid(row=0, column=1)
        self._AddSubplot()
        Button(self.toplevel, text="Gas Line Temps", command=self._PlotGasLines
               ).grid(row=0, column=2)
        Button(self.toplevel, text="Amps+Cell Temps", command=self._PlotCell
               ).grid(row=0, column=3)

        Label(self.toplevel, text='Start Time').grid(row=4, column=1)
        start_entry = Entry(self.toplevel, textvariable=self.start_t)
        start_entry.bind('<Return>', self.Update)
        start_entry.bind('<KP_Enter>', self.Update, '+')
        start_entry.grid(row=4, column=2, columnspan=2)
        Checkbutton(self.toplevel, text='Hours ago',
                    variable=self.relative_start_time).grid(row=4, column=4,
                                                            sticky='W')

        Label(self.toplevel, text='Stop Time').grid(row=5, column=1)
        stop_entry = Entry(self.toplevel, textvariable=self.stop_t)
        stop_entry.bind('<Return>', self.Update)
        stop_entry.bind('<KP_Enter>', self.Update, '+')
        stop_entry.grid(row=5, column=2, columnspan=2)
        Checkbutton(self.toplevel, text='Now',
                    variable=self.relative_stop_time).grid(row=5, column=4,
                                                           sticky='W')

        Label(self.toplevel, text='Y limits (min-max)').grid(row=7, column=1)
        ymin = Entry(self.toplevel, textvariable=self.ymin)
        ymin.grid(row=7, column=2)
        ymin.bind('<Return>', self.Update)
        ymin.bind('<KP_Enter>', self.Update, '+')
        ymax = Entry(self.toplevel, textvariable=self.ymax)
        ymax.grid(row=7, column=3)
        ymax.bind('<Return>', self.Update)
        ymax.bind('<KP_Enter>', self.Update, '+')
        Checkbutton(self.toplevel, text='Manual Y-limits', variable=self.ManualLimits
                    ).grid(row=8, column=1)
        Checkbutton(self.toplevel, text='Log Y-scale', variable=self.LogYScale
                    ).grid(row=8, column=2)
        Checkbutton(self.toplevel, text='Show Grid', variable=self.ShowGrid
                    ).grid(row=9, column=1)
        Checkbutton(self.toplevel, text='Connected Points', variable=self.ConnectedPts
                    ).grid(row=9, column=2)

        Button(self.toplevel, text="Update All", command=self.Update
               ).grid(row=10, column=1)
        Button(self.toplevel, text="Save Plot", command=self.SaveFigure
               ).grid(row=10, column=2)
        Button(self.toplevel, text="Save Json", command=self.SaveJson
               ).grid(row=10, column=3)
        Checkbutton(self.toplevel, text='Continuous (Button above to start)',
                    variable=self.continuous_updates
                    ).grid(row=11, column=1, columnspan=2)
        self.status_var.set('done')

        Label(self.toplevel, textvariable=self.status_var).grid(row=20,
                                                                column=1,
                                                                columnspan=2)

    def _SetupCanvas(self):
        '''
        '''
        self.figure = Figure()
        self.figure.subplots_adjust(left=0.15, bottom=0.2)
        self.subfigure = self.figure.add_subplot(1,1,1)
        self.notebook = Notebook(self.toplevel)
        self.notebook.grid(row=1, column=1, rowspan=3, columnspan=3, sticky='nsew')
        self.canvas = FigureCanvasTkAgg(self.figure, master=self.toplevel)
        self.canvas.show()
        self.canvas.get_tk_widget().grid(row=0, column=0, rowspan=10)

    def _AddSubplot(self):
        '''
        '''
        plotnum = len(self.notebook.tabs())
        self.plot_dicts[plotnum] = {}
        frame = Frame(self.notebook)
        frame.pack(side='top', fill='both', expand='y')
        self.plot_dicts[plotnum]['xname'] = StringVar(value='None')
        self.plot_dicts['xunit'] = False
        self.plot_dicts[plotnum]['yname'] = StringVar(value='None')
        self.plot_dicts['yunit'] = False
        Label(frame, text='X Channel').grid(row=0, column=0)
        Label(frame, text='Y Channel').grid(row=1, column=0)
        OptionMenu(frame, self.plot_dicts[plotnum]['xname'],
                   "None", "time", "dpph_field", *self.pype.EligibleLoggers()
                   ).grid(row=0, column=1, sticky='ew')
        OptionMenu(frame, self.plot_dicts[plotnum]['yname'],
                   "None", "dpph_field", *self.pype.EligibleLoggers()
                   ).grid(row=1, column=1, sticky='ew')
        self.notebook.add(frame, text='line:'+str(plotnum))

    def _SetStartStop(self, event=None):
        '''
        '''
        try:
            if self.relative_stop_time.get():
                stop_time = datetime.utcnow()
            else:
                stop_time = datetime.strptime(self.stop_t.get(), time_format)
            if self.relative_start_time.get():
                hours = float(self.start_t.get())
                start = datetime.utcnow() - timedelta(hours=hours)
            else:
                start = datetime.strptime(self.start_t.get(), time_format)
            assert (start < stop_time)
            self.time_interval[0] = start.strftime(time_format)
            self.time_interval[1] = stop_time.strftime(time_format)
        except ValueError:
            showwarning('Warning', 'invalid time format, must match yyyy-mm-ddThh:mm:ssZ')
            raise TimeFormatError("invalid start or stop time format")
        except AssertionError:
            showwarning('Warning', 'time order error, stop time must be after start time')
            raise TimeOrderError("stop time must be after start time")

    def Update(self, event=None, tab='All', unpend=False):
        '''
            Call whatever sequence is needed to update local data and redraw
            the plot
        '''
        if self.abort:
            self.abort = False
            return
        if unpend:
            self.update_pending = False
        self.status_var.set('updating!')
        if tab == 'All':
            tab = range(len(self.notebook.tabs()))
        elif isinstance(tab, int):
            tab = [tab]
        else:
            raise ValueError('tab should be "All" or an int')
        try:
            self._SetStartStop(event=None)
        except:
            print('SetStartStop problems')
            self.abort = True
            
        self.subfigure.clear()
        for tabi in tab:
            if tabi > len(self.subfigure.get_lines()):
                print('wtf')
            elif tabi == len(self.subfigure.get_lines()):
                self._UpdateData(tab=tabi)
                self._MakePlot(tab=tabi)
            else:
                self._UpdateExisting(tab=tabi)
        self.figure.legends = []
        self.figure.legend(*self.subfigure.get_legend_handles_labels())
        self.figure.legends[0].draggable(True)
        self.canvas.draw()
        self.status_var.set('updated at: ' +
                            datetime.utcnow().strftime(time_format))
        if (self.continuous_updates.get() and self.relative_stop_time.get() and
                 not self.update_pending):
            self.update_pending = True
            self.toplevel.after(10000, lambda: self.Update(unpend=True))

    def _UpdateData(self, tab=0):
        '''
        '''
        try:
            yname = self.plot_dicts[tab]['yname'].get()
            ychdat = self.pype.GetTimeSeries(yname, self.time_interval[0],
                                             self.time_interval[1])
            if self.plot_dicts[tab]['xname'].get() == 'time':
                xchdat = (ychdat[0], ychdat[0], 'time' * len(ychdat[0]))
            else:
                xname = self.plot_dicts[tab]['xname'].get()
                xchdat = self.pype.GetTimeSeries(xname, self.time_interval[0],
                                                 self.time_interval[1])
            if tab > 0 and ychdat[0]:
                assert xchdat[2][0] == self.plot_dicts['xunit'], 'x units'
                assert ychdat[2][0] == self.plot_dicts['yunit'], 'y units'

            self.xdata = []
            self.ydata = []
            if ychdat[0]:
                for tx, x in zip(xchdat[0], xchdat[1]):
                    xtmp = False
                    ytmp = False
                    dt = timedelta(seconds=60)
                    for ty, y in zip(ychdat[0], ychdat[1]):
                        if abs(ty - tx) < dt:
                            dt = abs(ty - tx)
                            xtmp = x
                            ytmp = y
                    if xtmp and ytmp:
                        self.xdata.append(xtmp)
                        self.ydata.append(ytmp)
                [self.xdata, self.ydata] = zip(*sorted(zip(self.xdata,
                                                           self.ydata)))
                self.plot_dicts['xunit'] = xchdat[2][0]
                self.plot_dicts['yunit'] = ychdat[2][0]
        except AssertionError as e:
            print('*'*60, '\n the', e[0], 'do not match the 0th line', '*'*60)

    def _UpdateExisting(self, tab=0):
        '''
        '''
        try:
            yname = self.plot_dicts[tab]['yname'].get()
            ychdat = self.pype.GetTimeSeries(yname, self.time_interval[0],
                                             self.time_interval[1])
            if self.plot_dicts[tab]['xname'].get() == 'time':
                xchdat = (ychdat[0], ychdat[0], 'time' * len(ychdat[0]))
            else:
                xname = self.plot_dicts[tab]['xname'].get()
                xchdat = self.pype.GetTimeSeries(xname, self.time_interval[0],
                                                 self.time_interval[1])
            if tab > 0 and ychdat[0]:
                assert xchdat[2][0] == self.plot_dicts['xunit'], 'x units'
                assert ychdat[2][0] == self.plot_dicts['yunit'], 'y units'

            self.xdata = []
            self.ydata = []
            if ychdat[0]:
                for tx, x in zip(xchdat[0], xchdat[1]):
                    xtmp = False
                    ytmp = False
                    dt = timedelta(seconds=60)
                    for ty, y in zip(ychdat[0], ychdat[1]):
                        if abs(ty - tx) < dt:
                            dt = abs(ty - tx)
                            xtmp = x
                            ytmp = y
                    if xtmp and ytmp:
                        self.xdata.append(xtmp)
                        self.ydata.append(ytmp)
                [self.xdata, self.ydata] = zip(*sorted(zip(self.xdata,
                                                           self.ydata)))
                self.plot_dicts['xunit'] = xchdat[2][0]
                self.plot_dicts['yunit'] = ychdat[2][0]
            this_line = self.subfigure.get_lines()[tab]
            this_line.set_xdata(array(self.xdata))
            this_line.set_ydata(array(self.ydata))

        except AssertionError as e:
            print('*'*60, '\n the', e[0], 'do not match the 0th line', '*'*60)

    def _MakePlot(self, tab=0):
        '''
        '''
        if self.ConnectedPts.get():
            plotformat='o-'
        else:
            plotformat='o'
        if self.plot_dicts[tab]['xname'].get() == 'time':
            self.subfigure.plot_date(self.xdata, self.ydata, plotformat,
                                          label=self.plot_dicts[tab]['yname'].get())
            self.subfigure.set_xticklabels(self.subfigure.get_xticklabels(),
                                           rotation=-45)
            self.subfigure.xaxis.set_major_formatter(dates.DateFormatter(
                "%m/%d %H:%M"))
            self.subfigure.yaxis.set_major_formatter(ticker.ScalarFormatter(
                useOffset=False))
        else:
            self.subfigure.plot(self.xdata, self.ydata, plotformat,
                                label=self.plot_dicts[tab]['yname'].get())
        self.subfigure.set_title(self.plot_dicts[tab]['yname'].get() +
                                 ' vs ' +
                                 self.plot_dicts[tab]['xname'].get() +
                                 '\n from ' + self.time_interval[0] +
                                 ' to ' + self.time_interval[1])
        xname = self.plot_dicts[tab]['xname'].get().replace('_', ' ')
        xunit = '[' + str(self.plot_dicts['xunit']) + ']'
        self.subfigure.set_xlabel(xname + ' ' + xunit)
        yname = self.plot_dicts[tab]['yname'].get().replace('_', ' ')
        yunit = '[' + str(self.plot_dicts['yunit']) + ']'
        self.subfigure.set_ylabel(yname + ' ' + yunit)
        tickformat = ticker.ScalarFormatter(useOffset=False)
        if self.ManualLimits.get():
            self.subfigure.set_ylim(bottom=self.ymin.get(), top=self.ymax.get())
        if self.LogYScale.get():
            self.subfigure.set_yscale('log')
        if self.ShowGrid.get():
            self.subfigure.grid(b=True, which='major')
            self.subfigure.grid(b=True, which='minor')

    def _PlotGasLines(self):
        '''
        '''
        gas_lines = ['left_gas_line_lower_t',
                     'left_gas_line_upper_t',
                     'right_gas_line_lower_t',
                     'right_gas_line_upper_t']
        self._PlotSet(gas_lines)

    def _PlotCell(self):
        '''
        '''
        sensors = ['kh2_temp', 'kh3_temp', 'waveguide_cell_body_temp',
                   'coldhead_temp']
        self._PlotSet(sensors)

    def _PlotSet(self, channels):
        '''
            Plots a set of channels on common axes
        '''
        for plotn, channel in enumerate(channels):
            if (len(self.plot_dicts)-2) <= plotn:
                self._AddSubplot()
            self.plot_dicts[plotn]['xname'].set('time')
            self.plot_dicts[plotn]['yname'].set(channel)
        self.start_t.set('3')
        self.relative_start_time.set(True)
        self.relative_stop_time.set(True)
        self.continuous_updates.set(True)
        self.Update()

    def SaveFigure(self):
        '''
        '''
        file_extensions = [('vectorized', '.eps'), ('adobe', '.pdf'),
                           ('image', '.png'), ('all', '.*')]
        outfile = asksaveasfilename(defaultextension='.pdf',
                                    filetypes=file_extensions)
        self.figure.savefig(outfile)


    def SaveJson(self):
        '''
        '''
        outfile = asksaveasfile(defaultextension='.json')
        outdict = {'xunit':self.plot_dicts['xunit'],
                   'yunit':self.plot_dicts['yunit']
                  }
        for tab in range(len(self.plot_dicts)-2):
            outdict[tab] = {}
            outdict[tab]['xname']=self.plot_dicts[tab]['xname'].get()
            outdict[tab]['yname']=self.plot_dicts[tab]['yname'].get()
            this_line = self.subfigure.get_lines()[tab]
            if outdict['xunit'] == 't':
                outdict[tab]['xdata'] = [str(t) for t in this_line.get_xdata()]
            else:
                outdict[tab]['xdata'] = list(this_line.get_xdata())
            outdict[tab]['ydata'] = list(this_line.get_ydata())

        dump(outdict, outfile, indent=4)
        outfile.close()
class DaysimeterData:
    """Takes in  Daysimeter data and creates plots for that data"""
    def __init__(self): 
        """Initializes the DaysimeterData instance for plotting
        
        Initializes a figure, creates a placeholder subplot, then adds the
        figure to a canvas
        
        """
        self.fig = Figure(figsize=(600, 400), dpi=72, facecolor=(1, 1, 1), 
                          edgecolor = (0, 0, 0))    
        self.fig.add_subplot(111)
        self.values_set = False
        self.ax_dict = {}
        self.plot_tup = []
        self.timestamps = None
        self.data = None
        self.attrs = None
        self.canvas = FigureCanvas(self.fig)
        self.fontP = FontProperties()
        self.fontP.set_size('medium')
        
    def show_plots(self, button_names):
        """Show the created plots
        
        button_group - Group of buttons with buttons names matching the names
                       of the data values (e.g. Lux, CS, etc.)
                            
        """
        # Only tries to show plots once the data and timestamps have been set
        if self.values_set:
            # Iterates through the buttons and gets their names
            # If its name is matches an axis name, show the axis, otherwise 
            # hide it
            for name in self.ax_dict:
                if name in button_names:
                    self.ax_dict[name].set_visible(True)
                else:
                    self.ax_dict[name].set_visible(False)
            
            
    def get_plot(self):
        """Return the canvas for drawing"""
        return self.canvas
        
    def set_values(self, timestamps, data, filetype):  
        """Set the daysimeter values from a file
        
        times - data structure of datetimes containing the timestamps of the 
                daysimeter data
        data - dict of the the different kinds of data taken in from the 
               daysimeter 
        filetype - a string that is either 'cdf' or 'txt'
        
        Sets the timestamps, the data from the daysimeter (lux, CS, etc.) then 
        smooths them out.
        
        """
        self.timestamps = timestamps
        self.data = data
        if filetype == 'cdf':
            self.attrs = data['attrs']
            del data['attrs']
        self.values_set = True
        
    def make_plots(self):
        """Create the plots from the data."""
        
        colors = ('aqua', 'black', 'fuchsia', 'gray', 'lime', 'maroon', 
                  'navy', 'olive', 'orange', 'purple', 'silver', 'teal',
                  'white', 'yellow')
        linear_y = {'CS', 'activity'}
        main_ax = None
        names = self.get_data_names()
        self.plots = []
        
        self.ordered_names = []
        lower_names = []
        if 'red' in names:
            self.ordered_names.append('red')
        if 'green' in names:
            self.ordered_names.append('green')
        if 'blue' in names:
            self.ordered_names.append('blue')
        if 'illuminance' in names:
            self.ordered_names.append('illuminance')
        if 'CLA' in names:
            self.ordered_names.append('CLA')
        if 'CS' in names:
            self.ordered_names.append('CS')
        if 'activity' in names:
            self.ordered_names.append('activity')
        names.sort()
        for name in self.ordered_names:
            lower_names.append(string.lower(name))
        for name in names:
            if name == 'logicalArray':
                continue
            if string.lower(name) not in lower_names:
                self.ordered_names.append(name)
        
        main_ax = self.fig.add_subplot(111)
        main_ax.plot(self.timestamps, 
                     ones(len(self.timestamps)), visible=False)
        main_ax.set_yticklabels([])
        # Iterates through the sets of values (lux, CS, CLA, etc.) and creates 
        # axes for them and stores the axes in a dictionary mapped with their 
        # name e.g. ax_dict['Lux'] returns the lux axis
        for name, color in zip(self.ordered_names, colors):
            if string.lower(name) in ['red', 'green', 'blue']:
                color = name
            # Makes the rest of the values 'children' of the the main, using
            # the x axis of 'main, while creating thei own y axes
            self.ax_dict[name] = main_ax.twinx()
            if name in linear_y:
                self.ax_dict[name].set_yscale('linear')
            else:
                self.ax_dict[name].set_yscale('log')
            self.plots.extend(self.ax_dict[name].plot(self.timestamps,
                         self.data[name], color=color, alpha=0.8,
                         label=name))
            # Finds the min of the data, then sets that as the the lower y
            # bound of the plot to better align the graphs vertically    
            minimum = min(self.data[name])
            self.ax_dict[name].set_ybound(lower=minimum)
            self.ax_dict[name].tick_params(axis='y', colors=color)
        self.fig.legend(self.plots, self.ordered_names, loc='lower left', ncol=3, prop = self.fontP)
        self.fig.subplots_adjust(bottom=0.2)
        self.canvas = FigureCanvas(self.fig)
        
    def smooth(self):
        """Applies a lowpass filter to smooth out the data"""
        names = self.get_data_names()
        for name in names:
            if name != 'Activity':
                self.data[name] = lpf.lowpassFilter(self.data[name], 90)
                
    def get_data_names(self):
        """Returns a list of the data names"""
        if not self.attrs:
            return list(self.data.dtype.names)
        else:
            return self.data.keys()
            
    def get_metadata(self):
        """Returns a dictionary of the cdf's attributes"""
        if self.attrs:
            return self.attrs
        else:
            return {}
Ejemplo n.º 59
0
class DrawPlot(QtGui.QMainWindow):
    def __init__(self, sirna_size, query_sequence, sifi_data, off_target_pos_list, region_plot_lst, temp_location,
                 scoret_lst, main_targets, f_in, mode, table_data, parent = None):
        """Class for drawing the plots inside a window."""
        super(DrawPlot, self).__init__(parent)

        # Some plotting settings
        sns.set(style="white", palette="muted", color_codes=True)


        self.sirna_size = sirna_size                    # Size of siRNA chosen by user.
        self.query_sequence = query_sequence            # Query sequence.
        self.query_length = len(self.query_sequence)    # Size of the query sequence.
        self.sifi_data = sifi_data                      # siFi dara in json format file
        self.off_target_pos_list = off_target_pos_list  # Off target position list for design plot
        self.region_plot_lst = region_plot_lst          # Plot for suggested RNAi design region
        self.score_lst = scoret_lst
        self.temp_location = temp_location
        self.main_targets = main_targets
        self.f_in = f_in
        self.mode = mode
        self.home_location = str(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.HomeLocation))
        self.table_data = table_data

        if self.mode == 0:
            self.setWindowTitle('RNAi design plot')
        else:
            self.setWindowTitle('Off-target plot')

        # Image tempfile
        self.temp_img_file = tempfile.mkstemp()

        self.printer = QtGui.QPrinter()
        # Single query mode, get all data
        query = list(general_helpers.iterparse(self.sifi_data))[0]
        # Get number of hits per query
        hit_counter = Counter(player['hit_name'] for player in query)
        hit_overview = hit_counter.most_common()

        dpi = 80
        if self.mode == 0:
            figsize = (13, 4)
        else:
            if len(hit_overview) == 1:
                figsize = (13,5)
            elif len(hit_overview) == 2:
                figsize = (13,6)
            elif len(hit_overview) == 3:
                figsize = (13,8)
            elif len(hit_overview) == 4:
                figsize = (13,10)
            elif len(hit_overview) > 5:
                figsize = (13,20)
                dpi = 65

        self.figure = Figure(figsize =figsize, dpi = dpi, facecolor = '#FFFFFF')
        self.canvas = FigureCanvas(self.figure)
        # use addToolbar to add toolbars to the main window directly!
        #print 'ok'
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.addToolBar(self.toolbar)

        self.main_widget = QtGui.QWidget(self)
        self.setCentralWidget(self.main_widget)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)

        self.createActions()
        self.createMenus()

        self.main_widget.setLayout(layout)

    def plot_design(self):
        """ Plotting the design plot."""

        # Create main figure
        ax1 = self.figure.add_subplot(111)
        def format_coord(x, y):
            return 'Sequence position = %d , Nr. of siRNAs = %d '%(x, y)
        ax1.format_coord = format_coord

        off_target_dict, main_target_dict, efficient_dict, main_hits_histo = general_helpers.get_target_data(self.f_in, self.sirna_size)

        # If there are no hits, we show only the efficient sirnas for designing a construct
        if self.main_targets == []:
            off_target_dict = {}
            main_target_dict = {}
            main_hits_histo = []

        # Off-target position list
        off_targets_pos = set()
        for i in off_target_dict.values():
            off_targets_pos = off_targets_pos | i

        # Main-target position list
        main_targets_plot = set()
        for i in main_target_dict.values():
            main_targets_plot = main_targets_plot | i

        # Efficient position list
        eff_sirna_plot = []
        for i in efficient_dict.values():
            eff_sirna_plot.extend(i)
        eff_sirna_plot.sort()

        # Draw efficiency plot
        eff_sirna_histo = np.bincount(eff_sirna_plot, minlength=self.query_length)
        ax1.plot(eff_sirna_histo, 'r-', label='Efficient siRNA hits')

        # Draw main target histogram
        main_histo = np.bincount(main_hits_histo, minlength=self.query_length)
        ax1.plot(main_histo, 'b-', label='Main target siRNA hits')

        # Draw main targets as green rectangles inside plot figure
        for region in main_targets_plot:
            someX, someY = region, 0.
            currentAxis = self.figure.gca()
            tri1 = Rectangle((someX, someY), 1, self.sirna_size + 3, color='g', alpha=0.2)#, label='green')
            currentAxis.add_patch(tri1)
            tri1.set_clip_on(False)

        # Draw off-targets as red rectangles inside plot figure
        for off_target in off_targets_pos:
            someX, someY = off_target, 0.
            currentAxis = self.figure.gca()
            tri2 = Rectangle((someX, someY), 1, self.sirna_size + 3, color='r', alpha=0.2)#, label='red')
            currentAxis.add_patch(tri2)
            tri2.set_clip_on(False)

        if max(eff_sirna_histo) > self.sirna_size:
            max_y = max(eff_sirna_histo) + 3
        else:
            max_y = self.sirna_size + 3


        ax1.set_ylim([0, max_y])
        x_text = 'mRNA sequence position\n\n'
        ax1.set_xlabel(x_text, fontsize=12)
        ax1.set_ylabel('Nr of siRNAs', color='b', fontsize=12)
        ax1.set_xlim([0, self.query_length])
        ax1.set_title("RNAi design plot\n\n", fontsize=14)
        self.figure.tight_layout()
        p1 = Rectangle((0, 0), 1, 1, fc="g", alpha=0.2)
        p2 = Rectangle((0, 0), 1, 1, fc="r", alpha=0.2)
        p3 = mlines.Line2D([], [], color='r')
        p4 = mlines.Line2D([], [], color='b')
        ax1.legend([p1,p2, p3, p4], ["Main target", "Off target", 'Efficient siRNAs', 'All siRNAs'],
                    bbox_to_anchor=(0., 1.02, 1., .102), loc=4, ncol=4, mode="", borderaxespad=0.5, frameon=True)

        self.figure.savefig(self.temp_img_file[1] + '.png')
        self.canvas.draw()
        return self.temp_img_file[1] + '.png', off_target_dict, main_target_dict

    def plot_offtarget(self):
        """Plotting the off-target plot."""
        max_sirna_count = self.sirna_size

        # Single query mode, get all data
        query = list(general_helpers.iterparse(self.sifi_data))[0]
        # Get number of hits per query
        hit_counter = Counter(player['hit_name'] for player in query)
        efficicent_counter = Counter(player['hit_name'] for player in query if player['is_efficient'])
        hit_overview = hit_counter.most_common()

        table_data = []
        for x in hit_counter.most_common():
            for y in efficicent_counter.most_common():
                if x[0] == y[0]:
                    table_data.append([x[0], x[1], y[1]])
            if x[0] not in list(efficicent_counter):
                table_data.append([x[0], x[1], 0])

        if len(hit_overview) > 5:
            data = table_data[:5]
            data.append([str(len(table_data)-5) + ' More targets', '...', '...'])
        else:
            data = table_data

        nrows = len(hit_overview[:5]) + 1
        ncols = 1

        ### Create main figure
        axes = self.figure.add_subplot(nrows, 1, 1)


        # First plot is table
        axes.axis('off')

        collabel = ("Targets", "Total siRNA hits", "Efficient siRNA hits")
        the_table = axes.table(cellText=data, colLabels=collabel, loc='center', cellLoc='left')
        cellDict = the_table.get_celld()
        for row, col in cellDict:
            cellDict[(row, col)].set_width(0.08)
        the_table.set_fontsize(12)
        the_table.scale(2.1, 2.1)

        p3 = mlines.Line2D([], [], color='r')
        p4 = mlines.Line2D([], [], color='b')

        # Extract all siRNA position, separate for all and efficient siRNAs
        # Show only up to five targets in plot, otherwise it become to much
        counter = 2

        for hit, nr_hits in hit_overview[:5]:
            all_sirna_plot = []
            eff_sirna_plot = []
            for data in query:
                if hit == data['hit_name']:
                    all_sirna_plot.extend(range(int(data['sirna_position']) + 1, int(data['sirna_position']) + self.sirna_size + 1))
                    if data['is_efficient']:
                        eff_sirna_plot.extend(range(int(data['sirna_position']) + 1, int(data['sirna_position']) + self.sirna_size + 1))
            axes = self.figure.add_subplot(nrows, 1, counter)
            # Create a new plot for each hit
            axes.set_title(str(hit), loc='left')#, color='k', fontsize=14, fontweight='bold')

            # Create a histogram of siRNA positions
            all_sirna_histo = np.bincount(all_sirna_plot, minlength=self.query_length)
            eff_sirna_histo = np.bincount(eff_sirna_plot, minlength=self.query_length)

            # Plot both histograms into one plot
            axes.plot(all_sirna_histo, color="b", label='Total siRNA hits')
            axes.plot(eff_sirna_histo, color="r", label='Strand selected siRNAs')

            # Adjust axis
            if np.amax(all_sirna_histo) > max_sirna_count:
                max_sirna_count = np.amax(all_sirna_histo)

            axes.set_ylim([0, max_sirna_count + 3])
            axes.set_xlim([0, self.query_length + 5])

            # Next plot
            counter += 1

        # Some figure settings
        bottom_offset = (nrows-1)
        if bottom_offset > 5:
            bottom_offset = 5

        axes.set_xlabel('\nRNAi trigger sequence position', fontsize=12)
        axes.set_ylabel('siRNA counts per position', fontsize=12)
        def format_coord(x, y):
            return 'Sequence position = %d , Nr. of siRNAs = %d '%(x, y)
        axes.format_coord = format_coord

        self.figure.subplots_adjust(left=0.05, bottom=0.15/bottom_offset, right=0.98, top=0.99, wspace=None, hspace=0.35)
        self.figure.legend([p4, p3], ['All siRNAs', 'Efficient siRNAs'], loc = "lower right", ncol=2, frameon=True,)
        self.figure.tight_layout()
        self.figure.savefig(self.temp_img_file[1] + '.png')
        self.canvas.draw()
        return self.temp_img_file[1] + '.png', table_data


    def print_(self):
        fileName = self.temp_img_file[1] + '.png'

        if fileName:
            image = QtGui.QImage(fileName)

        self.imageLabel = QtGui.QLabel()
        self.imageLabel.setBackgroundRole(QtGui.QPalette.Base)
        self.imageLabel.setSizePolicy(QtGui.QSizePolicy.Ignored,
                QtGui.QSizePolicy.Ignored)
        self.imageLabel.setScaledContents(True)
        self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(image))
        self.scaleFactor = 1.0

        dialog = QtGui.QPrintDialog(self.printer, self)
        if dialog.exec_():
            painter = QtGui.QPainter(self.printer)
            rect = painter.viewport()
            size = self.imageLabel.pixmap().size()
            size.scale(rect.size(), QtCore.Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
            painter.setWindow(self.imageLabel.pixmap().rect())
            painter.drawPixmap(0, 0, self.imageLabel.pixmap())

    def export_image(self):
        """Export the images as png."""
        filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', self.home_location, '*.png')
        if filename:
            if not str(filename).endswith('.png'):
                filename += filename + '.png'
            shutil.copy(self.temp_img_file[1] + '.png', filename)
            if os.path.exists(filename):
                message = 'Image successfully saved!'
            else:
                message = 'Could not save image!'
            self.show_info_message(message)

    def export_table(self):
        filename = QtGui.QFileDialog.getSaveFileName(self, 'Export table', self.home_location, '*.csv')
        if filename:
            if not str(filename).endswith('.csv'):
                filename += filename + '.csv'
            try:
                f_in = open(filename, 'w')
                f_in.write("Targets" + ';' + "Total siRNA hits" + ';' + "Efficient siRNA hits" + '\n')
                for data in self.table_data:
                    f_in.write(str(data[0]) + ';' + str(data[1]) + ';' + str(data[2]) + '\n')
                f_in.close()
                if os.path.exists(filename):
                    message = 'Table successfully saved!'
                else:
                    message = 'Could not save table!'
            except IOError:
                message = 'Permission denied! Please close the file.'

            self.show_info_message(message)

    def show_info_message(self, message):
        """Pop up an info message."""
        QtGui.QMessageBox.information(self,
                                      u"Information",
                                      message)


    def createActions(self):
        self.printAct = QtGui.QAction("&Print...", self, enabled=True, triggered=self.print_)
        self.exitAct = QtGui.QAction("E&xit", self, triggered=self.close)

        self.imgAct = QtGui.QAction("Image file", self, triggered=self.export_image)
        self.tableAct = QtGui.QAction("Table (CSV)", self, triggered=self.export_table)

    def createMenus(self):
        self.fileMenu = QtGui.QMenu("&File", self)
        self.fileMenu.addAction(self.printAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAct)

        # Export menu
        self.exportMenu = QtGui.QMenu("&Save as", self)
        self.exportMenu.addAction(self.imgAct)

        self.exportMenu.addAction(self.tableAct)

        self.menuBar().addMenu(self.fileMenu)
        self.menuBar().addMenu(self.exportMenu)
class VoltagePanel(wx.Panel):
    """
    GUI Window for plotting voltage data.
    """
    #--------------------------------------------------------------------------
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        global filePath
        
        global tV_list
        global V_list
        
        self.create_title("Voltage Panel")
        self.init_plot()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.create_control_panel()
        self.create_sizer()
        
        pub.subscribe(self.OnVoltage, "Voltage")
        pub.subscribe(self.OnVTime, "Time Voltage")
        
        # For saving the plots at the end of data acquisition:
        pub.subscribe(self.save_plot, "Save_All")
        
        self.animator = animation.FuncAnimation(self.figure, self.draw_plot, interval=500, blit=False)
    #end init
    
    #--------------------------------------------------------------------------    
    def create_title(self, name):
        self.titlePanel = wx.Panel(self, -1)
        title = wx.StaticText(self.titlePanel, label=name)
        font_title = wx.Font(16, wx.DEFAULT, wx.NORMAL, wx.BOLD)
        title.SetFont(font_title)
        
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add((0,-1))
        hbox.Add(title, 0, wx.LEFT, 5)
        
        self.titlePanel.SetSizer(hbox)    
    #end def
    
    #--------------------------------------------------------------------------
    def create_control_panel(self):
        
        self.xmin_control = BoundControlBox(self, -1, "t min", 0)
        self.xmax_control = BoundControlBox(self, -1, "t max", 100)
        self.ymin_control = BoundControlBox(self, -1, "V min", -500)
        self.ymax_control = BoundControlBox(self, -1, "V max", 500)
        
        self.hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox1.AddSpacer(10)
        self.hbox1.Add(self.xmin_control, border=5, flag=wx.ALL)
        self.hbox1.Add(self.xmax_control, border=5, flag=wx.ALL)
        self.hbox1.AddSpacer(10)
        self.hbox1.Add(self.ymin_control, border=5, flag=wx.ALL)
        self.hbox1.Add(self.ymax_control, border=5, flag=wx.ALL)     
    #end def
        
    #--------------------------------------------------------------------------
    def OnVoltage(self, msg):
        self.V = float(msg)
        V_list.append(self.V)   
    #end def

    #--------------------------------------------------------------------------
    def OnVTime(self, msg):
        self.tV = float(msg)   
        tV_list.append(self.tV)
    #end def

    #--------------------------------------------------------------------------
    def init_plot(self):
        self.dpi = 100
        self.colorV = 'g'
        
        self.figure = Figure((6,2), dpi=self.dpi)
        self.subplot = self.figure.add_subplot(111)
        self.lineV, = self.subplot.plot(tV_list,V_list, color=self.colorV, linewidth=1)
        self.legend = self.figure.legend( (self.lineV,), (r"$V$",), (0.15,0.75),fontsize=8)
        #self.subplot.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', \
            #verticalalignment='top', transform = self.subplot.transAxes)
    #end def

    #--------------------------------------------------------------------------
    def draw_plot(self,i):
        self.subplot.clear()
        #self.subplot.set_title("voltage vs. time", fontsize=12)
        self.subplot.set_ylabel(r"voltage ($\mu$V)", fontsize = 8)
        self.subplot.set_xlabel("time (s)", fontsize = 8)
        
        # Adjustable scale:
        if self.xmax_control.is_auto():
            xmax = max(tV_list)
        else:
            xmax = float(self.xmax_control.manual_value())    
        if self.xmin_control.is_auto():            
            xmin = 0
        else:
            xmin = float(self.xmin_control.manual_value())
        if self.ymin_control.is_auto():
            minV = min(V_list)
            ymin = minV - abs(minV)*0.3
        else:
            ymin = float(self.ymin_control.manual_value())
        if self.ymax_control.is_auto():
            maxV = max(V_list)
            ymax = maxV + abs(maxV)*0.3
        else:
            ymax = float(self.ymax_control.manual_value())
        
        
        self.subplot.set_xlim([xmin, xmax])
        self.subplot.set_ylim([ymin, ymax])
        
        pylab.setp(self.subplot.get_xticklabels(), fontsize=8)
        pylab.setp(self.subplot.get_yticklabels(), fontsize=8)
        
        self.lineV, = self.subplot.plot(tV_list,V_list, color=self.colorV, linewidth=1)
        
        return (self.lineV)
        #return (self.subplot.plot( thighV_list, highV_list, color=self.colorH, linewidth=1),
            #self.subplot.plot( tlowV_list, lowV_list, color=self.colorL, linewidth=1))
        
    #end def
    
    #--------------------------------------------------------------------------
    def save_plot(self, msg):
        path = filePath + "/Voltage_Plot.png"
        self.canvas.print_figure(path)
        
    #end def
    
    #--------------------------------------------------------------------------
    def create_sizer(self):    
        sizer = wx.GridBagSizer(3,1)
        sizer.Add(self.titlePanel, (0, 0), flag=wx.ALIGN_CENTER_HORIZONTAL)
        sizer.Add(self.canvas, ( 1,0), flag=wx.ALIGN_CENTER_HORIZONTAL)
        sizer.Add(self.hbox1, (2,0), flag=wx.ALIGN_CENTER_HORIZONTAL)
        
        self.SetSizer(sizer)