def heatmap(self):
    [dates,watts] = self.building.data
    clipMax = scipy.stats.scoreatpercentile(watts,per=95)/1000
    clipMin = scipy.stats.scoreatpercentile(watts,per=0)/1000
    #watts[watts > clipMax] = clipMax

    [datesA,wattsA] = self.building.dailyData

    (m,n) = wattsA.shape
    fig = Figure(figsize=(10,6),facecolor='white',edgecolor='none')
    ax = fig.add_subplot(111)
    
    #print 'shapes:',m,n
    #print cm.coolwarm
    p = ax.imshow(wattsA/1000, interpolation='nearest', aspect='auto', cmap=cm.coolwarm, extent=[0,n*20*2,0,m*2])
    p.cmap.set_over('grey')
    cbar = fig.colorbar(p,ax=ax,shrink=0.8)
    cbar.set_label('kW')
    p.set_clim(clipMin, clipMax)
    ax.set_xticks(range(0,n*40+1,n*40/24*2))
    ax.set_xticklabels(['%iam' % x for x in [12]+range(2,12,2)] + ['%ipm' % x for x in [12] + range(2,12,2)] + ['12am'])
    # rotate lables
    for l in ax.xaxis.get_majorticklabels(): l.set_rotation(70)
    ax.set_yticks(range(1,m*2+1,30*2))
    ax.format_ydata = mpld.DateFormatter('%m/%d')
    ax.set_yticklabels([x.strftime('%m/%d/%y') for x in datesA[-1:1:-30,0]])
    #fig.autofmt_ydate()
    ax.tick_params(axis='both', which='major', labelsize=8)
    ax.set_title('Heat map of %s data for %s' % ('electricity','uploaded data'))
    ax.set_xlabel('Hour of day')
    ax.set_ylabel('Date')
    ax.grid(True)
    fig.subplots_adjust(top=1.0, left=0.20)
    return fig
Example #2
0
 def create_input_graph(self, parent, sizer):
     """
     Creates a graph that plots the input
     It returns a timer what starts the plotting
     """
     graph_panel = wx.Panel(parent, size=(320,0))
     self.input_data_generator = DataGen(self)
     self.data_input = []
     dpi = 160
     fig = Figure((2.0, 1.0), dpi=dpi)
     self.axes_input = fig.add_subplot(111)
     fig.add_subplot()
     fig.subplots_adjust(bottom=0.009,left=0.003,right=0.997, top=0.991)
     self.axes_input.set_axis_bgcolor('black')
     pylab.setp(self.axes_input.get_xticklabels(), fontsize=4)
     pylab.setp(self.axes_input.get_yticklabels(), fontsize=4)        
     self.plot_data_input = self.axes_input.plot(self.data_input, 
         linewidth=1,
         color=(1, 0, 0),
         )[0] 
     self.axes_input.grid(True, color='gray')
     self.canvas_input = FigCanvas(graph_panel, -1, fig)        
     vbox = wx.BoxSizer(wx.VERTICAL)
     vbox.Add(self.canvas_input, 0)        
     graph_panel.SetSizer(vbox)
     sizer.Add(graph_panel, 0, wx.TOP | wx.BOTTOM, 5)
     self.axes_input.set_xbound(lower=0, upper=100)
     self.axes_input.set_ybound(lower=-1.0, upper=1.0)
     redraw_timer_input = MyThread(self.graph_refresh_time, self.on_redraw_graph, self) #wx.Timer(self)
     return redraw_timer_input
Example #3
0
 def prepare_configure_subplots(self):
     toolfig = Figure(figsize=(6, 3))
     canvas = FigureCanvasMac(toolfig)
     toolfig.subplots_adjust(top=0.9)
     # Need to keep a reference to the tool.
     _tool = SubplotTool(self.canvas.figure, toolfig)
     return canvas
Example #4
0
def plotgraph(window):
    global df2, indexes, f, a, b

    f = Figure()

    plot_df = df2.ix[indexes]
    plot_df = plot_df.set_index('Particulars')

    if graph == 1:
        a = f.add_subplot(211)
        b = f.add_subplot(212)

        a.clear()
        b.clear()

        plot_df1 = plot_df.T
        plot_df1.plot(ax=a, title='% Change of Particulars in Income Statement as Trends')
        plot_df1.plot(ax=b, kind='barh', title='% Change of Particulars in Income Statement as Bars')
        f.subplots_adjust(left=0.2,bottom=0.2,hspace=0.5)
    elif graph == 2:
        a = f.add_subplot(111)
        a.clear()
        plot_df.plot(ax=a, kind='barh', title='% Change of Particulars in Income Statement as Bars')
        f.subplots_adjust(left=0.2,bottom=0.2,hspace=0.5)
    canvas = FigureCanvasTkAgg(f, window)
    canvas.show()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

    toolbar = NavigationToolbar2TkAgg(canvas, window)
    toolbar.update()
    canvas._tkcanvas.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
Example #5
0
 def create_output_graph(self, parent, sizer):
     """
     Creates a graph that plots the output
     """
     graph_panel = wx.Panel(parent, size=(320,0))
     self.data_output = []
     dpi = 160
     fig = Figure((2.0, 1.0), dpi=dpi)
     self.axes_output = fig.add_subplot(111)
     fig.add_subplot()
     fig.subplots_adjust(bottom=0.009,left=0.003,right=0.997, top=0.991)
     self.axes_output.set_axis_bgcolor('black')
     pylab.setp(self.axes_output.get_xticklabels(), fontsize=4)
     pylab.setp(self.axes_output.get_yticklabels(), fontsize=4)        
     self.plot_data_output = self.axes_output.plot(self.data_output, 
         linewidth=1,
         color=(0, 0, 1),
         )[0] 
     self.axes_output.grid(True, color='gray')
     self.canvas_output = FigCanvas(graph_panel, -1, fig)        
     vbox = wx.BoxSizer(wx.VERTICAL)
     vbox.Add(self.canvas_output, 0)        
     graph_panel.SetSizer(vbox)
     sizer.Add(graph_panel, 0, wx.TOP | wx.BOTTOM, 5)
     self.axes_output.set_xbound(lower=0, upper=100)
     self.axes_output.set_ybound(lower=-1.0, upper=1.0)
Example #6
0
class PlotPanel (wx.PyPanel):
    """The PlotPanel has a Figure and a Canvas. OnSize events simply set a
    flag, and the actual resizing of the figure is triggered by an Idle event."""
    def __init__( self, parent, color=None, dpi=None, **kwargs ):
        from matplotlib.backends.backend_wxagg import (FigureCanvasWxAgg,
                                                       NavigationToolbar2WxAgg)
        from matplotlib.figure import Figure

        # initialize Panel
        if 'id' not in kwargs.keys():
            kwargs['id'] = wx.ID_ANY
        if 'style' not in kwargs.keys():
            kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE
        wx.Panel.__init__( self, parent, **kwargs )
        self.parent = parent

        # initialize matplotlib stuff
        self.figure = Figure( None, dpi )
        self.canvas = FigureCanvasWxAgg( self, -1, self.figure )
        self.ax = self.figure.add_subplot(111)
        self.figure.subplots_adjust(hspace=0.8)
        self.toolbar = NavigationToolbar2WxAgg(self.canvas)

        vSizer = wx.BoxSizer(wx.VERTICAL)
        vSizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        vSizer.Add(self.toolbar, 0, wx.EXPAND)
        self.draw()
        self.SetAutoLayout(True)
        self.SetSizer(vSizer)
        self.Layout()

    def draw(self):
        pass # abstract, to be overridden by child classes
Example #7
0
def template_plotter(x_axis_label, y_axis_label,x_axes=[],x_ticks=[],title, outfile_name):
    fig = Figure(linewidth=0.0)
    fig.set_size_inches(fig_width,fig_length, forward=True)
    Figure.subplots_adjust(fig, left = fig_left, right = fig_right, bottom = fig_bottom, top = fig_top, hspace = fig_hspace)

    _subplot = fig.add_subplot(1,1,1)
    _subplot.boxplot(x_axis,notch=0,sym='+',vert=1, whis=1.5)    
    #_subplot.plot(x,y,color='b', linestyle='--', marker='o' ,label='labels')
    a =[i for i in range(1,len(x_ticks)+1)]
    _subplot.set_xticklabels(x_ticks)
    _subplot.set_xticks(a)
    labels=_subplot.get_xticklabels()
    for label in labels:
        label.set_rotation(30)
    _subplot.set_ylabel(y_axis_label,fontsize=36)
    _subplot.set_xlabel(x_axis_label)
    #_subplot.set_ylim()
    #_subplot.set_xlim()
    
    _subplot.set_title(title)
    _subplot.legend(loc='upper left',prop=LEGEND_PROP ,bbox_to_anchor=(0.5, -0.05))
    canvas = FigureCanvasAgg(fig)
    if '.eps' in outfile_name:
        canvas.print_eps(outfile_name, dpi = 110)
    if '.png' in outfile_name:
        canvas.print_figure(outfile_name, dpi = 110)
    outfile_name='EpsilonvsMTU.pdf'
    if '.pdf' in outfile_name:
        canvas.print_figure(outfile_name, dpi = 110)
Example #8
0
def processOne(fn,done,gpus,telescope,outdir,plotdir,redo=False):
    print fn
    info = decodeFilename(fn)
    print info
    pklname = ('ds_%s_%s_%s_%s.pkl' % (info['source'],info['mjd'],
                                      info['scan'],telescope))
    outfn = os.path.join(outdir,'pkls',pklname)
    if (not redo) and (outfn in done):
        return fn,None,pklname
    try:
    #if True:
        ds = loadDynSpecFromCycSpecScan(int(info['scan']), int(info['mjd']), 
                                        gpus=gpus, telescope=telescope)
        print "loaded dynspec"
        dynspec.pickle(outfn, ds)
        print "pickled",outfn
        fig = Figure(figsize=(10,12))
        fig.subplots_adjust(left=0.09,bottom=0.05,top=0.95,right=0.95)
        ds.plot(fig=fig)
        plotname = os.path.join(plotdir,pklname + '.png')
        esc_fname = outfn.replace('_',r'\_')
        fig.suptitle(('%s @ %s %s' % (info['source'],telescope,esc_fname)),size='medium')
        canvas = FigureCanvasAgg(fig)
        canvas.print_figure(plotname)
    except Exception,e:
        print fn,e,pklname
        return fn,e,pklname
Example #9
0
def _diffHist(pixels, mean, clippedMedian, sigma, upperKey, lowerKey,
              plotPath):
    fig = Figure(figsize=(6, 6))
    canvas = FigureCanvas(fig)
    fig.subplots_adjust(left=0.15, bottom=0.13, wspace=0.25, hspace=0.25,
                        right=0.95)
    ax = fig.add_subplot(111)
    nPixels = len(pixels)
    # Plot histogram
    nCounts, bins, patches = ax.hist(pixels,
                                     bins=int(nPixels / 1000),
                                     histtype='stepfilled', fc='0.5',
                                     log=True, normed=True)
    # Plot estimates of the image difference
    ax.axvline(mean, ls="-", c='k', label="mean")
    ax.axvline(clippedMedian, ls='--', c='k', label="clipped median")
    # ax.axvline(fittedMean, ls='--', c='r', label="fitted mean")
    ax.legend()
    ax.text(0.05, 0.95,
            r"Clipped $\Delta= %.2e \pm %.2e$" % (clippedMedian, sigma),
            ha="left", va="top", transform=ax.transAxes)
    ax.set_xlabel("Image Difference (counts)")
    upperKey = upperKey.replace("_", "\_")
    lowerKey = lowerKey.replace("_", "\_")
    ax.set_title("%s - %s" % (upperKey, lowerKey))
    canvas.print_figure(plotPath)
Example #10
0
def plot_vo(tri, colors=None):
    import matplotlib as mpl
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    fig = Figure(figsize=(4,4))
    canvas = FigureCanvas(fig)
    fig.subplots_adjust(left=0.15, bottom=0.13,wspace=0.25, right=0.95)
    ax = fig.add_subplot(111, aspect='equal')
    
    if colors is None:
        colors = [(0,1,0,0.2)]
    #lc = mpl.collections.LineCollection(numpy.array(
    #    [(tri.circumcenters[i], tri.circumcenters[j])
    #        for i in xrange(len(tri.circumcenters))
    #            for j in tri.triangle_neighbors[i] if j != -1]),
    #    colors=colors)
    lines = [(tri.circumcenters[i], tri.circumcenters[j])
                for i in xrange(len(tri.circumcenters))
                    for j in tri.triangle_neighbors[i] if j != -1]
    lines = numpy.array(lines)
    lc = mpl.collections.LineCollection(lines, colors=colors)
    # ax = pl.gca()
    ax.add_collection(lc)
    # pl.draw()
    # pl.savefig("voronoi")
    ax.plot(tri.x, tri.y, '.k')
    ax.set_xlim(-50,550)
    ax.set_ylim(-50,550)
    canvas.print_figure("voronoi", dpi=300.)
Example #11
0
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        self.axes.hold(False)

        super(GraphWidget, self).__init__(fig)
        self.setParent(parent)
        fig.subplots_adjust(bottom=0.2)

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

        self.below_absolute_value = 0.0
        self.below_absolute_enabled = False
        self.above_absolute_value = 0.0
        self.above_absolute_enabled = False

        self.delayed_plot_timer = QtCore.QTimer()
        self.delayed_plot_timer.setSingleShot(True)
        self.delayed_plot_timer.timeout.connect(self.plot)

        self.readPlotData()
        self.plot()
Example #12
0
def plot_alpha_parameters(pdict, outinfo):
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigCanvas
    pars = []
    parlist, div_idxs = _sort_alpha(pdict)
    # in some fits we don't include systematics, don't draw anything
    if not parlist:
        return
    xlab, xpos, ypos, yerr = _get_lab_x_y_err(parlist)
    fig = Figure(figsize=(8, 4))
    fig.subplots_adjust(bottom=0.2)
    canvas = FigCanvas(fig)
    ax = fig.add_subplot(1,1,1)
    ax.set_xlim(0, len(xlab))
    ax.set_ylim(-2.5, 2.5)
    ax.errorbar(
        xpos, ypos, yerr=yerr, **_eb_style)
    ax.axhline(0, **_hline_style)
    for hline in div_idxs:
        ax.axvline(hline, **_hline_style)
    ax.set_xticks(xpos)
    ax.set_xticklabels(xlab)
    ax.tick_params(labelsize=_txt_size)
    for lab in ax.get_xticklabels():
        lab.set_rotation(60 if len(xlab) < 10 else 90)

    outdir = outinfo['outdir']
    fig.tight_layout(pad=0.3, h_pad=0.3, w_pad=0.3)
    canvas.print_figure(
        join(outdir, 'alpha' + outinfo['ext']), bboxinches='tight')
Example #13
0
def plot_loads_devs(response, start, alldata, allmeans, meandates, maxload, notesets):
    fig = Figure(figsize=(12,8), dpi=72)
    rect = fig.patch
    rect.set_facecolor('white')
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    colorlist = ['b', 'g', 'r', 'y', 'c']
    plts = []
    labels = []
    colorlist_count = 0
    for dev in alldata.keys():
        labels.append(dev)
        plt = ax.plot(alldata[dev]['dates'], alldata[dev]['loads'], colorlist[colorlist_count] + 'x')[0]
        plts.append(plt)
        colorlist_count += 1
    ax.plot(meandates, allmeans, 'ks')
    for i in range(len(meandates)):
        outstr = "%.03f ug/cm^2\n" % (allmeans[i])
        for j in notesets[i]:
            outstr += j + "\n"
        ax.text(meandates[i], allmeans[i], outstr)
    ax.set_ylabel('$ug/cm^2$')
    ax.set_xlabel('Image Record Time (from EXIF)')
    ax.set_title("%s" % (str(start)))
    fig.autofmt_xdate()
    ax.legend(plts, labels, numpoints=1, loc='lower right')
    fig.subplots_adjust(left=0.07, bottom=0.10, right=0.91, \
                        top=0.95, wspace=0.20, hspace=0.00)
    canvas.print_png(response)
    def On_Double(self, event):
        """Finds best fit with selection and returns a pyplot graph."""
        widget = event.widget
        selection = widget.curselection()
        choice = widget.get(selection[0])

        base_data = pd.read_csv(PATH+choice+'.csv', index_col='Year')
        base_index = base_data.columns[0]
        best_fit, r2 = find_best_correlation(data_frame, base_index)

        fig = Figure(figsize=(6, 4), dpi=100)

        #Axis of original data set
        ax1 = fig.add_subplot(111)
        ax1.plot(data_frame.index, data_frame[base_index], color='r')
        ax1.set_ylabel(base_index)
        ax1.annotate(r'$ r ^ 2$ = %s' % r2, xy=(0.05, 0.9),\
            xycoords='axes fraction', size='large')
        #Axis of best fit
        ax2 = ax1.twinx()
        ax2.plot(data_frame.index, data_frame[best_fit], color='k')
        ax2.set_ylabel(best_fit)

        fig.subplots_adjust(left=0.2, top=0.85, right=0.8, bottom=0.15)

        canvas = FigureCanvasTkAgg(fig, self)
        canvas.show()
        canvas.get_tk_widget().grid(row=1, column=2, ipady=10, ipadx=10)
class MplCanvas(FigureCanvas):

    def __init__(self, figsize=(8, 6), dpi=80):
        self.fig = Figure(figsize=figsize, dpi=dpi)
        self.fig.subplots_adjust(wspace=0, hspace=0, left=0, right=1.0, top=1.0, bottom=0)

        self.ax = self.fig.add_subplot(111, frameon=False)
        self.ax.patch.set_visible(False)
        self.ax.set_axis_off()
        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        #self.setAlpha(0.0)

    def saveFig(self, str_io_buf):
        self.setAlpha(0.0)
        self.fig.savefig(str_io_buf, transparent=True, frameon=False, format='png')
        # 140818 Save file to StringIO Buffer not disk file

    def getFig(self):
        return self.fig

    def setAlpha(self, value):
        self.fig.patch.set_alpha(value)
        self.ax.patch.set_alpha(value)
        self.ax.set_axis_off()

    def set_face_color(self, color):
        self.fig.set_facecolor(color)  # "#000000"
Example #16
0
    def init_window(self):
        if self.window:
            return
        self.window = Gtk.Window(title="Subplot Configuration Tool")

        try:
            self.window.window.set_icon_from_file(window_icon)
        except Exception:
            # we presumably already logged a message on the
            # failure of the main plot, don't keep reporting
            pass

        self.vbox = Gtk.Box()
        self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
        self.window.add(self.vbox)
        self.vbox.show()
        self.window.connect('destroy', self.destroy)

        toolfig = Figure(figsize=(6, 3))
        canvas = self.figure.canvas.__class__(toolfig)

        toolfig.subplots_adjust(top=0.9)
        SubplotTool(self.figure, toolfig)

        w = int(toolfig.bbox.width)
        h = int(toolfig.bbox.height)

        self.window.set_default_size(w, h)

        canvas.show()
        self.vbox.pack_start(canvas, True, True, 0)
        self.window.show()
Example #17
0
class MapPlot(QtGui.QWidget):
    """
    """
    def __init__(self, parent, uielement):
        super(MapPlot, self).__init__()
        self.parent = parent
        self.img = None

        #Set dpi via preference
        self.fig = Figure(dpi=72)
        self.ax = self.fig.add_subplot(111)
        self.fig.subplots_adjust(wspace=0.01, hspace=0.01)
        self.ax.grid()
        self.ax.set_xticks([])
        self.ax.set_yticks([])
        self.canvas = FigureCanvas(self.fig)

        combo = QtGui.QComboBox(self)
        [combo.addItem(m) for m in matplotlib.cm.datad]
        combo.activated[str].connect(self.recolor)


        ntb = NavigationToolbar(self.canvas, self)
        ntb.addWidget(combo)
        uielement.addWidget(self.canvas, 1)  # Expanding
        uielement.addWidget(ntb)

    def recolor(self, cbar):
        self.img.set_cmap(cbar)
        self.canvas.draw()
Example #18
0
def bar_plot(d, labels):
    colors = itertools.cycle(['b', 'g', 'r', 'c', 'm', 'y', 'k'])
    fig=Figure(figsize=(8, 6), dpi=200)
    fig.set_facecolor('white')
    fig.subplots_adjust(bottom=0.30)
    ax=fig.add_subplot(111)
    ax.set_title("")
    ax.set_ylabel('Factor values')
    #ax.grid(which='major')
    bottom = None
    for col in d.columns:
	if bottom is None:
	    bottom = 0*d[col]
	ax.bar(range(len(d[col])), d[col], align='center', bottom=bottom,
		label=labels[col], color=colors.next(), alpha=0.6)
	bottom += d[col]
    ax.set_xticks(range(len(d[col])))
    ax.set_xlim([-0.5, len(d[col])])
    ax.set_xticklabels([unicode(el) for el in d[col].index], size='x-small',
	    rotation='vertical')
    leg = ax.legend(loc='best', fancybox=True, prop={'size':9})
    leg.get_frame().set_alpha(0.5)

    canvas=FigureCanvas(fig)
    stream=cStringIO.StringIO()
    canvas.print_png(stream, bbox_inches='tight')
    return stream.getvalue()
class Canvas(FigureCanvas):
  def __init__(self,parent,dpi=100.0):
    size = parent.size()
    self.dpi = dpi
    self.width = size.width() / dpi
    self.height = size.height() / dpi
    self.figure = Figure(figsize=(self.width, self.height), dpi=self.dpi, facecolor='w', edgecolor='k', frameon=False)
    self.figure.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95, wspace=None, hspace=None)
    self.axes = self.figure.add_subplot(111)
    self.axes.axis((-1,1,-1,1))
    FigureCanvas.__init__(self, self.figure)
    self.updateGeometry()
    self.draw()
    self.cc = self.copy_from_bbox(self.axes.bbox)
    self.particle_plot = None
    self.setParent(parent)
    self.blit(self.axes.bbox)

  def on_pre_draw(self):
    self.restore_region(self.cc)

  def on_draw(self):
    raise NotImplementedError

  def on_post_draw(self):
    self.blit(self.axes.bbox)

  def redraw(self):
    self.on_pre_draw()
    self.on_draw()
    self.on_post_draw()
Example #20
0
class DevPlot(Plot):

  def __init__(self,k1={'intel_snb' : ['intel_snb','intel_snb','intel_snb']},k2={'intel_snb':['LOAD_1D_ALL','INSTRUCTIONS_RETIRED','LOAD_OPS_ALL']},processes=1,**kwargs):
    self.k1 = k1
    self.k2 = k2
    super(DevPlot,self).__init__(processes=processes,**kwargs)

  def plot(self,jobid,job_data=None):
    self.setup(jobid,job_data=job_data)
    cpu_name = self.ts.pmc_type
    type_name=self.k1[cpu_name][0]
    events = self.k2[cpu_name]

    ts=self.ts

    n_events = len(events)
    self.fig = Figure(figsize=(8,n_events*2+3),dpi=110)

    do_rate = True
    scale = 1.0
    if type_name == 'mem': 
      do_rate = False
      scale=2.0**10
    if type_name == 'cpu':
      scale=ts.wayness*100.0

    for i in range(n_events):
      self.ax = self.fig.add_subplot(n_events,1,i+1)
      self.plot_lines(self.ax, [i], 3600., yscale=scale, do_rate = do_rate)
      self.ax.set_ylabel(events[i],size='small')
    self.ax.set_xlabel("Time (hr)")
    self.fig.subplots_adjust(hspace=0.5)
    #self.fig.tight_layout()

    self.output('devices')
Example #21
0
    def __init__(self, ticker):
        gtk.VBox.__init__(self)

        startdate = datetime.date(2001, 1, 1)
        today = enddate = datetime.date.today()

        date1 = datetime.date(2011, 1, 1)
        date2 = datetime.date.today()

        mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
        alldays = DayLocator()  # minor ticks on the days
        weekFormatter = DateFormatter("%b %d")  # Eg, Jan 12
        dayFormatter = DateFormatter("%d")  # Eg, 12

        quotes = quotes_historical_yahoo(ticker, date1, date2)
        if len(quotes) == 0:
            raise SystemExit

        fig = Figure(facecolor="white", figsize=(5, 4), dpi=100)
        fig.subplots_adjust(bottom=0.2)
        ax = fig.add_subplot(111)
        ax.xaxis.set_major_locator(mondays)
        ax.xaxis.set_minor_locator(alldays)
        ax.xaxis.set_major_formatter(weekFormatter)
        candlestick(ax, quotes, width=0.6)

        ax.xaxis_date()
        ax.autoscale_view()
        pylab.setp(pylab.gca().get_xticklabels(), rotation=45, horizontalalignment="right")

        canvas = FigureCanvas(fig)  # a gtk.DrawingArea
        self.pack_start(canvas)
        toolbar = NavigationToolbar(canvas, win)
        self.pack_start(toolbar, False, False)
def save_plotSpectrum(y,Fs,image_name):
    """
    Plots a Single-Sided Amplitude Spectrum of y(t)
    """
    fig = Figure(linewidth=0.0)
    fig.set_size_inches(fig_width,fig_length, forward=True)
    Figure.subplots_adjust(fig, left = fig_left, right = fig_right, bottom = fig_bottom, top = fig_top, hspace = fig_hspace)
    n = len(y) # length of the signal

    _subplot = fig.add_subplot(2,1,1)        
    print "Fi"
    _subplot.plot(arange(0,n),y)
    xlabel('Time')
    ylabel('Amplitude')
    _subploti_2=fig.add_subplot(2,1,2)
    k = arange(n)
    T = n/Fs
    frq = k/T # two sides frequency range
    frq = frq[range(n/2)] # one side frequency range

    Y = fft(y)/n # fft computing and normalization
    Y = Y[range(n/2)]

    _subplot_2.plot(frq,abs(Y),'r') # plotting the spectrum
    xlabel('Freq (Hz)')
    ylabel('|Y(freq)|')
    print "here"
    canvas = FigureCanvasAgg(fig)
    if '.eps' in outfile_name:
        canvas.print_eps(outfile_name, dpi = 110)
    if '.png' in outfile_name:
        canvas.print_figure(outfile_name, dpi = 110)
Example #23
0
class VOASSNThumb:

    def __init__(self, data_source):
        years    = mdates.YearLocator(2)   # every year
        months   = mdates.MonthLocator()  # every month
        yearsFmt = mdates.DateFormatter('%y')
        
        dt_list, ssn_list = data_source.get_plotting_data()
        
        self.figure = Figure(figsize=(12,8), dpi=72)   
        self.figure.patch.set_facecolor('white')
        self.figure.subplots_adjust(bottom=0.2)
        self.axis = self.figure.add_subplot(111) 
        self.axis.plot_date(dt_list, ssn_list, '-', lw=2)
        self.axis.axvline(date.today(), color='r')
        
        # format the ticks
        self.axis.xaxis.set_major_locator(years)
        self.axis.xaxis.set_major_formatter(yearsFmt)
        
        self.axis.grid(True)
        
        # rotates and right aligns the x labels, and moves the bottom of the
        # axes up to make room for them
        # The following line currently breaks voacapgui if the thumbnail is 
        # inserted into a panel
        # self.figure.autofmt_xdate(rotation=90)
        
        self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea   

        
    def get_thumb(self):
        return self.canvas
 def run(self, postResults):
     #create tree with relevant datas
     source = sortTree(postResults, ['modules', 'controller', 'type'])
     
     #create plot
     fig = Figure()
     fig.subplots_adjust(wspace=0.5, hspace=0.25)
     
     #plot for L1NormAbs
     axes = fig.add_subplot(111)
                     
     self.plotVariousController(source, axes,\
             xPath=['modules', 'disturbance', 'sigma'],\
             yPath=['metrics', 'L1NormAbs'],\
             typ='line')
     self.plotSettings(axes,\
             titel=r'Fehlerintegral w(t) und y(t) \"uber Sigma',\
             grid=True,\
             xlabel=r'$\sigma \, \lbrack m\rbrack$',\
             ylabel=r'$E \, \lbrack ms \rbrack$',\
             )
     
     #extract controllerNames
     controllerNames = [x[:-len('Controller')] for x in source.keys()]
     
     canvas = FigureCanvas(fig)
     #write output files
     fileName = self.name[len('eval_'):]\
                 + '_Controller_(' + ''.join(controllerNames) + ')'
     self.writeOutputFiles(fileName, fig)
     
     return [{'figure': canvas, 'name': self.name}]
class MplCanvas(FigureCanvas):

    def __init__(self):

        self.fig = Figure(facecolor = '#FFFFFF')
        self.ax = self.fig.add_subplot(111)
        self.fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9)
        self.xtitle="x-Axis"
        self.ytitle="y-Axis"
        self.PlotTitle = "Some Plot"
        self.grid_status = True
        self.xaxis_style = 'linear'
        self.yaxis_style = 'linear'
        self.format_labels()
        self.ax.hold(True)
        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def format_labels(self):
        self.ax.set_title(self.PlotTitle)
        self.ax.title.set_fontsize(10)
        self.ax.set_xlabel(self.xtitle, fontsize = 9)
        self.ax.set_ylabel(self.ytitle, fontsize = 9)
        labels_x = self.ax.get_xticklabels()
        labels_y = self.ax.get_yticklabels()

        for xlabel in labels_x:
            xlabel.set_fontsize(8)
            xlabel.set_color('b')
        for ylabel in labels_y:
            ylabel.set_fontsize(8)
            ylabel.set_color('b')
class MplCanvas(FigureCanvas):
 
    def __init__(self):
        self.fig = Figure()
        self.fig.patch.set_facecolor('white')
        self.ax = self.fig.add_subplot(111)
        #self.ax.set_frame_on(False)
        self.ax.axes.get_yaxis().set_visible(False)
        self.ax.get_xaxis().tick_bottom()
        self.ax.autoscale(enable = True, axis='y', tight= True)
        self.ax.autoscale(enable = False, axis='x', tight= True)
        self.fig.subplots_adjust(0.005,0.2,0.995,1,0,0)
        self.xdata = 0
        
        #self.ax.spines['right'].set_color('none')
        #self.ax.spines['top'].set_color('none')
        #self.ax.spines['left'].set_color('none')
        
        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        
    def mousePressEvent(self, event):
        inv = self.ax.transData.inverted()
        self.xdata = int(inv.transform((event.x(),event.y()))[0])
        self.emit(QtCore.SIGNAL('chartClicked'))
Example #27
0
    def plotConfusionMatrix(self, confmat):

        confmat_norm = confmat.astype(float) / confmat.sum(axis=0)

        fig = Figure(facecolor="white", tight_layout=True)
        ax = fig.add_subplot(111)
        ax.matshow(confmat_norm, cmap=cm.Blues)

        classes = self.parent().model.currentClasses()
        names = [v.name for v in classes.values()]

        ax.xaxis.set_major_locator(FixedLocator(range(len(names))))
        ax.set_xticklabels(names, rotation=45, size=10)

        ax.yaxis.set_major_locator(FixedLocator(range(len(names))))
        ax.set_yticklabels(names, rotation=45, size=10)

        ax.set_xlabel("Predictions", fontsize=14)
        ax.set_ylabel("Annotations", fontsize=14)
        fig.subplots_adjust(top=0.85)

        size = _font_size(confmat.shape[0])
        for i, items in enumerate(confmat):
            for j, item in enumerate(items):
                color = _font_color(confmat_norm[j, i])
                ax.text(i, j, str(item), size=size, color=color, va="center", ha="center")

        self.addFigure("Confusion Matrix", fig)
Example #28
0
def matrix_figure(N1=160, N2=32):
   r=0.4

   fsx=20.
   fsy=fsx*N2/N1

   f=Figure(figsize=(fsx,fsy),frameon=False)
   #f=plt.figure(figsize=(fsx,fsy),frameon=False)
   
   ax=f.add_subplot(111,axisbg='k')
   ax.set_xlim([-2*r,N1-1+2*r])
   ax.set_ylim([-2*r,N2-1+2*r])
   ax.set_axis_bgcolor('k')
   ax.set_yticks([])
   ax.set_xticks([])
   ax.set_frame_on(False) 
   x=np.arange(N1)
   y=np.arange(N2)

   xx,yy=np.meshgrid(x,y)
   cmap = col.ListedColormap([ '#6E6E6E','#FE2E2E', '#64FE2E', '#FF8000'])
   colors=np.random.randint(0,4,(N1,N2))

   patches = []
   for x1,y1 in zip(xx.flatten(), yy.flatten()):
     circle = Circle((x1,y1), r)
     patches.append(circle)

   p = PatchCollection(patches, cmap=cmap)
   p.set_array(colors.flatten())
   ax.add_collection(p)
   f.subplots_adjust(0,0,1,1)
   return ax, colors
Example #29
0
    def configure_subplots(self, button):
        toolfig = Figure(figsize=(6, 3))
        canvas = self._get_canvas(toolfig)
        toolfig.subplots_adjust(top=0.9)
        tool =  SubplotTool(self.canvas.figure, toolfig)

        w = int(toolfig.bbox.width)
        h = int(toolfig.bbox.height)

        window = Gtk.Window()
        try:
            window.set_icon_from_file(window_icon)
        except Exception:
            # we presumably already logged a message on the
            # failure of the main plot, don't keep reporting
            pass
        window.set_title("Subplot Configuration Tool")
        window.set_default_size(w, h)
        vbox = Gtk.Box()
        vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
        window.add(vbox)
        vbox.show()

        canvas.show()
        vbox.pack_start(canvas, True, True, 0)
        window.show()
Example #30
0
    def __init__(self, matrix, matx, maty, dominio, tipodis, X, Y, tiempos, tiemposobs, superficies, ming, maxg, selected = None, parent = None):

        fig = Figure(figsize = (1.8 * 4, 2.4 * 4))

        self.ax = None
        self.axt = None

        fig.subplots_adjust(hspace=.2, wspace=.3, bottom=.07, left=.08, right=.92, top=.94)



        print "tipos q ",tiempos
        print "tiempos obs ", tiemposobs

        self.fig = fig
        self.matrix = matrix
        self.dominio=dominio
        self.tipodis=tipodis
        self.X=X
        self.Y=Y
        self.matx = matx
        self.maty = maty
        self.ming=ming
        self.maxg=maxg
        self.tiempos = tiempos
        self.tiemposobs = tiemposobs
        self.superficies=superficies
Example #31
0
class MatplotlibWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MatplotlibWidget, self).__init__(parent)

        self.figure = Figure(edgecolor='k')
        self.figure.subplots_adjust(left=0.05,
                                    right=0.95,
                                    top=0.85,
                                    bottom=0.15)
        self.figure.set_size_inches(7, 3)
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.axes = self.figure.add_subplot(111)
        self.axes.set_title('Dep/Arr')

        self.scroll = QtWidgets.QScrollArea(self)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.scroll.sizePolicy().hasHeightForWidth())
        self.scroll.setSizePolicy(sizePolicy)
        self.scroll.setWidget(self.canvas)

        self.layoutVertical = QtWidgets.QVBoxLayout(self)
        self.layoutVertical.setSizeConstraint(
            QtWidgets.QLayout.SetDefaultConstraint)
        self.layoutVertical.setContentsMargins(0, 0, 0, 0)
        self.nav = NavigationToolbar(self.canvas, self)

        self.prop = QtWidgets.QLabel(self)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.prop.sizePolicy().hasHeightForWidth())
        self.prop.setSizePolicy(sizePolicy)

        self.layoutVertical.addWidget(self.nav)
        self.layoutVertical.addWidget(self.prop)
        self.layoutVertical.addWidget(self.scroll)

        # self.scroll.resize(self.layoutVertical.geometry().width(), self.layoutVertical.geometry().height())

        self.bins = [1]
        self.binsize = 15 * 60  # min
        self.max_y = 0
        self.plot_off = False
        self.scroll_resize = False
        self.show_labels = False
        self.grid_on = True
        self.reset_fig()
        self.first_timestamp = None

    def reset_fig(self):
        self.axes.clear()
        self.axes.set_title('Dep/Arr', loc='center')
        self.axes.grid(self.grid_on)
        self.axes.set_xticklabels([''])
        self.resize_fig()

    def resize_fig(self):
        if not self.plot_off:
            dpi1 = self.figure.get_dpi()
            if self.scroll_resize and len(self.bins) >= 5 and len(
                    self.bins) * 50 >= self.scroll.width():
                self.figure.set_size_inches(
                    len(self.bins) * 50 / float(dpi1),
                    (self.scroll.height() - 20) / float(dpi1))
                self.canvas.resize(self.figure.get_figwidth() * float(dpi1),
                                   self.figure.get_figheight() * float(dpi1))
            else:
                self.figure.set_size_inches(
                    (self.scroll.width()) / float(dpi1),
                    (self.scroll.height() - 20) / float(dpi1))
                self.canvas.resize(self.figure.get_figwidth() * float(dpi1),
                                   self.figure.get_figheight() * float(dpi1))

    def update_figure(self, op_list, config_list):
        if not self.plot_off and op_list:
            self.reset_fig()
            dep = [0]
            arr = [0]
            labels = []

            if not self.first_timestamp:
                self.first_timestamp = op_list[-1].get_op_timestamp()

            for op in reversed(op_list):
                index = int((op.get_op_timestamp() - self.first_timestamp) /
                            self.binsize)
                # fill in labels and empty values for new bars
                if index >= len(labels):
                    for m in reversed(range(index - len(labels) + 1)):
                        bin_time = op.get_op_timestamp() - m * self.binsize
                        labels.append(
                            time_string(bin_time - (bin_time % self.binsize)))
                    dep.extend([0] * (index - len(dep) + 1))
                    arr.extend([0] * (index - len(arr) + 1))

                if op.LorT == 'T':
                    dep[index] += 1
                elif op.LorT == 'L':
                    arr[index] += 1

            N = len(labels)
            self.bins = np.arange(N)
            width = 0.8
            # plot stacked bars
            p1 = self.axes.bar(self.bins, arr, width, color='#9CB380')
            p2 = self.axes.bar(self.bins,
                               dep,
                               width,
                               bottom=arr,
                               color='#5CC8FF')
            # set legend and labels (not always so they don't overlap)
            self.axes.legend((p2[0], p1[0]), ('Dep', 'Arr'), loc=0)
            self.axes.set_xticks(self.bins - 0.5)
            if len(labels) > 10:
                i = 0
                one_label_per = len(labels) / 15
                for m, label in enumerate(labels):
                    if i > 0:
                        labels[m] = ''
                    i += 1
                    if i > one_label_per: i = 0
            self.axes.set_xticklabels(labels, rotation=-40)
            self.max_y = self.axes.get_ylim()[1]
            self.axes.set_xlim(-1, N)
            x_offset = 0.2
            # set text for count of each bar
            if self.show_labels:
                for m, label in enumerate(labels):
                    if arr[m] != 0:
                        self.axes.text(self.bins[m] - x_offset,
                                       arr[m] + self.max_y * 0.01,
                                       '{:.0f}'.format(arr[m]))
                    if dep[m] != 0:
                        self.axes.text(self.bins[m] + x_offset / 2,
                                       dep[m] + arr[m] + self.max_y * 0.01,
                                       '{:.0f}'.format(dep[m]))
            # config change vertical lines and text
            for m, config in enumerate(config_list):
                x = float(
                    (config.from_epoch - self.first_timestamp) / self.binsize)
                self.axes.plot([x] * 2, [0, 0.9 * self.max_y],
                               'b--',
                               linewidth=1)
                self.axes.text(x + x_offset,
                               self.max_y * 0.9,
                               config.config,
                               fontsize=16)
            # show plot
            self.canvas.draw()
Example #32
0
class DensityPanel(FigureCanvasWxAgg):
    def __init__(self, parent, **kwargs):
        self.figure = Figure()
        FigureCanvasWxAgg.__init__(self, parent, -1, self.figure, **kwargs)
        self.canvas = self.figure.canvas
        self.SetMinSize((100, 100))
        self.figure.set_facecolor((1, 1, 1))
        self.figure.set_edgecolor((1, 1, 1))
        self.canvas.SetBackgroundColour('white')
        self.subplot = self.figure.add_subplot(111)
        self.gate_helper = GatingHelper(self.subplot, self)

        self.navtoolbar = None
        self.point_list = []
        self.gridsize = 50
        self.cb = None
        self.x_scale = LINEAR_SCALE
        self.y_scale = LINEAR_SCALE
        self.color_scale = None
        self.x_label = ''
        self.y_label = ''
        self.cmap = 'jet'

        self.canvas.mpl_connect('button_release_event', self.on_release)

    def setpointslists(self, points):
        self.subplot.clear()
        self.point_list = points
        plot_pts = np.array(points).astype(float)

        if self.x_scale == LOG_SCALE:
            plot_pts = plot_pts[(plot_pts[:, 0] > 0)]
        if self.y_scale == LOG_SCALE:
            plot_pts = plot_pts[(plot_pts[:, 1] > 0)]

        hb = self.subplot.hexbin(plot_pts[:, 0],
                                 plot_pts[:, 1],
                                 gridsize=self.gridsize,
                                 xscale=self.x_scale,
                                 yscale=self.y_scale,
                                 bins=self.color_scale,
                                 cmap=matplotlib.cm.get_cmap(self.cmap))

        if self.cb:
            # Remove the existing colorbar and reclaim the space so when we add
            # a colorbar to the new hexbin subplot, it doesn't get indented.
            #self.figure.delaxes(self.figure.axes[1])
            self.cb.remove()
            self.figure.subplots_adjust(right=0.90)
        self.cb = self.figure.colorbar(hb, fraction=0.046, pad=0.04)
        if self.color_scale == LOG_SCALE:
            self.cb.set_label('log10(N)')

        self.subplot.set_xlabel(self.x_label)
        self.subplot.set_ylabel(self.y_label)

        xmin = np.nanmin(plot_pts[:, 0])
        xmax = np.nanmax(plot_pts[:, 0])
        ymin = np.nanmin(plot_pts[:, 1])
        ymax = np.nanmax(plot_pts[:, 1])

        # Pad all sides
        if self.x_scale == LOG_SCALE:
            xmin = xmin / 1.5
            xmax = xmax * 1.5
        else:
            xmin = xmin - (xmax - xmin) / 20.
            xmax = xmax + (xmax - xmin) / 20.

        if self.y_scale == LOG_SCALE:
            ymin = ymin / 1.5
            ymax = ymax * 1.5
        else:
            ymin = ymin - (ymax - ymin) / 20.
            ymax = ymax + (ymax - ymin) / 20.

        self.subplot.axis([xmin, xmax, ymin, ymax])

        self.reset_toolbar()

    def getpointslists(self):
        return self.point_list

    def setgridsize(self, gridsize):
        self.gridsize = gridsize

    def set_x_scale(self, scale):
        self.x_scale = scale

    def set_y_scale(self, scale):
        self.y_scale = scale

    def set_color_scale(self, scale):
        if scale == LINEAR_SCALE:
            scale = None
        self.color_scale = scale

    def set_x_label(self, label):
        self.x_label = label

    def set_y_label(self, label):
        self.y_label = label

    def set_colormap(self, cmap):
        self.cmap = cmap
        self.draw()

    def get_toolbar(self):
        if not self.navtoolbar:
            self.navtoolbar = NavigationToolbar(self.canvas)
        return self.navtoolbar

    def reset_toolbar(self):
        # Cheat since there is no way reset
        if self.navtoolbar:
            self.navtoolbar._views.clear()
            self.navtoolbar._positions.clear()
            self.navtoolbar.push_current()

    def set_configpanel(self, configpanel):
        '''Allow access of the control panel from the plotting panel'''
        self.configpanel = configpanel

    def on_release(self, evt):
        if evt.button == 3:  # right click
            self.show_popup_menu((evt.x, self.canvas.GetSize()[1] - evt.y),
                                 None)

    def show_popup_menu(self, (x, y), data):
        self.popup_menu_filters = {}
        popup = wx.Menu()
        loadimages_table_item = popup.Append(
            -1, 'Create gated table for CellProfiler LoadImages')
        selected_gate = self.configpanel.gate_choice.get_gatename_or_none()
        selected_gates = []
        if selected_gate:
            selected_gates = [selected_gate]
        self.Bind(
            wx.EVT_MENU, lambda (e): ui.prompt_user_to_create_loadimages_table(
                self, selected_gates), loadimages_table_item)

        show_images_in_gate_item = popup.Append(-1, 'Show images in gate')
        show_images_in_gate_item.Enable(selected_gate is not None)
        self.Bind(wx.EVT_MENU, self.show_images_from_gate,
                  show_images_in_gate_item)
        if p.object_table:
            show_objects_in_gate_item = popup.Append(
                -1, 'Show %s in gate (montage)' % (p.object_name[1]))
            show_objects_in_gate_item.Enable(selected_gate is not None)
            self.Bind(wx.EVT_MENU, self.show_objects_from_gate,
                      show_objects_in_gate_item)

        self.PopupMenu(popup, (x, y))
Example #33
0
class PCAWindow(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          parent,
                          id=wx.ID_ANY,
                          title=u"振動モード分析",
                          pos=wx.DefaultPosition,
                          size=wx.Size(1280, 980),
                          style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)
        self.SetForegroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
        self.SetBackgroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))

        self.contribution_figure = Figure(figsize=(8, 4.3), dpi=100)
        self.contribution_canvas = FigureCanvasWxAgg(self, -1,
                                                     self.contribution_figure)
        self.contribution_navigationToolbar = NavigationToolbar2Wx(
            self.contribution_canvas)
        self.contribution_navigationToolbar.Realize()
        self.contribution_navigationToolbar.update()

        self.dammy1_figure = Figure(figsize=(8, 4.3), dpi=100)
        self.dammy1_canvas = FigureCanvasWxAgg(self, -1, self.dammy1_figure)
        self.dammy1_navigationToolbar = NavigationToolbar2Wx(
            self.dammy1_canvas)
        self.dammy1_navigationToolbar.Realize()
        self.dammy1_navigationToolbar.update()

        import configdata
        self.n_comp = 5  #仮設定(固有値の計算範囲)
        self.p_comp = 1  #仮設定(表示する固有値モード)
        self.scale = 1  #仮設定(表示倍率)
        self.data = configdata.dis.sel(layer=0,
                                       features=["dis_x", "dis_y"],
                                       stats="mu").values
        self.pxpy = configdata.pxpys.sel(layer=0, features=["x", "y"]).values
        self.x = range(1, self.n_comp + 1)
        from eof_analysis import eof
        self.d, self.v = eof(self.data, self.n_comp)
        point = int(self.v.shape[0] / 2)
        datavx = self.v[:point, self.p_comp - 1]
        datavy = self.v[point:, self.p_comp - 1]

        self.contribution_figure.subplots_adjust(left=0.3,
                                                 right=0.7,
                                                 bottom=0.1,
                                                 top=0.8)
        #self.contribution_axes = self.contribution_figure.add_subplot(111, facecolor='black')
        self.contribution_axes = self.contribution_figure.add_subplot(
            111, facecolor='white')
        self.contribution_axes.minorticks_on()
        self.contribution_axes.tick_params(axis='both',
                                           which='major',
                                           direction='inout',
                                           colors="black",
                                           labelsize=8,
                                           bottom='on',
                                           left='on')
        self.contribution_axes.grid(True)
        self.contribution_axes.tick_params(axis='both',
                                           which='minor',
                                           direction='inout',
                                           length=5,
                                           colors="black")
        self.contribution_axes.set_title('contribution ratio')
        #self.colorlist = ["r", "g", "b", "c", "m", "y", "k", "w"]
        self.colorlist = ["r", "g", "b", "c", "m", "y", "k"]
        self.contribution_axes.bar(self.x, self.d, color=self.colorlist)

        frame = 0
        cv2img = cv2.imread(configdata.image_filelist[frame])
        self.im = cv2.cvtColor(cv2img, cv2.COLOR_BGR2RGB)
        self.dammy1_figure.subplots_adjust(left=0.1,
                                           right=0.995,
                                           bottom=0.1,
                                           top=0.9)
        #self.dammy1_axes = self.dammy1_figure.add_subplot(111, facecolor='black')
        self.dammy1_axes = self.dammy1_figure.add_subplot(111,
                                                          facecolor='white')
        self.dammy1_axes.minorticks_on()
        self.dammy1_axes.tick_params(axis='both',
                                     which='major',
                                     direction='inout',
                                     colors="black",
                                     labelsize=8,
                                     bottom='on',
                                     left='on')
        self.dammy1_axes.grid(True)
        self.dammy1_axes.tick_params(axis='both',
                                     which='minor',
                                     direction='inout',
                                     length=5,
                                     colors="black")
        self.dammy1_axes.set_title('dammy1')
        m = mainWindow.setSt_Dialog2(self)
        param = int(m.getParam2())
        xl = []
        st = int(param / 10)
        for i in range(0, param, st):
            xl.append(i)

        self.dammy1_axes.set_xticklabels(xl)
        self.dammy1_axes.imshow(self.im)
        self.dammy1_axes.quiver(self.pxpy[:, 0],
                                self.pxpy[:, 1],
                                datavx,
                                datavy,
                                angles='xy',
                                width=0.005,
                                color='red',
                                scale=self.scale)

        gSizer1 = wx.BoxSizer(wx.VERTICAL)

        bSizer32 = wx.BoxSizer(wx.VERTICAL)  # 左上
        bSizer32.Add(self.contribution_canvas, 0, wx.EXPAND)
        bSizer32.Add(self.contribution_navigationToolbar, 0, wx.EXPAND)
        gSizer1.Add(bSizer32, 0, wx.EXPAND)

        bSizer35 = wx.BoxSizer(wx.HORIZONTAL)
        bSizer34 = wx.BoxSizer(wx.VERTICAL)  # 下
        bSizer35.Add(bSizer34, 0, wx.EXPAND)
        bSizer34.Add(self.dammy1_canvas, 0, wx.EXPAND)
        bSizer34.Add(self.dammy1_navigationToolbar, 0, wx.EXPAND)
        bSizer36 = wx.BoxSizer(wx.VERTICAL)
        bSizer35.Add(bSizer36, 0, wx.EXPAND)
        staticText0 = wx.StaticText(self, wx.ID_ANY,
                                    u"  \n  \n  \n   \n    \n",
                                    wx.DefaultPosition, wx.DefaultSize,
                                    wx.TE_CENTRE)
        bSizer36.Add(staticText0, 0, wx.ALIGN_LEFT)
        array = []
        for i in range(self.n_comp):
            array.append(str(i + 1))
        self.combo = wx.ComboBox(self, -1, u'  ', choices=array)
        self.combo.SetSelection(0)
        self.combo.Bind(wx.EVT_COMBOBOX, self.event_combo)
        self.textCtrl1 = wx.TextCtrl(self, wx.ID_ANY, u"1", wx.DefaultPosition,
                                     wx.DefaultSize, 0)
        bSizer37 = wx.BoxSizer(wx.HORIZONTAL)
        bSizer36.Add(bSizer37, 0, wx.ALIGN_LEFT)
        staticText1 = wx.StaticText(self, wx.ID_ANY, u"次数:",
                                    wx.DefaultPosition, wx.DefaultSize,
                                    wx.TE_CENTRE)
        staticText1.SetForegroundColour('#000000')
        bSizer37.Add(staticText1, 0, wx.ALIGN_CENTER)
        bSizer37.Add(self.combo, 0, wx.ALIGN_CENTER)
        bSizer38 = wx.BoxSizer(wx.HORIZONTAL)
        bSizer36.Add(bSizer38, 0, wx.ALIGN_LEFT)
        staticText2 = wx.StaticText(self, wx.ID_ANY, u"スケール:",
                                    wx.DefaultPosition, wx.DefaultSize,
                                    wx.TE_CENTRE)
        staticText2.SetForegroundColour('#000000')
        self.button1 = wx.Button(self, wx.ID_ANY, u"更新", wx.DefaultPosition,
                                 wx.DefaultSize, 0)
        self.button1.Bind(wx.EVT_BUTTON, self.event_scale)
        bSizer38.Add(staticText2, 0, wx.ALIGN_CENTER)
        bSizer38.Add(self.textCtrl1, 0, wx.ALIGN_CENTER)
        bSizer38.Add(self.button1, 0, wx.ALIGN_CENTER)
        gSizer1.Add(bSizer35, 0, wx.EXPAND)
        self.SetSizer(gSizer1)
        self.Layout()
        self.Centre(wx.BOTH)

    def updateGraph(self):
        point = int(self.v.shape[0] / 2)
        datavx = self.v[:point, self.p_comp]
        datavy = self.v[point:, self.p_comp]
        self.dammy1_axes.cla()
        #self.dammy1_axes = self.dammy1_figure.add_subplot(111, facecolor='black')
        self.dammy1_axes = self.dammy1_figure.add_subplot(111,
                                                          facecolor='white')
        self.dammy1_axes.minorticks_on()
        self.dammy1_axes.tick_params(axis='both',
                                     which='major',
                                     direction='inout',
                                     colors="black",
                                     labelsize=8,
                                     bottom='on',
                                     left='on')
        self.dammy1_axes.grid(True)
        self.dammy1_axes.tick_params(axis='both',
                                     which='minor',
                                     direction='inout',
                                     length=5,
                                     colors="black")
        self.dammy1_axes.set_title('dammy1')
        m = mainWindow.setSt_Dialog2(self)
        param = int(m.getParam2())
        xl = []
        st = int(param / 10)
        for i in range(0, param, st):
            xl.append(i)

        self.dammy1_axes.set_xticklabels(xl)
        self.dammy1_axes.imshow(self.im)
        self.dammy1_axes.quiver(self.pxpy[:, 0],
                                self.pxpy[:, 1],
                                datavx,
                                datavy,
                                angles='xy',
                                width=0.005,
                                color=self.colorlist[self.p_comp],
                                scale=self.scale)
        self.dammy1_canvas.draw()

    def event_combo(self, event):
        self.p_comp = int(self.combo.GetSelection())
        self.updateGraph()

    def event_scale(self, event):
        self.scale = float(self.textCtrl1.GetValue())
        self.updateGraph()

    def __del__(self):
        pass
Example #34
0
class WidgetPrimaryNuclides(QWidget, Ui_WidgetPrimaryNuclides):
    cooling_times = ['1', '1.0e5', '1.0e6', '1.0e7', '1.0e8', '1.0e9', '1.5e9']
    param_names = [
        'activity(Bq/kg)', 'total_heat(kW/kg)', 'dose_rate(Sv/h)',
        'ingestion_dose(Sv/kg)'
    ]
    show_names = [
        'Specific activity(Bq/kg)', 'Heat(kW/kg)', 'Dose rate(Sv/h)',
        'Ingestion dose(Sv/kg)'
    ]
    colors = [
        '#FA8072', '#7FFF00', '#87CEFA', '#8A2BE2', '#A9A9A9', '#E9967A',
        '#FF1493', '#9932CC', '#CD853F', '#FF7F50', '#2E8B57'
    ]

    def __init__(self, parent=None):
        super(WidgetPrimaryNuclides, self).__init__(parent)
        self.figure = None
        self.setupUi(self)
        self.axes = [None, None, None, None]
        self.checkButtons = [
            self.checkBoxAct, self.checkBoxHeat, self.checkBoxDose,
            self.checkBoxIng
        ]
        for checkButton in self.checkButtons:
            checkButton.clicked.connect(self.on_click)
        for time in WidgetPrimaryNuclides.cooling_times:
            self.comboBoxCoolingTime.addItem(time)
        self.comboBoxCoolingTime.setCurrentIndex(2)
        self.initialize_canvas()

    def initialize_canvas(self):
        self.figure = Figure(figsize=(8, 6), dpi=100, tight_layout=True)
        self.figure.set_facecolor('#F5F5F5')
        self.figure.subplots_adjust(left=0.08, top=0.92, bottom=0.1)
        self.canvas = FigureCanvas(self.figure)
        self.verticalLayoutPlot.addWidget(self.canvas)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.verticalLayoutToolbarAndOtherWidgets.addWidget(self.toolbar)

    def data_to_ui(self, act_data: OneSpectrumActivationData):
        self.act_data = act_data
        self.update()
        self.initialize_figs()

    def initialize_figs(self):
        self.update()
        self.canvas.figure.clf()
        checked_button_num = 0
        for i in range(0, 4):
            if self.checkButtons[i].isChecked():
                checked_button_num += 1
        if checked_button_num is 0:
            return
        idx = 1
        if checked_button_num % 2 is 0:
            totalnum = checked_button_num * 50 + 20
        elif checked_button_num == 3:
            totalnum = 220
        else:
            totalnum = checked_button_num * 100 + 10
        for i in range(0, 4):
            if self.checkButtons[i].isChecked():
                self.axes[i] = self.figure.add_subplot(totalnum + idx)
                self.draw_axe(i)
                idx += 1
        self.canvas.draw()

    def draw_axe(self, idx):
        assert (self.act_data is not None)
        cooling_time_idx = self.comboBoxCoolingTime.currentIndex()
        assert (cooling_time_idx < len(
            self.act_data.all_steps_activation_data))
        one_step_data = self.act_data.all_steps_activation_data[
            cooling_time_idx]
        # get primary nuclides for xxx
        parameter_name = WidgetPrimaryNuclides.param_names[idx]
        # total_val = 0.0 # one_step_data.parameters[parameter_name]
        total_val = one_step_data.parameters[parameter_name]
        if total_val <= 0.0:
            self.axes[idx].set_title(
                "Primary nuclides for: " + parameter_name +
                " is not valid.\nBecause the total value is 0.")
            self.axes[idx].pie([], labels=[])
            return
        nuclides = []
        nuclide_props = []
        accumulate_amount = 0.0
        primary_limit = self.horizontalSliderPrimaryAmount.value() * 1.0 / 100
        # for nuclide in one_step_data.nuclides.keys():
        #     total_val += one_step_data.nuclides[nuclide].params[parameter_name]
        for nuclide in sorted(one_step_data.nuclides.keys(),
                              key=lambda a: -one_step_data.nuclides[a].params[
                                  parameter_name]):
            nuclides.append(nuclide)
            act_value = one_step_data.nuclides[nuclide].params[parameter_name]
            prop = act_value / total_val
            accumulate_amount += prop
            nuclide_props.append(prop)
            if accumulate_amount >= primary_limit:
                break
        if accumulate_amount > 0.999999:
            accumulate_amount = 1.0
        leftprop = 1 - accumulate_amount
        if leftprop > 0.0001:
            nuclide_props.append(leftprop)
            nuclides.append('Other')
        self.axes[idx].pie(nuclide_props,
                           labels=nuclides,
                           colors=WidgetPrimaryNuclides.colors,
                           autopct='%1.2f%%',
                           shadow=True,
                           startangle=90)
        show_name = WidgetPrimaryNuclides.show_names[idx]
        self.axes[idx].set_title("Primary nuclides for: " + show_name)
        self.axes[idx].axis('equal')
        return

    def on_click(self):
        self.update()
        self.initialize_figs()

    @pyqtSlot(int)
    def on_comboBoxCoolingTime_currentIndexChanged(self, idx):
        if self.figure is not None:
            self.initialize_figs()

    @pyqtSlot(int)
    def on_horizontalSliderPrimaryAmount_valueChanged(self, amount):
        self.labelPrimaryAmount.setText("{0}".format(amount))
        if self.figure is not None:
            self.initialize_figs()
Example #35
0
def get_fit_loop_plot():
    Ia_model_count = len(info.options_dict["Ia_table"])
    cc_model_count = len(info.options_dict["cc_table"])

    total_models = Ia_model_count * cc_model_count
    print("total_models", total_models)

    new_chi_list = Stats.fit_loop_results["chi_list"].reshape(
        Ia_model_count, cc_model_count)
    new_ratio_list = Stats.fit_loop_results["ratio_percent_list"].reshape(
        Ia_model_count, cc_model_count)
    new_ratio_error_n_list = Stats.fit_loop_results[
        "ratio_percent_error_n_list"].reshape(Ia_model_count, cc_model_count)
    new_ratio_error_p_list = Stats.fit_loop_results[
        "ratio_percent_error_p_list"].reshape(Ia_model_count, cc_model_count)

    fig = Figure(dpi=200,
                 figsize=(10, 10),
                 facecolor=(1, 1, 1),
                 edgecolor=(0, 0, 0))
    ax = [
        fig.add_subplot(141),
        fig.add_subplot(142),
        fig.add_subplot(143),
        fig.add_subplot(144)
    ]

    fig.subplots_adjust(left=0.15,
                        bottom=0.175,
                        right=0.95,
                        top=0.95,
                        wspace=0.0,
                        hspace=0.0)

    xlabel = [t.rsplit(".", 1)[0] for t in info.options_dict["cc_table"]]
    ax[0].set_xticks(range(cc_model_count))
    ax[0].set_xticklabels(xlabel, rotation=80, size=5)

    ylabel = [t.rsplit(".", 1)[0] for t in info.options_dict["Ia_table"]]
    ax[0].set_yticks(range(Ia_model_count))
    ax[0].set_yticklabels(ylabel, size=5)

    ax[0].imshow(new_chi_list, cmap=matplotlib.cm.get_cmap('winter_r'))

    for i in range(len(xlabel)):
        for j in range(len(ylabel)):
            text = ax[0].text(i,
                              j,
                              "{:.2f}".format(new_chi_list[j, i]),
                              ha="center",
                              va="center",
                              color="black",
                              fontsize=5)

    ax[0].set_title("Chi")

    xlabel = [t.rsplit(".", 1)[0] for t in info.options_dict["cc_table"]]
    ax[1].set_xticks(range(cc_model_count))
    ax[1].set_xticklabels(xlabel, rotation=80, size=5)

    ylabel = ["" for _ in info.options_dict["Ia_table"]]
    ax[1].set_yticks(range(Ia_model_count))
    ax[1].set_yticklabels(ylabel, size=5)

    ax[1].imshow(new_ratio_list,
                 vmin=0,
                 vmax=1,
                 cmap=matplotlib.cm.get_cmap('autumn_r'))

    for i in range(len(xlabel)):
        for j in range(len(ylabel)):
            text = ax[1].text(i,
                              j,
                              "{:.2f}".format(new_ratio_list[j, i]),
                              ha="center",
                              va="center",
                              color="black",
                              fontsize=5)

    ax[1].set_title("Ratio")

    xlabel = [t.rsplit(".", 1)[0] for t in info.options_dict["cc_table"]]
    ax[2].set_xticks(range(cc_model_count))
    ax[2].set_xticklabels(xlabel, rotation=80, size=5)

    ylabel = ["" for _ in info.options_dict["Ia_table"]]
    ax[2].set_yticks(range(Ia_model_count))
    ax[2].set_yticklabels(ylabel, size=5)

    ax[2].imshow(new_ratio_list, cmap=matplotlib.cm.get_cmap('summer_r'))

    for i in range(len(xlabel)):
        for j in range(len(ylabel)):
            text = ax[2].text(i,
                              j,
                              "{:.2f}".format(new_ratio_error_n_list[j, i]),
                              ha="center",
                              va="center",
                              color="black",
                              fontsize=5)

    ax[2].set_title("(-)")

    xlabel = [t.rsplit(".", 1)[0] for t in info.options_dict["cc_table"]]
    ax[3].set_xticks(range(cc_model_count))
    ax[3].set_xticklabels(xlabel, rotation=80, size=5)

    ylabel = ["" for _ in info.options_dict["Ia_table"]]
    ax[3].set_yticks(range(Ia_model_count))
    ax[3].set_yticklabels(ylabel, size=5)

    ax[3].imshow(new_ratio_list, cmap=matplotlib.cm.get_cmap('summer_r'))

    for i in range(len(xlabel)):
        for j in range(len(ylabel)):
            text = ax[3].text(i,
                              j,
                              "{:.2f}".format(new_ratio_error_p_list[j, i]),
                              ha="center",
                              va="center",
                              color="black",
                              fontsize=5)

    ax[3].set_title("(+)")

    return fig
Example #36
0
class VNA(QMainWindow, Ui_VNA):

    max_size = 32768

    def __init__(self):
        super(VNA, self).__init__()
        self.setupUi(self)
        # IP address validator
        rx = QRegExp(
            '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'
        )
        self.addrValue.setValidator(QRegExpValidator(rx, self.addrValue))
        # state variables
        self.idle = True
        self.reading = False
        # sweep parameters
        self.sweep_start = 10
        self.sweep_stop = 60000
        self.sweep_size = 6000
        # buffer and offset for the incoming samples
        self.buffer = bytearray(16 * VNA.max_size)
        self.offset = 0
        self.data = np.frombuffer(self.buffer, np.complex64)
        self.open = Measurement(self.sweep_start, self.sweep_stop,
                                self.sweep_size)
        self.short = Measurement(self.sweep_start, self.sweep_stop,
                                 self.sweep_size)
        self.load = Measurement(self.sweep_start, self.sweep_stop,
                                self.sweep_size)
        self.dut = Measurement(self.sweep_start, self.sweep_stop,
                               self.sweep_size)
        self.mode = 'dut'
        # create figure
        self.figure = Figure()
        self.figure.set_facecolor('none')
        self.canvas = FigureCanvas(self.figure)
        self.plotLayout.addWidget(self.canvas)
        # create navigation toolbar
        self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False)
        # initialize cursor
        self.cursor = None
        # remove subplots action
        actions = self.toolbar.actions()
        if int(matplotlib.__version__[0]) < 2:
            self.toolbar.removeAction(actions[7])
        else:
            self.toolbar.removeAction(actions[6])
        self.plotLayout.addWidget(self.toolbar)
        # create TCP socket
        self.socket = QTcpSocket(self)
        self.socket.connected.connect(self.connected)
        self.socket.readyRead.connect(self.read_data)
        self.socket.error.connect(self.display_error)
        # connect signals from buttons and boxes
        self.sweepFrame.setEnabled(False)
        self.dutSweep.setEnabled(False)
        self.connectButton.clicked.connect(self.start)
        self.writeButton.clicked.connect(self.write_cfg)
        self.readButton.clicked.connect(self.read_cfg)
        self.openSweep.clicked.connect(self.sweep_open)
        self.shortSweep.clicked.connect(self.sweep_short)
        self.loadSweep.clicked.connect(self.sweep_load)
        self.dutSweep.clicked.connect(self.sweep_dut)
        self.csvButton.clicked.connect(self.write_csv)
        self.s1pButton.clicked.connect(self.write_s1p)
        self.s2pButton.clicked.connect(self.write_s2p)
        self.startValue.valueChanged.connect(self.set_start)
        self.stopValue.valueChanged.connect(self.set_stop)
        self.sizeValue.valueChanged.connect(self.set_size)
        self.rateValue.addItems([
            '50000', '10000', '5000', '1000', '500', '100', '50', '10', '5',
            '1'
        ])
        self.rateValue.lineEdit().setReadOnly(True)
        self.rateValue.lineEdit().setAlignment(Qt.AlignRight)
        for i in range(0, self.rateValue.count()):
            self.rateValue.setItemData(i, Qt.AlignRight, Qt.TextAlignmentRole)
        self.rateValue.currentIndexChanged.connect(self.set_rate)
        self.corrValue.valueChanged.connect(self.set_corr)
        self.levelValue.valueChanged.connect(self.set_level)
        self.openPlot.clicked.connect(self.plot_open)
        self.shortPlot.clicked.connect(self.plot_short)
        self.loadPlot.clicked.connect(self.plot_load)
        self.dutPlot.clicked.connect(self.plot_dut)
        self.smithPlot.clicked.connect(self.plot_smith)
        self.impPlot.clicked.connect(self.plot_imp)
        self.rcPlot.clicked.connect(self.plot_rc)
        self.swrPlot.clicked.connect(self.plot_swr)
        self.rlPlot.clicked.connect(self.plot_rl)
        self.gainPlot.clicked.connect(self.plot_gain)
        # create timer
        self.startTimer = QTimer(self)
        self.startTimer.timeout.connect(self.timeout)

    def start(self):
        if self.idle:
            self.connectButton.setEnabled(False)
            self.socket.connectToHost(self.addrValue.text(), 1001)
            self.startTimer.start(5000)
        else:
            self.stop()

    def stop(self):
        self.idle = True
        self.socket.abort()
        self.connectButton.setText('Connect')
        self.connectButton.setEnabled(True)
        self.sweepFrame.setEnabled(False)
        self.selectFrame.setEnabled(True)
        self.dutSweep.setEnabled(False)

    def timeout(self):
        self.display_error('timeout')

    def connected(self):
        self.startTimer.stop()
        self.idle = False
        self.set_start(self.startValue.value())
        self.set_stop(self.stopValue.value())
        self.set_size(self.sizeValue.value())
        self.set_rate(self.rateValue.currentIndex())
        self.set_corr(self.corrValue.value())
        self.set_level(self.levelValue.value())
        self.connectButton.setText('Disconnect')
        self.connectButton.setEnabled(True)
        self.sweepFrame.setEnabled(True)
        self.dutSweep.setEnabled(True)

    def read_data(self):
        while (self.socket.bytesAvailable() > 0):
            if not self.reading:
                self.socket.readAll()
                return
            size = self.socket.bytesAvailable()
            self.progress.setValue((self.offset + size) / 16)
            limit = 16 * self.sweep_size
            if self.offset + size < limit:
                self.buffer[self.offset:self.offset +
                            size] = self.socket.read(size)
                self.offset += size
            else:
                self.buffer[self.offset:limit] = self.socket.read(limit -
                                                                  self.offset)
                adc1 = self.data[0::2]
                adc2 = self.data[1::2]
                attr = getattr(self, self.mode)
                size = attr.freq.size
                attr.data = adc1[0:size].copy()
                getattr(self, 'plot_%s' % self.mode)()
                self.reading = False
                self.sweepFrame.setEnabled(True)
                self.selectFrame.setEnabled(True)

    def display_error(self, socketError):
        self.startTimer.stop()
        if socketError == 'timeout':
            QMessageBox.information(self, 'VNA', 'Error: connection timeout.')
        else:
            QMessageBox.information(self, 'VNA',
                                    'Error: %s.' % self.socket.errorString())
        self.stop()

    def set_start(self, value):
        self.sweep_start = value

    def set_stop(self, value):
        self.sweep_stop = value

    def set_size(self, value):
        self.sweep_size = value

    def set_rate(self, value):
        if self.idle: return
        rate = [1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000][value]
        self.socket.write(struct.pack('<I', 3 << 28 | int(rate)))

    def set_corr(self, value):
        if self.idle: return
        self.socket.write(struct.pack('<I', 4 << 28 | int(value)))

    def set_level(self, value):
        if self.idle: return
        self.socket.write(
            struct.pack('<I',
                        5 << 28 | int(32766 * np.power(10.0, value / 20.0))))
        self.socket.write(struct.pack('<I', 6 << 28 | int(0)))

    def sweep(self, mode):
        if self.idle: return
        self.sweepFrame.setEnabled(False)
        self.selectFrame.setEnabled(False)
        self.mode = mode
        attr = getattr(self, mode)
        attr.freq = np.linspace(self.sweep_start, self.sweep_stop,
                                self.sweep_size) * 1000
        self.offset = 0
        self.reading = True
        self.socket.write(
            struct.pack('<I', 0 << 28 | int(self.sweep_start * 1000)))
        self.socket.write(
            struct.pack('<I', 1 << 28 | int(self.sweep_stop * 1000)))
        self.socket.write(struct.pack('<I', 2 << 28 | int(self.sweep_size)))
        self.socket.write(struct.pack('<I', 7 << 28))
        self.progress = QProgressDialog('Sweep status', 'Cancel', 0,
                                        self.sweep_size)
        self.progress.setModal(True)
        self.progress.setMinimumDuration(1000)
        self.progress.canceled.connect(self.cancel)

    def cancel(self):
        self.offset = 0
        self.reading = False
        self.socket.write(struct.pack('<I', 8 << 28))
        self.sweepFrame.setEnabled(True)
        self.selectFrame.setEnabled(True)

    def sweep_open(self):
        self.sweep('open')

    def sweep_short(self):
        self.sweep('short')

    def sweep_load(self):
        self.sweep('load')

    def sweep_dut(self):
        self.sweep('dut')

    def interp(self, freq, data):
        real = np.interp(self.dut.freq, freq, data.real)
        imag = np.interp(self.dut.freq, freq, data.imag)
        return real + 1j * imag

    def gain(self):
        return self.dut.data / self.interp(self.short.freq, self.short.data)

    def impedance(self):
        open = self.interp(self.open.freq, self.open.data)
        short = self.interp(self.short.freq, self.short.data)
        load = self.interp(self.load.freq, self.load.data)
        dut = self.dut.data
        return 50.0 * (open - load) * (dut - short) / ((load - short) *
                                                       (open - dut))

    def gamma(self):
        z = self.impedance()
        return (z - 50.0) / (z + 50.0)

    def plot_gain(self):
        if self.cursor is not None: self.cursor.hide().disable()
        matplotlib.rcdefaults()
        self.figure.clf()
        self.figure.subplots_adjust(left=0.12,
                                    bottom=0.12,
                                    right=0.88,
                                    top=0.98)
        axes1 = self.figure.add_subplot(111)
        axes1.cla()
        axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
        axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix))
        axes1.tick_params('y', color='blue', labelcolor='blue')
        axes1.yaxis.label.set_color('blue')
        gain = self.gain()
        axes1.plot(self.dut.freq,
                   20.0 * np.log10(np.absolute(gain)),
                   color='blue',
                   label='Gain')
        axes2 = axes1.twinx()
        axes2.spines['left'].set_color('blue')
        axes2.spines['right'].set_color('red')
        axes1.set_xlabel('Hz')
        axes1.set_ylabel('Gain, dB')
        axes2.set_ylabel('Phase angle')
        axes2.tick_params('y', color='red', labelcolor='red')
        axes2.yaxis.label.set_color('red')
        axes2.plot(self.dut.freq,
                   np.angle(gain, deg=True),
                   color='red',
                   label='Phase angle')
        self.cursor = datacursor(axes=self.figure.get_axes(),
                                 formatter=LabelFormatter(),
                                 display='multiple')
        self.canvas.draw()

    def plot_magphase(self, freq, data):
        if self.cursor is not None: self.cursor.hide().disable()
        matplotlib.rcdefaults()
        self.figure.clf()
        self.figure.subplots_adjust(left=0.12,
                                    bottom=0.12,
                                    right=0.88,
                                    top=0.98)
        axes1 = self.figure.add_subplot(111)
        axes1.cla()
        axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
        axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix))
        axes1.tick_params('y', color='blue', labelcolor='blue')
        axes1.yaxis.label.set_color('blue')
        axes1.plot(freq, np.absolute(data), color='blue', label='Magnitude')
        axes2 = axes1.twinx()
        axes2.spines['left'].set_color('blue')
        axes2.spines['right'].set_color('red')
        axes1.set_xlabel('Hz')
        axes1.set_ylabel('Magnitude')
        axes2.set_ylabel('Phase angle')
        axes2.tick_params('y', color='red', labelcolor='red')
        axes2.yaxis.label.set_color('red')
        axes2.plot(freq,
                   np.angle(data, deg=True),
                   color='red',
                   label='Phase angle')
        self.cursor = datacursor(axes=self.figure.get_axes(),
                                 formatter=LabelFormatter(),
                                 display='multiple')
        self.canvas.draw()

    def plot_open(self):
        self.plot_magphase(self.open.freq, self.open.data)

    def plot_short(self):
        self.plot_magphase(self.short.freq, self.short.data)

    def plot_load(self):
        self.plot_magphase(self.load.freq, self.load.data)

    def plot_dut(self):
        self.plot_magphase(self.dut.freq, self.dut.data)

    def plot_smith_grid(self, axes, color):
        load = 50.0
        ticks = np.array([0.0, 0.2, 0.5, 1.0, 2.0, 5.0])
        for tick in ticks * load:
            axis = np.logspace(-4, np.log10(1.0e3), 200) * load
            z = tick + 1.0j * axis
            gamma = (z - load) / (z + load)
            axes.plot(gamma.real,
                      gamma.imag,
                      color=color,
                      linewidth=0.4,
                      alpha=0.3)
            axes.plot(gamma.real,
                      -gamma.imag,
                      color=color,
                      linewidth=0.4,
                      alpha=0.3)
            z = axis + 1.0j * tick
            gamma = (z - load) / (z + load)
            axes.plot(gamma.real,
                      gamma.imag,
                      color=color,
                      linewidth=0.4,
                      alpha=0.3)
            axes.plot(gamma.real,
                      -gamma.imag,
                      color=color,
                      linewidth=0.4,
                      alpha=0.3)
            if tick == 0.0:
                axes.text(1.0,
                          0.0,
                          u'\u221E',
                          color=color,
                          ha='left',
                          va='center',
                          clip_on=True,
                          fontsize=18.0)
                axes.text(-1.0,
                          0.0,
                          u'0\u03A9',
                          color=color,
                          ha='left',
                          va='bottom',
                          clip_on=True,
                          fontsize=12.0)
                continue
            lab = u'%d\u03A9' % tick
            x = (tick - load) / (tick + load)
            axes.text(x,
                      0.0,
                      lab,
                      color=color,
                      ha='left',
                      va='bottom',
                      clip_on=True,
                      fontsize=12.0)
            lab = u'j%d\u03A9' % tick
            z = 1.0j * tick
            gamma = (z - load) / (z + load) * 1.05
            x = gamma.real
            y = gamma.imag
            angle = np.angle(gamma) * 180.0 / np.pi - 90.0
            axes.text(x,
                      y,
                      lab,
                      color=color,
                      ha='center',
                      va='center',
                      clip_on=True,
                      rotation=angle,
                      fontsize=12.0)
            lab = u'-j%d\u03A9' % tick
            axes.text(x,
                      -y,
                      lab,
                      color=color,
                      ha='center',
                      va='center',
                      clip_on=True,
                      rotation=-angle,
                      fontsize=12.0)

    def plot_smith(self):
        if self.cursor is not None: self.cursor.hide().disable()
        matplotlib.rcdefaults()
        self.figure.clf()
        self.figure.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0)
        axes1 = self.figure.add_subplot(111)
        self.plot_smith_grid(axes1, 'blue')
        gamma = self.gamma()
        plot, = axes1.plot(gamma.real, gamma.imag, color='red')
        axes1.axis('equal')
        axes1.set_xlim(-1.12, 1.12)
        axes1.set_ylim(-1.12, 1.12)
        axes1.xaxis.set_visible(False)
        axes1.yaxis.set_visible(False)
        for loc, spine in axes1.spines.items():
            spine.set_visible(False)
        self.cursor = datacursor(plot,
                                 formatter=SmithFormatter(self.dut.freq),
                                 display='multiple')
        self.canvas.draw()

    def plot_imp(self):
        self.plot_magphase(self.dut.freq, self.impedance())

    def plot_rc(self):
        self.plot_magphase(self.dut.freq, self.gamma())

    def plot_swr(self):
        if self.cursor is not None: self.cursor.hide().disable()
        matplotlib.rcdefaults()
        self.figure.clf()
        self.figure.subplots_adjust(left=0.12,
                                    bottom=0.12,
                                    right=0.88,
                                    top=0.98)
        axes1 = self.figure.add_subplot(111)
        axes1.cla()
        axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
        axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix))
        axes1.set_xlabel('Hz')
        axes1.set_ylabel('SWR')
        magnitude = np.absolute(self.gamma())
        swr = np.maximum(
            1.0,
            np.minimum(100.0, (1.0 + magnitude) /
                       np.maximum(1.0e-20, 1.0 - magnitude)))
        axes1.plot(self.dut.freq, swr, color='blue', label='SWR')
        self.cursor = datacursor(axes=self.figure.get_axes(),
                                 formatter=LabelFormatter(),
                                 display='multiple')
        self.canvas.draw()

    def plot_rl(self):
        if self.cursor is not None: self.cursor.hide().disable()
        matplotlib.rcdefaults()
        self.figure.clf()
        self.figure.subplots_adjust(left=0.12,
                                    bottom=0.12,
                                    right=0.88,
                                    top=0.98)
        axes1 = self.figure.add_subplot(111)
        axes1.cla()
        axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
        axes1.set_xlabel('Hz')
        axes1.set_ylabel('Return loss, dB')
        magnitude = np.absolute(self.gamma())
        axes1.plot(self.dut.freq,
                   20.0 * np.log10(magnitude),
                   color='blue',
                   label='Return loss')
        self.cursor = datacursor(axes=self.figure.get_axes(),
                                 formatter=LabelFormatter(),
                                 display='multiple')
        self.canvas.draw()

    def write_cfg(self):
        dialog = QFileDialog(self, 'Write configuration settings', '.',
                             '*.ini')
        dialog.setDefaultSuffix('ini')
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setOptions(QFileDialog.DontConfirmOverwrite)
        if dialog.exec() == QDialog.Accepted:
            name = dialog.selectedFiles()
            settings = QSettings(name[0], QSettings.IniFormat)
            self.write_cfg_settings(settings)

    def read_cfg(self):
        dialog = QFileDialog(self, 'Read configuration settings', '.', '*.ini')
        dialog.setDefaultSuffix('ini')
        dialog.setAcceptMode(QFileDialog.AcceptOpen)
        if dialog.exec() == QDialog.Accepted:
            name = dialog.selectedFiles()
            settings = QSettings(name[0], QSettings.IniFormat)
            self.read_cfg_settings(settings)

    def write_cfg_settings(self, settings):
        settings.setValue('addr', self.addrValue.text())
        settings.setValue('rate', self.rateValue.currentIndex())
        settings.setValue('corr', self.corrValue.value())
        settings.setValue('open_start', int(self.open.freq[0]))
        settings.setValue('open_stop', int(self.open.freq[-1]))
        settings.setValue('open_size', self.open.freq.size)
        settings.setValue('short_start', int(self.short.freq[0]))
        settings.setValue('short_stop', int(self.short.freq[-1]))
        settings.setValue('short_size', self.short.freq.size)
        settings.setValue('load_start', int(self.load.freq[0]))
        settings.setValue('load_stop', int(self.load.freq[-1]))
        settings.setValue('load_size', self.load.freq.size)
        settings.setValue('dut_start', int(self.dut.freq[0]))
        settings.setValue('dut_stop', int(self.dut.freq[-1]))
        settings.setValue('dut_size', self.dut.freq.size)
        data = self.open.data
        for i in range(0, self.open.freq.size):
            settings.setValue('open_real_%d' % i, float(data.real[i]))
            settings.setValue('open_imag_%d' % i, float(data.imag[i]))
        data = self.short.data
        for i in range(0, self.short.freq.size):
            settings.setValue('short_real_%d' % i, float(data.real[i]))
            settings.setValue('short_imag_%d' % i, float(data.imag[i]))
        data = self.load.data
        for i in range(0, self.load.freq.size):
            settings.setValue('load_real_%d' % i, float(data.real[i]))
            settings.setValue('load_imag_%d' % i, float(data.imag[i]))
        data = self.dut.data
        for i in range(0, self.dut.freq.size):
            settings.setValue('dut_real_%d' % i, float(data.real[i]))
            settings.setValue('dut_imag_%d' % i, float(data.imag[i]))

    def read_cfg_settings(self, settings):
        self.addrValue.setText(settings.value('addr', '192.168.1.100'))
        self.rateValue.setCurrentIndex(settings.value('rate', 0, type=int))
        self.corrValue.setValue(settings.value('corr', 0, type=int))
        open_start = settings.value('open_start', 10000, type=int) // 1000
        open_stop = settings.value('open_stop', 60000000, type=int) // 1000
        open_size = settings.value('open_size', 6000, type=int)
        short_start = settings.value('short_start', 10000, type=int) // 1000
        short_stop = settings.value('short_stop', 60000000, type=int) // 1000
        short_size = settings.value('short_size', 6000, type=int)
        load_start = settings.value('load_start', 10000, type=int) // 1000
        load_stop = settings.value('load_stop', 60000000, type=int) // 1000
        load_size = settings.value('load_size', 6000, type=int)
        dut_start = settings.value('dut_start', 10000, type=int) // 1000
        dut_stop = settings.value('dut_stop', 60000000, type=int) // 1000
        dut_size = settings.value('dut_size', 6000, type=int)
        self.startValue.setValue(dut_start)
        self.stopValue.setValue(dut_stop)
        self.sizeValue.setValue(dut_size)
        self.open = Measurement(open_start, open_stop, open_size)
        for i in range(0, open_size):
            real = settings.value('open_real_%d' % i, 0.0, type=float)
            imag = settings.value('open_imag_%d' % i, 0.0, type=float)
            self.open.data[i] = real + 1.0j * imag
        self.short = Measurement(short_start, short_stop, short_size)
        for i in range(0, short_size):
            real = settings.value('short_real_%d' % i, 0.0, type=float)
            imag = settings.value('short_imag_%d' % i, 0.0, type=float)
            self.short.data[i] = real + 1.0j * imag
        self.load = Measurement(load_start, load_stop, load_size)
        for i in range(0, load_size):
            real = settings.value('load_real_%d' % i, 0.0, type=float)
            imag = settings.value('load_imag_%d' % i, 0.0, type=float)
            self.load.data[i] = real + 1.0j * imag
        self.dut = Measurement(dut_start, dut_stop, dut_size)
        for i in range(0, dut_size):
            real = settings.value('dut_real_%d' % i, 0.0, type=float)
            imag = settings.value('dut_imag_%d' % i, 0.0, type=float)
            self.dut.data[i] = real + 1.0j * imag

    def write_csv(self):
        dialog = QFileDialog(self, 'Write csv file', '.', '*.csv')
        dialog.setDefaultSuffix('csv')
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setOptions(QFileDialog.DontConfirmOverwrite)
        if dialog.exec() == QDialog.Accepted:
            name = dialog.selectedFiles()
            fh = open(name[0], 'w')
            o = self.interp(self.open.freq, self.open.data)
            s = self.interp(self.short.freq, self.short.data)
            l = self.interp(self.load.freq, self.load.data)
            d = self.dut.data
            f = self.dut.freq
            fh.write(
                'frequency;open.real;open.imag;short.real;short.imag;load.real;load.imag;dut.real;dut.imag\n'
            )
            for i in range(0, f.size):
                fh.write(
                    '0.0%.8d;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f;%12.9f\n'
                    % (f[i], o.real[i], o.imag[i], s.real[i], s.imag[i],
                       l.real[i], l.imag[i], d.real[i], d.imag[i]))
            fh.close()

    def write_s1p(self):
        dialog = QFileDialog(self, 'Write s1p file', '.', '*.s1p')
        dialog.setDefaultSuffix('s1p')
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setOptions(QFileDialog.DontConfirmOverwrite)
        if dialog.exec() == QDialog.Accepted:
            name = dialog.selectedFiles()
            fh = open(name[0], 'w')
            gamma = self.gamma()
            freq = self.dut.freq
            fh.write('# GHz S MA R 50\n')
            for i in range(0, freq.size):
                fh.write('0.0%.8d   %8.6f %7.2f\n' %
                         (freq[i], np.absolute(
                             gamma[i]), np.angle(gamma[i], deg=True)))
            fh.close()

    def write_s2p(self):
        dialog = QFileDialog(self, 'Write s2p file', '.', '*.s2p')
        dialog.setDefaultSuffix('s2p')
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setOptions(QFileDialog.DontConfirmOverwrite)
        if dialog.exec() == QDialog.Accepted:
            name = dialog.selectedFiles()
            fh = open(name[0], 'w')
            gain = self.gain()
            gamma = self.gamma()
            freq = self.dut.freq
            fh.write('# GHz S MA R 50\n')
            for i in range(0, freq.size):
                fh.write(
                    '0.0%.8d   %8.6f %7.2f   %8.6f %7.2f   0.000000    0.00   0.000000    0.00\n'
                    % (freq[i], np.absolute(gamma[i]),
                       np.angle(gamma[i], deg=True), np.absolute(
                           gain[i]), np.angle(gain[i], deg=True)))
            fh.close()
Example #37
0
        draw = False
        for item in self.menuitems:
            draw = item.set_hover(event)
            if draw:
                self.figure.canvas.draw()
                break


app = QApplication(sys.argv)

fig = Figure(figsize=(8, 6))
canvas = FigureCanvas(fig)
canvas.resize(640, 480)
canvas.show()

fig.subplots_adjust(left=0.3)
props = ItemProperties(labelcolor='black',
                       bgcolor='yellow',
                       fontsize=15,
                       alpha=0.2)
hoverprops = ItemProperties(labelcolor='white',
                            bgcolor='blue',
                            fontsize=15,
                            alpha=0.2)

menuitems = []
for label in ('open', 'close', 'save', 'save as', 'quit'):

    def on_select(item):
        print('you selected %s' % item.labelstr)
Example #38
0
class HorizonFrame(wx.Frame):
    """ The main frame of the horizon indicator."""

    def __init__(self, state, title):
        self.state = state
        # Create Frame and Panel(s)
        wx.Frame.__init__(self, None, title=title)
        state.frame = self

        # Initialisation
        self.initData()
        self.initUI()
        self.startTime = time.time()
        self.nextTime = 0.0
        self.fps = 10.0

    def initData(self):
        # Initialise Attitude
        self.pitch = 0.0  # Degrees
        self.roll = 0.0   # Degrees
        self.yaw = 0.0    # Degrees
        
        # History Values
        self.oldRoll = 0.0 # Degrees
        
        # Initialise Rate Information
        self.airspeed = 0.0 # m/s
        self.relAlt = 0.0 # m relative to home position
        self.relAltTime = 0.0 # s The time that the relative altitude was recorded
        self.climbRate = 0.0 # m/s
        self.altHist = [] # Altitude History
        self.timeHist = [] # Time History
        self.altMax = 0.0 # Maximum altitude since startup
        
        # Initialise HUD Info
        self.heading = 0.0 # 0-360
        
        # Initialise Battery Info
        self.voltage = 0.0
        self.current = 0.0
        self.batRemain = 0.0

        # Initialise Mode and State
        self.mode = 'UNKNOWN'
        self.armed = ''
        self.safetySwitch = ''
        
        # Intialise Waypoint Information
        self.currentWP = 0
        self.finalWP = 0
        self.wpDist = 0
        self.nextWPTime = 0
        self.wpBearing = 0
    

    def initUI(self):
        # Create Event Timer and Bindings
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
        self.timer.Start(100)
        self.Bind(wx.EVT_IDLE, self.on_idle)
        self.Bind(wx.EVT_CHAR_HOOK,self.on_KeyPress)

        # Create Panel
        self.panel = wx.Panel(self)
        self.vertSize = 0.09
        self.resized = False
        
        # Create Matplotlib Panel
        self.createPlotPanel()

        # Fix Axes - vertical is of length 2, horizontal keeps the same lengthscale
        self.rescaleX()
        self.calcFontScaling()        
        
        # Create Horizon Polygons
        self.createHorizonPolygons()
        
        # Center Pointer Marker
        self.thick = 0.015
        self.createCenterPointMarker()
        
        # Pitch Markers
        self.dist10deg = 0.2 # Graph distance per 10 deg
        self.createPitchMarkers()
        
        # Add Roll, Pitch, Yaw Text
        self.createRPYText()
        
        # Add Airspeed, Altitude, Climb Rate Text
        self.createAARText()
        
        # Create Heading Pointer
        self.createHeadingPointer()
        
        # Create North Pointer
        self.createNorthPointer()
        
        # Create Battery Bar
        self.batWidth = 0.1
        self.batHeight = 0.2
        self.rOffset = 0.35
        self.createBatteryBar()
        
        # Create Mode & State Text
        self.createStateText()
        
        # Create Waypoint Text
        self.createWPText()
        
        # Create Waypoint Pointer
        self.createWPPointer()
        
        # Create Altitude History Plot
        self.createAltHistoryPlot()
        
        # Show Frame
        self.Show(True)
        self.pending = []
    
    def createPlotPanel(self):
        '''Creates the figure and axes for the plotting panel.'''
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self,-1,self.figure)
        self.canvas.SetSize(wx.Size(300,300))
        self.axes.axis('off')
        self.figure.subplots_adjust(left=0,right=1,top=1,bottom=0)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas,1,wx.EXPAND,wx.ALL)
        self.SetSizerAndFit(self.sizer)
        self.Fit()
        
    def rescaleX(self):
        '''Rescales the horizontal axes to make the lengthscales equal.'''
        self.ratio = self.figure.get_size_inches()[0]/float(self.figure.get_size_inches()[1])
        self.axes.set_xlim(-self.ratio,self.ratio)
        self.axes.set_ylim(-1,1)
        
    def calcFontScaling(self):
        '''Calculates the current font size and left position for the current window.'''
        self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi
        self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi
        self.fontSize = self.vertSize*(self.ypx/2.0)
        self.leftPos = self.axes.get_xlim()[0]
        self.rightPos = self.axes.get_xlim()[1]
    
    def checkReszie(self):
        '''Checks if the window was resized.'''
        if not self.resized:
            oldypx = self.ypx
            oldxpx = self.xpx
            self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi
            self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi
            if (oldypx != self.ypx) or (oldxpx != self.xpx):
                self.resized = True
            else:
                self.resized = False
    
    def createHeadingPointer(self):
        '''Creates the pointer for the current heading.'''
        self.headingTri = patches.RegularPolygon((0.0,0.80),3,0.05,color='k',zorder=4)
        self.axes.add_patch(self.headingTri)
        self.headingText = self.axes.text(0.0,0.675,'0',color='k',size=self.fontSize,horizontalalignment='center',verticalalignment='center',zorder=4)
    
    def adjustHeadingPointer(self):
        '''Adjust the value of the heading pointer.'''
        self.headingText.set_text(str(self.heading))
        self.headingText.set_size(self.fontSize) 
    
    def createNorthPointer(self):
        '''Creates the north pointer relative to current heading.'''
        self.headingNorthTri = patches.RegularPolygon((0.0,0.80),3,0.05,color='k',zorder=4)
        self.axes.add_patch(self.headingNorthTri)
        self.headingNorthText = self.axes.text(0.0,0.675,'N',color='k',size=self.fontSize,horizontalalignment='center',verticalalignment='center',zorder=4)    

    def adjustNorthPointer(self):
        '''Adjust the position and orientation of
        the north pointer.'''
        self.headingNorthText.set_size(self.fontSize) 
        headingRotate = mpl.transforms.Affine2D().rotate_deg_around(0.0,0.0,self.heading)+self.axes.transData
        self.headingNorthText.set_transform(headingRotate)
        if (self.heading > 90) and (self.heading < 270):
            headRot = self.heading-180
        else:
            headRot = self.heading
        self.headingNorthText.set_rotation(headRot)
        self.headingNorthTri.set_transform(headingRotate)
        # Adjust if overlapping with heading pointer
        if (self.heading <= 10.0) or (self.heading >= 350.0):
            self.headingNorthText.set_text('')
        else:
            self.headingNorthText.set_text('N')
            
    def toggleWidgets(self,widgets):
        '''Hides/shows the given widgets.'''
        for wig in widgets:
            if wig.get_visible():
                wig.set_visible(False)
            else:
                wig.set_visible(True)
    
    def createRPYText(self):
        '''Creates the text for roll, pitch and yaw.'''
        self.rollText = self.axes.text(self.leftPos+(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0),'Roll:   %.2f' % self.roll,color='w',size=self.fontSize)
        self.pitchText = self.axes.text(self.leftPos+(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0),'Pitch: %.2f' % self.pitch,color='w',size=self.fontSize)
        self.yawText = self.axes.text(self.leftPos+(self.vertSize/10.0),-0.97,'Yaw:   %.2f' % self.yaw,color='w',size=self.fontSize)
        self.rollText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        self.pitchText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        self.yawText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        
    def updateRPYLocations(self):
        '''Update the locations of roll, pitch, yaw text.'''
        # Locations
        self.rollText.set_position((self.leftPos+(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0)))
        self.pitchText.set_position((self.leftPos+(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0)))
        self.yawText.set_position((self.leftPos+(self.vertSize/10.0),-0.97))
        # Font Size
        self.rollText.set_size(self.fontSize)
        self.pitchText.set_size(self.fontSize)
        self.yawText.set_size(self.fontSize)
        
    def updateRPYText(self):
        'Updates the displayed Roll, Pitch, Yaw Text'
        self.rollText.set_text('Roll:   %.2f' % self.roll)
        self.pitchText.set_text('Pitch: %.2f' % self.pitch)
        self.yawText.set_text('Yaw:   %.2f' % self.yaw)
        
    def createCenterPointMarker(self):
        '''Creates the center pointer in the middle of the screen.'''
        self.axes.add_patch(patches.Rectangle((-0.75,-self.thick),0.5,2.0*self.thick,facecolor='orange',zorder=3))
        self.axes.add_patch(patches.Rectangle((0.25,-self.thick),0.5,2.0*self.thick,facecolor='orange',zorder=3))
        self.axes.add_patch(patches.Circle((0,0),radius=self.thick,facecolor='orange',edgecolor='none',zorder=3))
        
    def createHorizonPolygons(self):
        '''Creates the two polygons to show the sky and ground.'''
        # Sky Polygon
        vertsTop = [[-1,0],[-1,1],[1,1],[1,0],[-1,0]]
        self.topPolygon = Polygon(vertsTop,facecolor='dodgerblue',edgecolor='none')
        self.axes.add_patch(self.topPolygon)
        # Ground Polygon
        vertsBot = [[-1,0],[-1,-1],[1,-1],[1,0],[-1,0]]
        self.botPolygon = Polygon(vertsBot,facecolor='brown',edgecolor='none')
        self.axes.add_patch(self.botPolygon)
        
    def calcHorizonPoints(self):
        '''Updates the verticies of the patches for the ground and sky.'''
        ydiff = math.tan(math.radians(-self.roll))*float(self.ratio)
        pitchdiff = self.dist10deg*(self.pitch/10.0)
        # Sky Polygon
        vertsTop = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,1),(self.ratio,1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)]       
        self.topPolygon.set_xy(vertsTop)
        # Ground Polygon
        vertsBot = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,-1),(self.ratio,-1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)]       
        self.botPolygon.set_xy(vertsBot)  
    
    def createPitchMarkers(self):
        '''Creates the rectangle patches for the pitch indicators.'''
        self.pitchPatches = []
        # Major Lines (multiple of 10 deg)
        for i in [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9]:
            width = self.calcPitchMarkerWidth(i)
            currPatch = patches.Rectangle((-width/2.0,self.dist10deg*i-(self.thick/2.0)),width,self.thick,facecolor='w',edgecolor='none')
            self.axes.add_patch(currPatch)
            self.pitchPatches.append(currPatch)
        # Add Label for +-30 deg
        self.vertSize = 0.09
        self.pitchLabelsLeft = []
        self.pitchLabelsRight = []
        i=0
        for j in [-90,-60,-30,30,60,90]:
            self.pitchLabelsLeft.append(self.axes.text(-0.55,(j/10.0)*self.dist10deg,str(j),color='w',size=self.fontSize,horizontalalignment='center',verticalalignment='center'))
            self.pitchLabelsLeft[i].set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
            self.pitchLabelsRight.append(self.axes.text(0.55,(j/10.0)*self.dist10deg,str(j),color='w',size=self.fontSize,horizontalalignment='center',verticalalignment='center'))
            self.pitchLabelsRight[i].set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
            i += 1
        
    def calcPitchMarkerWidth(self,i):
        '''Calculates the width of a pitch marker.'''
        if (i % 3) == 0:
            if i == 0:
                width = 1.5
            else:
                width = 0.9
        else:
            width = 0.6
            
        return width
        
    def adjustPitchmarkers(self):
        '''Adjusts the location and orientation of pitch markers.'''
        pitchdiff = self.dist10deg*(self.pitch/10.0)
        rollRotate = mpl.transforms.Affine2D().rotate_deg_around(0.0,-pitchdiff,self.roll)+self.axes.transData
        j=0
        for i in [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9]:
            width = self.calcPitchMarkerWidth(i)
            self.pitchPatches[j].set_xy((-width/2.0,self.dist10deg*i-(self.thick/2.0)-pitchdiff))
            self.pitchPatches[j].set_transform(rollRotate)
            j+=1
        # Adjust Text Size and rotation
        i=0
        for j in [-9,-6,-3,3,6,9]:
                self.pitchLabelsLeft[i].set_y(j*self.dist10deg-pitchdiff)
                self.pitchLabelsRight[i].set_y(j*self.dist10deg-pitchdiff)
                self.pitchLabelsLeft[i].set_size(self.fontSize)
                self.pitchLabelsRight[i].set_size(self.fontSize)
                self.pitchLabelsLeft[i].set_rotation(self.roll)
                self.pitchLabelsRight[i].set_rotation(self.roll)
                self.pitchLabelsLeft[i].set_transform(rollRotate)
                self.pitchLabelsRight[i].set_transform(rollRotate)
                i += 1 
                
    def createAARText(self):
        '''Creates the text for airspeed, altitude and climb rate.'''
        self.airspeedText = self.axes.text(self.rightPos-(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0),'AS:   %.1f m/s' % self.airspeed,color='w',size=self.fontSize,ha='right')
        self.altitudeText = self.axes.text(self.rightPos-(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0),'ALT: %.1f m   ' % self.relAlt,color='w',size=self.fontSize,ha='right')
        self.climbRateText = self.axes.text(self.rightPos-(self.vertSize/10.0),-0.97,'CR:   %.1f m/s' % self.climbRate,color='w',size=self.fontSize,ha='right')
        self.airspeedText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        self.altitudeText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        self.climbRateText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        
    def updateAARLocations(self):
        '''Update the locations of airspeed, altitude and Climb rate.'''
        # Locations
        self.airspeedText.set_position((self.rightPos-(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0)))
        self.altitudeText.set_position((self.rightPos-(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0)))
        self.climbRateText.set_position((self.rightPos-(self.vertSize/10.0),-0.97))
        # Font Size
        self.airspeedText.set_size(self.fontSize)
        self.altitudeText.set_size(self.fontSize)
        self.climbRateText.set_size(self.fontSize)
        
    def updateAARText(self):
        'Updates the displayed airspeed, altitude, climb rate Text'
        self.airspeedText.set_text('AR:   %.1f m/s' % self.airspeed)
        self.altitudeText.set_text('ALT: %.1f m   ' % self.relAlt)
        self.climbRateText.set_text('CR:   %.1f m/s' % self.climbRate)
    
    def createBatteryBar(self):
        '''Creates the bar to display current battery percentage.'''
        self.batOutRec = patches.Rectangle((self.rightPos-(1.3+self.rOffset)*self.batWidth,1.0-(0.1+1.0+(2*0.075))*self.batHeight),self.batWidth*1.3,self.batHeight*1.15,facecolor='darkgrey',edgecolor='none')
        self.batInRec = patches.Rectangle((self.rightPos-(self.rOffset+1+0.15)*self.batWidth,1.0-(0.1+1+0.075)*self.batHeight),self.batWidth,self.batHeight,facecolor='lawngreen',edgecolor='none')
        self.batPerText = self.axes.text(self.rightPos - (self.rOffset+0.65)*self.batWidth,1-(0.1+1+(0.075+0.15))*self.batHeight,'%.f' % self.batRemain,color='w',size=self.fontSize,ha='center',va='top')
        self.batPerText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        self.voltsText = self.axes.text(self.rightPos-(self.rOffset+1.3+0.2)*self.batWidth,1-(0.1+0.05+0.075)*self.batHeight,'%.1f V' % self.voltage,color='w',size=self.fontSize,ha='right',va='top')
        self.ampsText = self.axes.text(self.rightPos-(self.rOffset+1.3+0.2)*self.batWidth,1-self.vertSize-(0.1+0.05+0.1+0.075)*self.batHeight,'%.1f A' % self.current,color='w',size=self.fontSize,ha='right',va='top')
        self.voltsText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        self.ampsText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
        
        self.axes.add_patch(self.batOutRec)
        self.axes.add_patch(self.batInRec)
        
    def updateBatteryBar(self):
        '''Updates the position and values of the battery bar.'''
        # Bar
        self.batOutRec.set_xy((self.rightPos-(1.3+self.rOffset)*self.batWidth,1.0-(0.1+1.0+(2*0.075))*self.batHeight))
        self.batInRec.set_xy((self.rightPos-(self.rOffset+1+0.15)*self.batWidth,1.0-(0.1+1+0.075)*self.batHeight))
        self.batPerText.set_position((self.rightPos - (self.rOffset+0.65)*self.batWidth,1-(0.1+1+(0.075+0.15))*self.batHeight))
        self.batPerText.set_fontsize(self.fontSize)
        self.voltsText.set_text('%.1f V' % self.voltage)
        self.ampsText.set_text('%.1f A' % self.current)
        self.voltsText.set_position((self.rightPos-(self.rOffset+1.3+0.2)*self.batWidth,1-(0.1+0.05)*self.batHeight))
        self.ampsText.set_position((self.rightPos-(self.rOffset+1.3+0.2)*self.batWidth,1-self.vertSize-(0.1+0.05+0.1)*self.batHeight))
        self.voltsText.set_fontsize(self.fontSize)
        self.ampsText.set_fontsize(self.fontSize)
        if self.batRemain >= 0:
            self.batPerText.set_text(int(self.batRemain))
            self.batInRec.set_height(self.batRemain*self.batHeight/100.0)
            if self.batRemain/100.0 > 0.5:
                self.batInRec.set_facecolor('lawngreen')
            elif self.batRemain/100.0 <= 0.5 and self.batRemain/100.0 > 0.2:
                self.batInRec.set_facecolor('yellow')
            elif self.batRemain/100.0 <= 0.2 and self.batRemain >= 0.0:
                self.batInRec.set_facecolor('r')
        elif self.batRemain == -1:
            self.batInRec.set_height(self.batHeight)
            self.batInRec.set_facecolor('k')
        
    def createStateText(self):
        '''Creates the mode and arm state text.'''
        self.modeText = self.axes.text(self.leftPos+(self.vertSize/10.0),0.97,'UNKNOWN',color='grey',size=1.5*self.fontSize,ha='left',va='top')
        self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foreground='black')])
        
    def updateStateText(self):
        '''Updates the mode and colours red or green depending on arm state.'''
        self.modeText.set_position((self.leftPos+(self.vertSize/10.0),0.97))
        self.modeText.set_text(self.mode)
        self.modeText.set_size(1.5*self.fontSize)
        if self.armed:
            self.modeText.set_color('red')
            self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foreground='yellow')])
        elif (self.armed == False):
            self.modeText.set_color('lightgreen')
            self.modeText.set_bbox(None)
            self.modeText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='black')])
        else:
            # Fall back if unknown
            self.modeText.set_color('grey')
            self.modeText.set_bbox(None)
            self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foreground='black')])
        
    def createWPText(self):
        '''Creates the text for the current and final waypoint,
        and the distance to the new waypoint.'''
        self.wpText = self.axes.text(self.leftPos+(1.5*self.vertSize/10.0),0.97-(1.5*self.vertSize)+(0.5*self.vertSize/10.0),'0/0\n(0 m, 0 s)',color='w',size=self.fontSize,ha='left',va='top')
        self.wpText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='black')])
        
    def updateWPText(self):
        '''Updates the current waypoint and distance to it.''' 
        self.wpText.set_position((self.leftPos+(1.5*self.vertSize/10.0),0.97-(1.5*self.vertSize)+(0.5*self.vertSize/10.0)))
        self.wpText.set_size(self.fontSize)
        if type(self.nextWPTime) is str:
            self.wpText.set_text('%.f/%.f\n(%.f m, ~ s)' % (self.currentWP,self.finalWP,self.wpDist))
        else:
            self.wpText.set_text('%.f/%.f\n(%.f m, %.f s)' % (self.currentWP,self.finalWP,self.wpDist,self.nextWPTime))
    
    def createWPPointer(self):
        '''Creates the waypoint pointer relative to current heading.'''
        self.headingWPTri = patches.RegularPolygon((0.0,0.55),3,0.05,facecolor='lime',zorder=4,ec='k')
        self.axes.add_patch(self.headingWPTri)
        self.headingWPText = self.axes.text(0.0,0.45,'1',color='lime',size=self.fontSize,horizontalalignment='center',verticalalignment='center',zorder=4)   
        self.headingWPText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) 

    def adjustWPPointer(self):
        '''Adjust the position and orientation of
        the waypoint pointer.'''
        self.headingWPText.set_size(self.fontSize) 
        headingRotate = mpl.transforms.Affine2D().rotate_deg_around(0.0,0.0,-self.wpBearing+self.heading)+self.axes.transData
        self.headingWPText.set_transform(headingRotate)
        angle = self.wpBearing - self.heading
        if angle < 0:
            angle += 360
        if (angle > 90) and (angle < 270):
            headRot = angle-180
        else:
            headRot = angle
        self.headingWPText.set_rotation(-headRot)
        self.headingWPTri.set_transform(headingRotate)
        self.headingWPText.set_text('%.f' % (angle))
    
    def createAltHistoryPlot(self):
        '''Creates the altitude history plot.'''
        self.altHistRect = patches.Rectangle((self.leftPos+(self.vertSize/10.0),-0.25),0.5,0.5,facecolor='grey',edgecolor='none',alpha=0.4,zorder=4)
        self.axes.add_patch(self.altHistRect)
        self.altPlot, = self.axes.plot([self.leftPos+(self.vertSize/10.0),self.leftPos+(self.vertSize/10.0)+0.5],[0.0,0.0],color='k',marker=None,zorder=4)
        self.altMarker, = self.axes.plot(self.leftPos+(self.vertSize/10.0)+0.5,0.0,marker='o',color='k',zorder=4)
        self.altText2 = self.axes.text(self.leftPos+(4*self.vertSize/10.0)+0.5,0.0,'%.f m' % self.relAlt,color='k',size=self.fontSize,ha='left',va='center',zorder=4)
    
    def updateAltHistory(self):
        '''Updates the altitude history plot.'''
        self.altHist.append(self.relAlt)
        self.timeHist.append(self.relAltTime)
        
        # Delete entries older than x seconds
        histLim = 10
        currentTime = time.time()
        point = 0
        for i in range(0,len(self.timeHist)):
            if (self.timeHist[i] > (currentTime - 10.0)):
                break
        # Remove old entries
        self.altHist = self.altHist[i:]
        self.timeHist = self.timeHist[i:]
        
        # Transform Data
        x = []
        y = []
        tmin = min(self.timeHist)
        tmax = max(self.timeHist)
        x1 = self.leftPos+(self.vertSize/10.0)
        y1 = -0.25
        altMin = 0
        altMax = max(self.altHist)
        # Keep alt max for whole mission
        if altMax > self.altMax:
            self.altMax = altMax
        else:
            altMax = self.altMax
        if tmax != tmin:
            mx = 0.5/(tmax-tmin)
        else:
            mx = 0.0
        if altMax != altMin:
            my = 0.5/(altMax-altMin)
        else:
            my = 0.0
        for t in self.timeHist:
            x.append(mx*(t-tmin)+x1)
        for alt in self.altHist:
            val = my*(alt-altMin)+y1
            # Crop extreme noise
            if val < -0.25:
                val = -0.25
            elif val > 0.25:
                val = 0.25
            y.append(val)
        # Display Plot
        self.altHistRect.set_x(self.leftPos+(self.vertSize/10.0))
        self.altPlot.set_data(x,y)
        self.altMarker.set_data(self.leftPos+(self.vertSize/10.0)+0.5,val)
        self.altText2.set_position((self.leftPos+(4*self.vertSize/10.0)+0.5,val))
        self.altText2.set_size(self.fontSize)
        self.altText2.set_text('%.f m' % self.relAlt)
        
    # =============== Event Bindings =============== #    
    def on_idle(self, event):
        '''To adjust text and positions on rescaling the window when resized.'''
        # Check for resize
        self.checkReszie()
        
        if self.resized:
            # Fix Window Scales 
            self.rescaleX()
            self.calcFontScaling()
            
            # Recalculate Horizon Polygons
            self.calcHorizonPoints()
            
            # Update Roll, Pitch, Yaw Text Locations
            self.updateRPYLocations()
            
            # Update Airpseed, Altitude, Climb Rate Locations
            self.updateAARLocations()
            
            # Update Pitch Markers
            self.adjustPitchmarkers()
            
            # Update Heading and North Pointer
            self.adjustHeadingPointer()
            self.adjustNorthPointer()
            
            # Update Battery Bar
            self.updateBatteryBar()
            
            # Update Mode and State
            self.updateStateText()
            
            # Update Waypoint Text
            self.updateWPText()
            
            # Adjust Waypoint Pointer
            self.adjustWPPointer()
            
            # Update History Plot
            self.updateAltHistory()
            
            # Update Matplotlib Plot
            self.canvas.draw()
            self.canvas.Refresh()
            
            self.resized = False
        
        time.sleep(0.05)
 
    def on_timer(self, event):
        '''Main Loop.'''
        state = self.state
        self.loopStartTime = time.time()
        if state.close_event.wait(0.001):
            self.timer.Stop()
            self.Destroy()
            return
        
        # Check for resizing
        self.checkReszie()
        if self.resized:
            self.on_idle(0)
        
        # Get attitude information
        while state.child_pipe_recv.poll():           
            objList = state.child_pipe_recv.recv()
            for obj in objList:
                self.calcFontScaling()
                if isinstance(obj,Attitude):
                    self.oldRoll = self.roll
                    self.pitch = obj.pitch*180/math.pi
                    self.roll = obj.roll*180/math.pi
                    self.yaw = obj.yaw*180/math.pi
                    
                    # Update Roll, Pitch, Yaw Text Text
                    self.updateRPYText()
                    
                    # Recalculate Horizon Polygons
                    self.calcHorizonPoints()
                    
                    # Update Pitch Markers
                    self.adjustPitchmarkers()
                
                elif isinstance(obj,VFR_HUD):
                    self.heading = obj.heading
                    self.airspeed = obj.airspeed
                    self.climbRate = obj.climbRate
                    
                    # Update Airpseed, Altitude, Climb Rate Locations
                    self.updateAARText()
                    
                    # Update Heading North Pointer
                    self.adjustHeadingPointer()
                    self.adjustNorthPointer()
                
                elif isinstance(obj,Global_Position_INT):
                    self.relAlt = obj.relAlt
                    self.relAltTime = obj.curTime
                    
                    # Update Airpseed, Altitude, Climb Rate Locations
                    self.updateAARText()
                    
                    # Update Altitude History
                    self.updateAltHistory()
                    
                elif isinstance(obj,BatteryInfo):
                    self.voltage = obj.voltage
                    self.current = obj.current
                    self.batRemain = obj.batRemain
                    
                    # Update Battery Bar
                    self.updateBatteryBar()
                    
                elif isinstance(obj,FlightState):
                    self.mode = obj.mode
                    self.armed = obj.armState
                    
                    # Update Mode and Arm State Text
                    self.updateStateText()
                    
                elif isinstance(obj,WaypointInfo):
                    self.currentWP = obj.current
                    self.finalWP = obj.final
                    self.wpDist = obj.currentDist
                    self.nextWPTime = obj.nextWPTime
                    if obj.wpBearing < 0.0:
                        self.wpBearing = obj.wpBearing + 360
                    else:
                        self.wpBearing = obj.wpBearing
                    
                    # Update waypoint text
                    self.updateWPText()
                    
                    # Adjust Waypoint Pointer
                    self.adjustWPPointer()
                    
                elif isinstance(obj, FPS):
                    # Update fps target
                    self.fps = obj.fps
                
                
        # Quit Drawing if too early
        if (time.time() > self.nextTime):                     
            # Update Matplotlib Plot
            self.canvas.draw()
            self.canvas.Refresh()                 
                 
            self.Refresh()
            self.Update()
            
            # Calculate next frame time
            if (self.fps > 0):
                fpsTime = 1/self.fps
                self.nextTime = fpsTime + self.loopStartTime
            else:
                self.nextTime = time.time()
                
    def on_KeyPress(self,event):
        '''To adjust the distance between pitch markers.'''
        if event.GetKeyCode() == wx.WXK_UP:
            self.dist10deg += 0.1
            print('Dist per 10 deg: %.1f' % self.dist10deg)      
        elif event.GetKeyCode() == wx.WXK_DOWN:
            self.dist10deg -= 0.1
            if self.dist10deg <= 0:
                self.dist10deg = 0.1
            print('Dist per 10 deg: %.1f' % self.dist10deg)   
        # Toggle Widgets
        elif event.GetKeyCode() == 49: # 1
            widgets = [self.modeText,self.wpText]
            self.toggleWidgets(widgets)  
        elif event.GetKeyCode() == 50: # 2
            widgets = [self.batOutRec,self.batInRec,self.voltsText,self.ampsText,self.batPerText]
            self.toggleWidgets(widgets)     
        elif event.GetKeyCode() == 51: # 3
            widgets = [self.rollText,self.pitchText,self.yawText]
            self.toggleWidgets(widgets)                 
        elif event.GetKeyCode() == 52: # 4
            widgets = [self.airspeedText,self.altitudeText,self.climbRateText]
            self.toggleWidgets(widgets)
        elif event.GetKeyCode() == 53: # 5
            widgets = [self.altHistRect,self.altPlot,self.altMarker,self.altText2]
            self.toggleWidgets(widgets)
        elif event.GetKeyCode() == 54: # 6
            widgets = [self.headingTri,self.headingText,self.headingNorthTri,self.headingNorthText,self.headingWPTri,self.headingWPText]
            self.toggleWidgets(widgets)
            
        # Update Matplotlib Plot
        self.canvas.draw()
        self.canvas.Refresh()                       
        
        self.Refresh()
        self.Update()
Example #39
0
class func(object):
    def __init__(self, fm, page, setUIPage, setSwitchingEnabled):
        self.page = page
        self.setUIPage = setUIPage
        self.setMainSwitchingEnabled = setSwitchingEnabled

        self.module = fm.module()
        self.module_exists = None

        self.routine_stage = None
        self.routine_activity = None
        # many other internal variables

        self.mode = 'setup'

        # routine_setup variables
        self.routine_setup_ready = None
        self.routine_setup_issues = {
            'keithley_no_port': None,
            'module_exists_false': None,
            'module_ready_false': None,
        }
        self.routine_setup_issues_console = {
            'keithley_no_port':
            'No COM port selected for keithley',
            'module_exists_false':
            'Selected module with ID {} does not exist',
            'module_ready_false':
            'Selected module with ID {} not ready for IV curve',
        }

    def enforce_mode(mode):
        if not (type(mode) in [str, list]):
            raise ValueError

        def wrapper(function):
            def wrapped_function(self, *args, **kwargs):
                if type(mode) is str:
                    valid_mode = self.mode == mode
                elif type(mode) is list:
                    valid_mode = self.mode in mode
                else:
                    valid_mode = False
                if valid_mode:
                    if DEBUG:
                        print(
                            "page {} with mode {} req {} calling function {} with args {} kwargs {}"
                            .format(
                                PAGE_NAME,
                                self.mode,
                                mode,
                                function.__name__,
                                args,
                                kwargs,
                            ))
                    function(self, *args, **kwargs)
                else:
                    print(
                        "page {} mode is {}, needed {} for function {} with args {} kwargs {}"
                        .format(
                            PAGE_NAME,
                            self.mode,
                            mode,
                            function.__name__,
                            args,
                            kwargs,
                        ))

            return wrapped_function

        return wrapper

    @enforce_mode('setup')
    def setup(self):
        self.setupFigures()
        self.rig()
        self.mode = 'routine_setup'
        print("{} setup completed".format(PAGE_NAME))
        self.update_info()

    def setupFigures(self):
        self.all_fig = Figure()
        self.all_ax = self.all_fig.add_subplot(111)
        self.all_fc = FigureCanvas(self.all_fig)
        self.all_tb = NavigationToolbar(self.all_fc, self.page)
        self.page.vlAll.addWidget(self.all_tb)
        self.page.vlAll.addWidget(self.all_fc)
        self.all_fig.subplots_adjust(left=0.105,
                                     right=0.98,
                                     top=0.98,
                                     bottom=0.145)

        self.act_fig = Figure()
        self.act_ax = self.act_fig.add_subplot(111)
        self.act_fc = FigureCanvas(self.act_fig)
        self.act_tb = NavigationToolbar(self.act_fc, self.page)
        self.page.vlActive.addWidget(self.act_tb)
        self.page.vlActive.addWidget(self.act_fc)
        self.act_fig.subplots_adjust(left=0.105,
                                     right=0.98,
                                     top=0.98,
                                     bottom=0.145)

    @enforce_mode('setup')
    def rig(self):
        self.page.sbModuleID.valueChanged.connect(self.updateModuleInfo)
        self.page.pbGoModule.clicked.connect(self.goModule)

    @enforce_mode('routine_setup')
    def updateModuleInfo(self, *args, **kwargs):
        moduleID = self.page.sbModuleID.value()
        self.module_exists = self.module.load(moduleID)
        self.updateElements(change='moduleID')

    @enforce_mode('routine_setup')
    def update_info(self, ID=None, *args, **kwargs):
        self.updateModuleInfo()
        self.updateElements('mode')

    @enforce_mode(['routine_setup', 'routine_perform'])
    def updateElements(self, change=None):
        if change is None:
            return

        if change == 'moduleID' or change == 'all':
            # :TODO:
            # based on module existence & status
            # update dict on setup issues
            # then call function that refreshes pteConsole
            if self.module_exists:
                self.page.leModuleExists.setText(MSG_MODULE_EXISTS_TRUE)
                pcb = -1 if self.module.pcb is None else self.module.pcb
                self.page.leModuleReady.setText(
                    MSG_MODULE_READY_FALSE if pcb ==
                    -1 else MSG_MODULE_READY_TRUE)
                # :TODO:
                # When wirebonding and curing status is added: change this to check if the module is bonded, encapsulated, and cured
            else:
                self.page.leModuleExists.setText(MSG_MODULE_EXISTS_FALSE)
                self.page.leModuleReady.clear()

        if change == 'mode' or change == 'all':
            self.page.sbModuleID.setEnabled(
                self.mode ==
                'routine_setup')  # :TODO: and no issues with routine_setup
            self.page.pbGoModule.setEnabled(
                self.mode == 'routine_setup'
                and self.page.sbModuleID.value() >= 0)

            self.page.pbRefreshComPorts.setEnabled(
                self.mode == 'routine_setup')
            self.page.cbKeithleyPort.setEnabled(self.mode == 'routine_setup')
            self.page.cbKeithleyBaud.setEnabled(self.mode == 'routine_setup')
            self.page.pbKeithleyQuery.setEnabled(self.mode == 'routine_setup')

            self.page.pbRoutineStart.setEnabled(self.mode == 'routine_setup')
            self.page.pbRoutinePause.setEnabled(self.mode == 'routine_perform')
            self.page.pbRoutineResume.setEnabled(
                self.mode == 'routine_perform')
            self.page.pbRoutineDescend.setEnabled(
                self.mode == 'routine_perform')
            self.page.pbRoutineEnd.setEnabled(self.mode == 'routine_perform')

            self.page.pteNotes.setEnabled(self.mode == 'routine_perform')

    @enforce_mode('routine_setup')
    def goModule(self, *args, **kwargs):
        moduleID = self.page.sbModuleID.value()
        if moduleID >= 0:
            self.setUIPage(PAGE_ID_MODULE, ID=moduleID)

    @enforce_mode('routine_setup')
    def load_kwargs(self, kwargs):
        ...

    @enforce_mode('routine_setup')
    def changed_to(self):
        self.updateModuleInfo(
        )  # module info may have changed, so we reload it and propagate consequences.
Example #40
0
class SquidGui(QtGui.QMainWindow):
    defaults = {}
    defaults.update(SquidAxon.defaults)
    defaults.update(ClampCircuit.defaults)
    defaults.update({
        'runtime': 50.0,
        'simdt': 0.01,
        'plotdt': 0.1,
        'vclamp.holdingV': 0.0,
        'vclamp.holdingT': 10.0,
        'vclamp.prepulseV': 0.0,
        'vclamp.prepulseT': 0.0,
        'vclamp.clampV': 50.0,
        'vclamp.clampT': 20.0,
        'iclamp.baseI': 0.0,
        'iclamp.firstI': 0.1,
        'iclamp.firstT': 40.0,
        'iclamp.firstD': 5.0,
        'iclamp.secondI': 0.0,
        'iclamp.secondT': 0.0,
        'iclamp.secondD': 0.0
    })

    def __init__(self, *args):
        QtGui.QMainWindow.__init__(self, *args)
        self.squid_setup = SquidSetup()
        self._plotdt = SquidGui.defaults['plotdt']
        self._plot_dict = defaultdict(list)
        self.setWindowTitle('Squid Axon simulation')
        self.setDockNestingEnabled(True)
        self._createRunControl()
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self._runControlDock)
        self._runControlDock.setFeatures(
            QtGui.QDockWidget.AllDockWidgetFeatures)
        self._createChannelControl()
        self._channelCtrlBox.setWindowTitle('Channel properties')
        self._channelControlDock.setFeatures(
            QtGui.QDockWidget.AllDockWidgetFeatures)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea,
                           self._channelControlDock)
        self._createElectronicsControl()
        self._electronicsDock.setFeatures(
            QtGui.QDockWidget.AllDockWidgetFeatures)
        self._electronicsDock.setWindowTitle('Electronics')
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self._electronicsDock)
        self._createPlotWidget()
        self.setCentralWidget(self._plotWidget)
        self._createStatePlotWidget()
        self._createHelpMessage()
        self._helpWindow.setVisible(False)
        self._statePlotWidget.setWindowFlags(QtCore.Qt.Window)
        self._statePlotWidget.setWindowTitle('State plot')
        self._initActions()
        self._createRunToolBar()
        self._createPlotToolBar()

    def getFloatInput(self, widget, name):
        try:
            return float(str(widget.text()))
        except ValueError:
            QtGui.QMessageBox.critical(
                self, 'Invalid input',
                'Please enter a valid number for {}'.format(name))
            raise

    def _createPlotWidget(self):
        self._plotWidget = QtGui.QWidget()
        self._plotFigure = Figure()
        self._plotCanvas = FigureCanvas(self._plotFigure)
        self._plotCanvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Expanding)
        self._plotCanvas.updateGeometry()
        self._plotCanvas.setParent(self._plotWidget)
        self._plotCanvas.mpl_connect('scroll_event', self._onScroll)
        self._plotFigure.set_canvas(self._plotCanvas)
        # Vm and command voltage go in the same subplot
        self._vm_axes = self._plotFigure.add_subplot(
            2, 2, 1, title='Membrane potential')
        self._vm_axes.set_ylim(-20.0, 120.0)
        # Channel conductances go to the same subplot
        self._g_axes = self._plotFigure.add_subplot(
            2, 2, 2, title='Channel conductance')
        self._g_axes.set_ylim(0.0, 0.5)
        # Injection current for Vclamp/Iclamp go to the same subplot
        self._im_axes = self._plotFigure.add_subplot(2,
                                                     2,
                                                     3,
                                                     title='Injection current')
        self._im_axes.set_ylim(-0.5, 0.5)
        # Channel currents go to the same subplot
        self._i_axes = self._plotFigure.add_subplot(2,
                                                    2,
                                                    4,
                                                    title='Channel current')
        self._i_axes.set_ylim(-10, 10)
        for axis in self._plotFigure.axes:
            axis.set_autoscale_on(False)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self._plotCanvas)
        self._plotNavigator = NavigationToolbar(self._plotCanvas,
                                                self._plotWidget)
        layout.addWidget(self._plotNavigator)
        self._plotWidget.setLayout(layout)

    def _createStatePlotWidget(self):
        self._statePlotWidget = QtGui.QWidget()
        self._statePlotFigure = Figure()
        self._statePlotCanvas = FigureCanvas(self._statePlotFigure)
        self._statePlotCanvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                            QtGui.QSizePolicy.Expanding)
        self._statePlotCanvas.updateGeometry()
        self._statePlotCanvas.setParent(self._statePlotWidget)
        self._statePlotFigure.set_canvas(self._statePlotCanvas)
        self._statePlotFigure.subplots_adjust(hspace=0.5)
        self._statePlotAxes = self._statePlotFigure.add_subplot(
            2, 1, 1, title='State plot')
        self._state_plot, = self._statePlotAxes.plot([], [], label='state')
        self._activationParamAxes = self._statePlotFigure.add_subplot(
            2, 1, 2, title='H-H activation parameters vs time')
        self._activationParamAxes.set_xlabel('Time (ms)')
        #for axis in self._plotFigure.axes:
        #    axis.autoscale(False)
        self._stateplot_xvar_label = QtGui.QLabel('Variable on X-axis')
        self._stateplot_xvar_combo = QtGui.QComboBox()
        self._stateplot_xvar_combo.addItems(['V', 'm', 'n', 'h'])
        self._stateplot_xvar_combo.setCurrentIndex(0)
        self._stateplot_xvar_combo.setEditable(False)
        self.connect(self._stateplot_xvar_combo,
                     QtCore.SIGNAL('currentIndexChanged(const QString&)'),
                     self._statePlotXSlot)
        self._stateplot_yvar_label = QtGui.QLabel('Variable on Y-axis')
        self._stateplot_yvar_combo = QtGui.QComboBox()
        self._stateplot_yvar_combo.addItems(['V', 'm', 'n', 'h'])
        self._stateplot_yvar_combo.setCurrentIndex(2)
        self._stateplot_yvar_combo.setEditable(False)
        self.connect(self._stateplot_yvar_combo,
                     QtCore.SIGNAL('currentIndexChanged(const QString&)'),
                     self._statePlotYSlot)
        self._statePlotNavigator = NavigationToolbar(self._statePlotCanvas,
                                                     self._statePlotWidget)
        frame = QtGui.QFrame()
        frame.setFrameStyle(QtGui.QFrame.StyledPanel + QtGui.QFrame.Raised)
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self._stateplot_xvar_label)
        layout.addWidget(self._stateplot_xvar_combo)
        layout.addWidget(self._stateplot_yvar_label)
        layout.addWidget(self._stateplot_yvar_combo)
        frame.setLayout(layout)
        self._closeStatePlotAction = QtGui.QAction('Close', self)
        self.connect(self._closeStatePlotAction, QtCore.SIGNAL('triggered()'),
                     self._statePlotWidget.close)
        self._closeStatePlotButton = QtGui.QToolButton()
        self._closeStatePlotButton.setDefaultAction(self._closeStatePlotAction)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(frame)
        layout.addWidget(self._statePlotCanvas)
        layout.addWidget(self._statePlotNavigator)
        layout.addWidget(self._closeStatePlotButton)
        self._statePlotWidget.setLayout(layout)
        # Setting the close event so that when the help window is
        # closed the ``State plot`` button becomes unchecked
        self._statePlotWidget.closeEvent = lambda event: self._showStatePlotAction.setChecked(
            False)

    def _createRunControl(self):
        self._runControlBox = QtGui.QGroupBox(self)
        self._runControlBox.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                          QtGui.QSizePolicy.Preferred)
        self._runTimeLabel = QtGui.QLabel("Run time (ms)", self._runControlBox)
        self._simTimeStepLabel = QtGui.QLabel("Simulation time step (ms)",
                                              self._runControlBox)
        self._runTimeEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['runtime']), self._runControlBox)
        set_default_line_edit_size(self._runTimeEdit)
        self._simTimeStepEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['simdt']), self._runControlBox)
        set_default_line_edit_size(self._simTimeStepEdit)
        layout = QtGui.QGridLayout()
        layout.addWidget(self._runTimeLabel, 0, 0)
        layout.addWidget(self._runTimeEdit, 0, 1)
        layout.addWidget(self._simTimeStepLabel, 1, 0)
        layout.addWidget(self._simTimeStepEdit, 1, 1)
        layout.setColumnStretch(2, 1.0)
        layout.setRowStretch(2, 1.0)
        self._runControlBox.setLayout(layout)
        self._runControlDock = QtGui.QDockWidget('Simulation', self)
        self._runControlDock.setWidget(self._runControlBox)

    def _createChannelControl(self):
        self._channelControlDock = QtGui.QDockWidget('Channels', self)
        self._channelCtrlBox = QtGui.QGroupBox(self)
        self._naConductanceToggle = QtGui.QCheckBox('Block Na+ channel',
                                                    self._channelCtrlBox)
        self._naConductanceToggle.setToolTip('<html>%s</html>' %
                                             (tooltip_NaChan))
        self._kConductanceToggle = QtGui.QCheckBox('Block K+ channel',
                                                   self._channelCtrlBox)
        self._kConductanceToggle.setToolTip('<html>%s</html>' %
                                            (tooltip_KChan))
        self._kOutLabel = QtGui.QLabel('[K+]out (mM)', self._channelCtrlBox)
        self._kOutEdit = QtGui.QLineEdit(
            '%g' % (self.squid_setup.squid_axon.K_out), self._channelCtrlBox)
        self._kOutLabel.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        self._kOutEdit.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        set_default_line_edit_size(self._kOutEdit)
        self._naOutLabel = QtGui.QLabel('[Na+]out (mM)', self._channelCtrlBox)
        self._naOutEdit = QtGui.QLineEdit(
            '%g' % (self.squid_setup.squid_axon.Na_out), self._channelCtrlBox)
        self._naOutLabel.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        self._naOutEdit.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        set_default_line_edit_size(self._naOutEdit)
        self._kInLabel = QtGui.QLabel('[K+]in (mM)', self._channelCtrlBox)
        self._kInEdit = QtGui.QLineEdit(
            '%g' % (self.squid_setup.squid_axon.K_in), self._channelCtrlBox)
        self._kInEdit.setToolTip(tooltip_Nernst)
        self._naInLabel = QtGui.QLabel('[Na+]in (mM)', self._channelCtrlBox)
        self._naInEdit = QtGui.QLineEdit(
            '%g' % (self.squid_setup.squid_axon.Na_in), self._channelCtrlBox)
        self._naInEdit.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        self._temperatureLabel = QtGui.QLabel('Temperature (C)',
                                              self._channelCtrlBox)
        self._temperatureEdit = QtGui.QLineEdit(
            '%g' % (self.defaults['temperature'] - CELSIUS_TO_KELVIN),
            self._channelCtrlBox)
        self._temperatureEdit.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        set_default_line_edit_size(self._temperatureEdit)
        for child in self._channelCtrlBox.children():
            if isinstance(child, QtGui.QLineEdit):
                set_default_line_edit_size(child)
        layout = QtGui.QGridLayout(self._channelCtrlBox)
        layout.addWidget(self._naConductanceToggle, 0, 0)
        layout.addWidget(self._kConductanceToggle, 1, 0)
        layout.addWidget(self._naOutLabel, 2, 0)
        layout.addWidget(self._naOutEdit, 2, 1)
        layout.addWidget(self._naInLabel, 3, 0)
        layout.addWidget(self._naInEdit, 3, 1)
        layout.addWidget(self._kOutLabel, 4, 0)
        layout.addWidget(self._kOutEdit, 4, 1)
        layout.addWidget(self._kInLabel, 5, 0)
        layout.addWidget(self._kInEdit, 5, 1)
        layout.addWidget(self._temperatureLabel, 6, 0)
        layout.addWidget(self._temperatureEdit, 6, 1)
        layout.setRowStretch(7, 1.0)
        self._channelCtrlBox.setLayout(layout)
        self._channelControlDock.setWidget(self._channelCtrlBox)
        return self._channelCtrlBox

    def __get_stateplot_data(self, name):
        data = []
        if name == 'V':
            data = self.squid_setup.vm_table.vector
        elif name == 'm':
            data = self.squid_setup.m_table.vector
        elif name == 'h':
            data = self.squid_setup.h_table.vector
        elif name == 'n':
            data = self.squid_setup.n_table.vector
        else:
            raise ValueError('Unrecognized selection: %s' % (name))
        return numpy.asarray(data)

    def _statePlotYSlot(self, selectedItem):
        ydata = self.__get_stateplot_data(str(selectedItem))
        self._state_plot.set_ydata(ydata)
        self._statePlotAxes.set_ylabel(selectedItem)
        if str(selectedItem) == 'V':
            self._statePlotAxes.set_ylim(-20, 120)
        else:
            self._statePlotAxes.set_ylim(0, 1)
        self._statePlotCanvas.draw()

    def _statePlotXSlot(self, selectedItem):
        xdata = self.__get_stateplot_data(str(selectedItem))
        self._state_plot.set_xdata(xdata)
        self._statePlotAxes.set_xlabel(selectedItem)
        if str(selectedItem) == 'V':
            self._statePlotAxes.set_xlim(-20, 120)
        else:
            self._statePlotAxes.set_xlim(0, 1)
        self._statePlotCanvas.draw()

    def _createElectronicsControl(self):
        """Creates a tabbed widget of voltage clamp and current clamp controls"""
        self._electronicsTab = QtGui.QTabWidget(self)
        self._electronicsTab.addTab(self._getIClampCtrlBox(), 'Current clamp')
        self._electronicsTab.addTab(self._getVClampCtrlBox(), 'Voltage clamp')
        self._electronicsDock = QtGui.QDockWidget(self)
        self._electronicsDock.setWidget(self._electronicsTab)

    def _getVClampCtrlBox(self):
        vClampPanel = QtGui.QGroupBox(self)
        self._vClampCtrlBox = vClampPanel
        self._holdingVLabel = QtGui.QLabel("Holding Voltage (mV)", vClampPanel)
        self._holdingVEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.holdingV']), vClampPanel)
        self._holdingTimeLabel = QtGui.QLabel("Holding Time (ms)", vClampPanel)
        self._holdingTimeEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.holdingT']), vClampPanel)
        self._prePulseVLabel = QtGui.QLabel("Pre-pulse Voltage (mV)",
                                            vClampPanel)
        self._prePulseVEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.prepulseV']), vClampPanel)
        self._prePulseTimeLabel = QtGui.QLabel("Pre-pulse Time (ms)",
                                               vClampPanel)
        self._prePulseTimeEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.prepulseT']), vClampPanel)
        self._clampVLabel = QtGui.QLabel("Clamp Voltage (mV)", vClampPanel)
        self._clampVEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.clampV']), vClampPanel)
        self._clampTimeLabel = QtGui.QLabel("Clamp Time (ms)", vClampPanel)
        self._clampTimeEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.clampT']), vClampPanel)
        for child in vClampPanel.children():
            if isinstance(child, QtGui.QLineEdit):
                set_default_line_edit_size(child)
        layout = QtGui.QGridLayout(vClampPanel)
        layout.addWidget(self._holdingVLabel, 0, 0)
        layout.addWidget(self._holdingVEdit, 0, 1)
        layout.addWidget(self._holdingTimeLabel, 1, 0)
        layout.addWidget(self._holdingTimeEdit, 1, 1)
        layout.addWidget(self._prePulseVLabel, 2, 0)
        layout.addWidget(self._prePulseVEdit, 2, 1)
        layout.addWidget(self._prePulseTimeLabel, 3, 0)
        layout.addWidget(self._prePulseTimeEdit, 3, 1)
        layout.addWidget(self._clampVLabel, 4, 0)
        layout.addWidget(self._clampVEdit, 4, 1)
        layout.addWidget(self._clampTimeLabel, 5, 0)
        layout.addWidget(self._clampTimeEdit, 5, 1)
        layout.setRowStretch(6, 1.0)
        vClampPanel.setLayout(layout)
        return self._vClampCtrlBox

    def _getIClampCtrlBox(self):
        iClampPanel = QtGui.QGroupBox(self)
        self._iClampCtrlBox = iClampPanel
        self._baseCurrentLabel = QtGui.QLabel("Base Current Level (uA)",
                                              iClampPanel)
        self._baseCurrentEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.baseI']), iClampPanel)
        self._firstPulseLabel = QtGui.QLabel("First Pulse Current (uA)",
                                             iClampPanel)
        self._firstPulseEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.firstI']), iClampPanel)
        self._firstDelayLabel = QtGui.QLabel("First Onset Delay (ms)",
                                             iClampPanel)
        self._firstDelayEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.firstD']), iClampPanel)
        self._firstPulseWidthLabel = QtGui.QLabel("First Pulse Width (ms)",
                                                  iClampPanel)
        self._firstPulseWidthEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.firstT']), iClampPanel)
        self._secondPulseLabel = QtGui.QLabel("Second Pulse Current (uA)",
                                              iClampPanel)
        self._secondPulseEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.secondI']), iClampPanel)
        self._secondDelayLabel = QtGui.QLabel("Second Onset Delay (ms)",
                                              iClampPanel)
        self._secondDelayEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.secondD']), iClampPanel)
        self._secondPulseWidthLabel = QtGui.QLabel("Second Pulse Width (ms)",
                                                   iClampPanel)
        self._secondPulseWidthEdit = QtGui.QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.secondT']), iClampPanel)
        self._pulseMode = QtGui.QComboBox(iClampPanel)
        self._pulseMode.addItem("Single Pulse")
        self._pulseMode.addItem("Pulse Train")
        for child in iClampPanel.children():
            if isinstance(child, QtGui.QLineEdit):
                set_default_line_edit_size(child)
        layout = QtGui.QGridLayout(iClampPanel)
        layout.addWidget(self._baseCurrentLabel, 0, 0)
        layout.addWidget(self._baseCurrentEdit, 0, 1)
        layout.addWidget(self._firstPulseLabel, 1, 0)
        layout.addWidget(self._firstPulseEdit, 1, 1)
        layout.addWidget(self._firstDelayLabel, 2, 0)
        layout.addWidget(self._firstDelayEdit, 2, 1)
        layout.addWidget(self._firstPulseWidthLabel, 3, 0)
        layout.addWidget(self._firstPulseWidthEdit, 3, 1)
        layout.addWidget(self._secondPulseLabel, 4, 0)
        layout.addWidget(self._secondPulseEdit, 4, 1)
        layout.addWidget(self._secondDelayLabel, 5, 0)
        layout.addWidget(self._secondDelayEdit, 5, 1)
        layout.addWidget(self._secondPulseWidthLabel, 6, 0)
        layout.addWidget(self._secondPulseWidthEdit, 6, 1)
        layout.addWidget(self._pulseMode, 7, 0, 1, 2)
        layout.setRowStretch(8, 1.0)
        # layout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
        iClampPanel.setLayout(layout)
        return self._iClampCtrlBox

    def _overlayPlots(self, overlay):
        if not overlay:
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                title = axis.get_title()
                axis.clear()
                axis.set_title(title)
            suffix = ''
        else:
            suffix = '_%d' % (len(self._plot_dict['vm']))
        self._vm_axes.set_xlim(0.0, self._runtime)
        self._g_axes.set_xlim(0.0, self._runtime)
        self._im_axes.set_xlim(0.0, self._runtime)
        self._i_axes.set_xlim(0.0, self._runtime)
        self._vm_plot, = self._vm_axes.plot([], [], label='Vm%s' % (suffix))
        self._plot_dict['vm'].append(self._vm_plot)
        self._command_plot, = self._vm_axes.plot([], [],
                                                 label='command%s' % (suffix))
        self._plot_dict['command'].append(self._command_plot)
        # Channel conductances go to the same subplot
        self._gna_plot, = self._g_axes.plot([], [], label='Na%s' % (suffix))
        self._plot_dict['gna'].append(self._gna_plot)
        self._gk_plot, = self._g_axes.plot([], [], label='K%s' % (suffix))
        self._plot_dict['gk'].append(self._gk_plot)
        # Injection current for Vclamp/Iclamp go to the same subplot
        self._iclamp_plot, = self._im_axes.plot([], [],
                                                label='Iclamp%s' % (suffix))
        self._vclamp_plot, = self._im_axes.plot([], [],
                                                label='Vclamp%s' % (suffix))
        self._plot_dict['iclamp'].append(self._iclamp_plot)
        self._plot_dict['vclamp'].append(self._vclamp_plot)
        # Channel currents go to the same subplot
        self._ina_plot, = self._i_axes.plot([], [], label='Na%s' % (suffix))
        self._plot_dict['ina'].append(self._ina_plot)
        self._ik_plot, = self._i_axes.plot([], [], label='K%s' % (suffix))
        self._plot_dict['ik'].append(self._ik_plot)
        # self._i_axes.legend()
        # State plots
        self._state_plot, = self._statePlotAxes.plot([], [],
                                                     label='state%s' %
                                                     (suffix))
        self._plot_dict['state'].append(self._state_plot)
        self._m_plot, = self._activationParamAxes.plot([], [],
                                                       label='m%s' % (suffix))
        self._h_plot, = self._activationParamAxes.plot([], [],
                                                       label='h%s' % (suffix))
        self._n_plot, = self._activationParamAxes.plot([], [],
                                                       label='n%s' % (suffix))
        self._plot_dict['m'].append(self._m_plot)
        self._plot_dict['h'].append(self._h_plot)
        self._plot_dict['n'].append(self._n_plot)
        if self._showLegendAction.isChecked():
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                axis.legend()

    def _updateAllPlots(self):
        self._updatePlots()
        self._updateStatePlot()

    def _updatePlots(self):
        if len(self.squid_setup.vm_table.vector) <= 0:
            return
        vm = numpy.asarray(self.squid_setup.vm_table.vector)
        cmd = numpy.asarray(self.squid_setup.cmd_table.vector)
        ik = numpy.asarray(self.squid_setup.ik_table.vector)
        ina = numpy.asarray(self.squid_setup.ina_table.vector)
        iclamp = numpy.asarray(self.squid_setup.iclamp_table.vector)
        vclamp = numpy.asarray(self.squid_setup.vclamp_table.vector)
        gk = numpy.asarray(self.squid_setup.gk_table.vector)
        gna = numpy.asarray(self.squid_setup.gna_table.vector)
        time_series = numpy.linspace(0, self._plotdt * len(vm), len(vm))
        self._vm_plot.set_data(time_series, vm)
        time_series = numpy.linspace(0, self._plotdt * len(cmd), len(cmd))
        self._command_plot.set_data(time_series, cmd)
        time_series = numpy.linspace(0, self._plotdt * len(ik), len(ik))
        self._ik_plot.set_data(time_series, ik)
        time_series = numpy.linspace(0, self._plotdt * len(ina), len(ina))
        self._ina_plot.set_data(time_series, ina)
        time_series = numpy.linspace(0, self._plotdt * len(iclamp),
                                     len(iclamp))
        self._iclamp_plot.set_data(time_series, iclamp)
        time_series = numpy.linspace(0, self._plotdt * len(vclamp),
                                     len(vclamp))
        self._vclamp_plot.set_data(time_series, vclamp)
        time_series = numpy.linspace(0, self._plotdt * len(gk), len(gk))
        self._gk_plot.set_data(time_series, gk)
        time_series = numpy.linspace(0, self._plotdt * len(gna), len(gna))
        self._gna_plot.set_data(time_series, gna)
        # self._vm_axes.margins(y=0.1)
        # self._g_axes.margin(y=0.1)
        # self._im_axes.margins(y=0.1)
        # self._i_axes.margins(y=0.1)
        if self._autoscaleAction.isChecked():
            for axis in self._plotFigure.axes:
                axis.relim()
                axis.margins(0.1, 0.1)
                axis.autoscale_view(tight=True)
        else:
            self._vm_axes.set_ylim(-20.0, 120.0)
            self._g_axes.set_ylim(0.0, 0.5)
            self._im_axes.set_ylim(-0.5, 0.5)
            self._i_axes.set_ylim(-10, 10)
        self._vm_axes.set_xlim(0.0, time_series[-1])
        self._g_axes.set_xlim(0.0, time_series[-1])
        self._im_axes.set_xlim(0.0, time_series[-1])
        self._i_axes.set_xlim(0.0, time_series[-1])
        self._plotCanvas.draw()

    def _updateStatePlot(self):
        if len(self.squid_setup.vm_table.vector) <= 0:
            return
        sx = str(self._stateplot_xvar_combo.currentText())
        sy = str(self._stateplot_yvar_combo.currentText())
        xdata = self.__get_stateplot_data(sx)
        ydata = self.__get_stateplot_data(sy)
        minlen = min(len(xdata), len(ydata))
        self._state_plot.set_data(xdata[:minlen], ydata[:minlen])
        self._statePlotAxes.set_xlabel(sx)
        self._statePlotAxes.set_ylabel(sy)
        if sx == 'V':
            self._statePlotAxes.set_xlim(-20, 120)
        else:
            self._statePlotAxes.set_xlim(0, 1)
        if sy == 'V':
            self._statePlotAxes.set_ylim(-20, 120)
        else:
            self._statePlotAxes.set_ylim(0, 1)
        self._activationParamAxes.set_xlim(0, self._runtime)
        m = self.__get_stateplot_data('m')
        n = self.__get_stateplot_data('n')
        h = self.__get_stateplot_data('h')
        time_series = numpy.linspace(0, self._plotdt * len(m), len(m))
        self._m_plot.set_data(time_series, m)
        time_series = numpy.linspace(0, self._plotdt * len(h), len(h))
        self._h_plot.set_data(time_series, h)
        time_series = numpy.linspace(0, self._plotdt * len(n), len(n))
        self._n_plot.set_data(time_series, n)
        if self._autoscaleAction.isChecked():
            for axis in self._statePlotFigure.axes:
                axis.relim()
                axis.set_autoscale_on(True)
                axis.autoscale_view(True)
        self._statePlotCanvas.draw()

    def _runSlot(self):
        if moose.isRunning():
            print 'Stopping simulation in progress ...'
            moose.stop()
        self._runtime = self.getFloatInput(self._runTimeEdit,
                                           self._runTimeLabel.text())
        self._overlayPlots(self._overlayAction.isChecked())
        self._simdt = self.getFloatInput(self._simTimeStepEdit,
                                         self._simTimeStepLabel.text())
        clampMode = None
        singlePulse = True
        if self._electronicsTab.currentWidget() == self._vClampCtrlBox:
            clampMode = 'vclamp'
            baseLevel = self.getFloatInput(self._holdingVEdit,
                                           self._holdingVLabel.text())
            firstDelay = self.getFloatInput(self._holdingTimeEdit,
                                            self._holdingTimeLabel.text())
            firstWidth = self.getFloatInput(self._prePulseTimeEdit,
                                            self._prePulseTimeLabel.text())
            firstLevel = self.getFloatInput(self._prePulseVEdit,
                                            self._prePulseVLabel.text())
            secondDelay = firstWidth
            secondWidth = self.getFloatInput(self._clampTimeEdit,
                                             self._clampTimeLabel.text())
            secondLevel = self.getFloatInput(self._clampVEdit,
                                             self._clampVLabel.text())
            if not self._autoscaleAction.isChecked():
                self._im_axes.set_ylim(-10.0, 10.0)
        else:
            clampMode = 'iclamp'
            baseLevel = self.getFloatInput(self._baseCurrentEdit,
                                           self._baseCurrentLabel.text())
            firstDelay = self.getFloatInput(self._firstDelayEdit,
                                            self._firstDelayLabel.text())
            firstWidth = self.getFloatInput(self._firstPulseWidthEdit,
                                            self._firstPulseWidthLabel.text())
            firstLevel = self.getFloatInput(self._firstPulseEdit,
                                            self._firstPulseLabel.text())
            secondDelay = self.getFloatInput(self._secondDelayEdit,
                                             self._secondDelayLabel.text())
            secondLevel = self.getFloatInput(self._secondPulseEdit,
                                             self._secondPulseLabel.text())
            secondWidth = self.getFloatInput(
                self._secondPulseWidthEdit, self._secondPulseWidthLabel.text())
            singlePulse = (self._pulseMode.currentIndex() == 0)
            if not self._autoscaleAction.isChecked():
                self._im_axes.set_ylim(-0.4, 0.4)
        self.squid_setup.clamp_ckt.configure_pulses(baseLevel=baseLevel,
                                                    firstDelay=firstDelay,
                                                    firstWidth=firstWidth,
                                                    firstLevel=firstLevel,
                                                    secondDelay=secondDelay,
                                                    secondWidth=secondWidth,
                                                    secondLevel=secondLevel,
                                                    singlePulse=singlePulse)
        if self._kConductanceToggle.isChecked():
            self.squid_setup.squid_axon.specific_gK = 0.0
        else:
            self.squid_setup.squid_axon.specific_gK = SquidAxon.defaults[
                'specific_gK']
        if self._naConductanceToggle.isChecked():
            self.squid_setup.squid_axon.specific_gNa = 0.0
        else:
            self.squid_setup.squid_axon.specific_gNa = SquidAxon.defaults[
                'specific_gNa']
        self.squid_setup.squid_axon.celsius = self.getFloatInput(
            self._temperatureEdit, self._temperatureLabel.text())
        self.squid_setup.squid_axon.K_out = self.getFloatInput(
            self._kOutEdit, self._kOutLabel.text())
        self.squid_setup.squid_axon.Na_out = self.getFloatInput(
            self._naOutEdit, self._naOutLabel.text())
        self.squid_setup.squid_axon.K_in = self.getFloatInput(
            self._kInEdit, self._kInLabel.text())
        self.squid_setup.squid_axon.Na_in = self.getFloatInput(
            self._naInEdit, self._naInLabel.text())
        self.squid_setup.squid_axon.updateEk()
        self.squid_setup.schedule(self._simdt, self._plotdt, clampMode)
        # The following line is for use with Qthread
        self.squid_setup.run(self._runtime)
        self._updateAllPlots()

    def _toggleDocking(self, on):
        self._channelControlDock.setFloating(on)
        self._electronicsDock.setFloating(on)
        self._runControlDock.setFloating(on)

    def _restoreDocks(self):
        self._channelControlDock.setVisible(True)
        self._electronicsDock.setVisible(True)
        self._runControlDock.setVisible(True)

    def _initActions(self):
        self._runAction = QtGui.QAction(self.tr('Run'), self)
        self._runAction.setShortcut(self.tr('F5'))
        self._runAction.setToolTip('Run simulation (F5)')
        self.connect(self._runAction, QtCore.SIGNAL('triggered()'),
                     self._runSlot)
        self._resetToDefaultsAction = QtGui.QAction(
            self.tr('Restore defaults'), self)
        self._resetToDefaultsAction.setToolTip(
            'Reset all settings to their default values')
        self.connect(self._resetToDefaultsAction, QtCore.SIGNAL('triggered()'),
                     self._useDefaults)
        self._showLegendAction = QtGui.QAction(self.tr('Display legend'), self)
        self._showLegendAction.setCheckable(True)
        self.connect(self._showLegendAction, QtCore.SIGNAL('toggled(bool)'),
                     self._showLegend)
        self._showStatePlotAction = QtGui.QAction(self.tr('State plot'), self)
        self._showStatePlotAction.setCheckable(True)
        self._showStatePlotAction.setChecked(False)
        self.connect(self._showStatePlotAction, QtCore.SIGNAL('toggled(bool)'),
                     self._statePlotWidget.setVisible)
        self._autoscaleAction = QtGui.QAction(self.tr('Auto-scale plots'),
                                              self)
        self._autoscaleAction.setCheckable(True)
        self._autoscaleAction.setChecked(False)
        self.connect(self._autoscaleAction, QtCore.SIGNAL('toggled(bool)'),
                     self._autoscale)
        self._overlayAction = QtGui.QAction('Overlay plots', self)
        self._overlayAction.setCheckable(True)
        self._overlayAction.setChecked(False)
        self._dockAction = QtGui.QAction('Undock all', self)
        self._dockAction.setCheckable(True)
        self._dockAction.setChecked(False)
        self.connect(self._dockAction, QtCore.SIGNAL('toggled(bool)'),
                     self._toggleDocking)
        self._restoreDocksAction = QtGui.QAction('Show all', self)
        self.connect(self._restoreDocksAction, QtCore.SIGNAL('triggered()'),
                     self._restoreDocks)
        self._quitAction = QtGui.QAction(self.tr('&Quit'), self)
        self._quitAction.setShortcut(self.tr('Ctrl+Q'))
        self.connect(self._quitAction, QtCore.SIGNAL('triggered()'),
                     QtGui.qApp.closeAllWindows)

    def _createRunToolBar(self):
        self._simToolBar = self.addToolBar(self.tr('Simulation control'))
        self._simToolBar.addAction(self._quitAction)
        self._simToolBar.addAction(self._runAction)
        self._simToolBar.addAction(self._resetToDefaultsAction)
        self._simToolBar.addAction(self._dockAction)
        self._simToolBar.addAction(self._restoreDocksAction)

    def _createPlotToolBar(self):
        self._plotToolBar = self.addToolBar(self.tr('Plotting control'))
        self._plotToolBar.addAction(self._showLegendAction)
        self._plotToolBar.addAction(self._autoscaleAction)
        self._plotToolBar.addAction(self._overlayAction)
        self._plotToolBar.addAction(self._showStatePlotAction)
        self._plotToolBar.addAction(self._helpAction)
        self._plotToolBar.addAction(self._helpBiophysicsAction)

    def _showLegend(self, on):
        if on:
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                axis.legend().set_visible(True)
        else:
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                axis.legend().set_visible(False)
        self._plotCanvas.draw()
        self._statePlotCanvas.draw()

    def _autoscale(self, on):
        if on:
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                axis.relim()
                axis.set_autoscale_on(True)
                axis.autoscale_view(True)
        else:
            for axis in self._plotFigure.axes:
                axis.set_autoscale_on(False)
            self._vm_axes.set_ylim(-20.0, 120.0)
            self._g_axes.set_ylim(0.0, 0.5)
            self._im_axes.set_ylim(-0.5, 0.5)
            self._i_axes.set_ylim(-10, 10)
        self._plotCanvas.draw()
        self._statePlotCanvas.draw()

    def _useDefaults(self):
        self._runTimeEdit.setText('%g' % (self.defaults['runtime']))
        self._simTimeStepEdit.setText('%g' % (self.defaults['simdt']))
        self._overlayAction.setChecked(False)
        self._naConductanceToggle.setChecked(False)
        self._kConductanceToggle.setChecked(False)
        self._kOutEdit.setText('%g' % (SquidGui.defaults['K_out']))
        self._naOutEdit.setText('%g' % (SquidGui.defaults['Na_out']))
        self._kInEdit.setText('%g' % (SquidGui.defaults['K_in']))
        self._naInEdit.setText('%g' % (SquidGui.defaults['Na_in']))
        self._temperatureEdit.setText(
            '%g' % (SquidGui.defaults['temperature'] - CELSIUS_TO_KELVIN))
        self._holdingVEdit.setText('%g' %
                                   (SquidGui.defaults['vclamp.holdingV']))
        self._holdingTimeEdit.setText('%g' %
                                      (SquidGui.defaults['vclamp.holdingT']))
        self._prePulseVEdit.setText('%g' %
                                    (SquidGui.defaults['vclamp.prepulseV']))
        self._prePulseTimeEdit.setText('%g' %
                                       (SquidGui.defaults['vclamp.prepulseT']))
        self._clampVEdit.setText('%g' % (SquidGui.defaults['vclamp.clampV']))
        self._clampTimeEdit.setText('%g' %
                                    (SquidGui.defaults['vclamp.clampT']))
        self._baseCurrentEdit.setText('%g' %
                                      (SquidGui.defaults['iclamp.baseI']))
        self._firstPulseEdit.setText('%g' %
                                     (SquidGui.defaults['iclamp.firstI']))
        self._firstDelayEdit.setText('%g' %
                                     (SquidGui.defaults['iclamp.firstD']))
        self._firstPulseWidthEdit.setText('%g' %
                                          (SquidGui.defaults['iclamp.firstT']))
        self._secondPulseEdit.setText('%g' %
                                      (SquidGui.defaults['iclamp.secondI']))
        self._secondDelayEdit.setText('%g' %
                                      (SquidGui.defaults['iclamp.secondD']))
        self._secondPulseWidthEdit.setText(
            '%g' % (SquidGui.defaults['iclamp.secondT']))
        self._pulseMode.setCurrentIndex(0)

    def _onScroll(self, event):
        if event.inaxes is None:
            return
        axes = event.inaxes
        zoom = 0.0
        if event.button == 'up':
            zoom = -1.0
        elif event.button == 'down':
            zoom = 1.0
        if zoom != 0.0:
            self._plotNavigator.push_current()
            axes.get_xaxis().zoom(zoom)
            axes.get_yaxis().zoom(zoom)
        self._plotCanvas.draw()

    def closeEvent(self, event):
        QtGui.qApp.closeAllWindows()

    def _showBioPhysicsHelp(self):
        self._createHelpMessage()
        self._helpMessageText.setText(
            '<html><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p></html>' %
            (tooltip_Nernst, tooltip_Erest, tooltip_KChan, tooltip_NaChan,
             tooltip_Im))
        self._helpWindow.setVisible(True)

    def _showRunningHelp(self):
        self._createHelpMessage()
        self._helpMessageText.setSource(QtCore.QUrl(self._helpBaseURL))
        self._helpWindow.setVisible(True)

    def _createHelpMessage(self):
        if hasattr(self, '_helpWindow'):
            return
        self._helpWindow = QtGui.QWidget()
        self._helpWindow.setWindowFlags(QtCore.Qt.Window)
        layout = QtGui.QVBoxLayout()
        self._helpWindow.setLayout(layout)
        self._helpMessageArea = QtGui.QScrollArea()
        self._helpMessageText = QtGui.QTextBrowser()
        self._helpMessageText.setOpenExternalLinks(True)
        self._helpMessageArea.setWidget(self._helpMessageText)
        layout.addWidget(self._helpMessageText)
        self._squidGuiPath = os.path.dirname(os.path.abspath(__file__))
        self._helpBaseURL = os.path.join(self._squidGuiPath, 'help.html')
        self._helpMessageText.setSource(QtCore.QUrl(self._helpBaseURL))
        self._helpMessageText.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                            QtGui.QSizePolicy.Expanding)
        self._helpMessageArea.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                            QtGui.QSizePolicy.Expanding)
        self._helpMessageText.setMinimumSize(800, 600)
        self._closeHelpAction = QtGui.QAction('Close', self)
        self.connect(self._closeHelpAction, QtCore.SIGNAL('triggered()'),
                     self._helpWindow.close)
        # Setting the close event so that the ``Help`` button is
        # unchecked when the help window is closed
        self._helpWindow.closeEvent = lambda event: self._helpAction.setChecked(
            False)
        self._helpTOCAction = QtGui.QAction('Help running demo', self)
        self.connect(self._helpTOCAction, QtCore.SIGNAL('triggered()'),
                     self._jumpToHelpTOC)
        # This panel is for putting two buttons using horizontal
        # layout
        panel = QtGui.QFrame()
        panel.setFrameStyle(QtGui.QFrame.StyledPanel + QtGui.QFrame.Raised)
        layout.addWidget(panel)
        layout = QtGui.QHBoxLayout()
        panel.setLayout(layout)
        self._helpAction = QtGui.QAction('Help running', self)
        self.connect(self._helpAction, QtCore.SIGNAL('triggered()'),
                     self._showRunningHelp)
        self._helpBiophysicsAction = QtGui.QAction('Help biophysics', self)
        self.connect(self._helpBiophysicsAction, QtCore.SIGNAL('triggered()'),
                     self._showBioPhysicsHelp)
        self._helpTOCButton = QtGui.QToolButton()
        self._helpTOCButton.setDefaultAction(self._helpTOCAction)
        self._helpBiophysicsButton = QtGui.QToolButton()
        self._helpBiophysicsButton.setDefaultAction(self._helpBiophysicsAction)
        layout.addWidget(self._helpTOCButton)
        layout.addWidget(self._helpBiophysicsButton)
        self._closeHelpButton = QtGui.QToolButton()
        self._closeHelpButton.setDefaultAction(self._closeHelpAction)
        layout.addWidget(self._closeHelpButton)

    def _jumpToHelpTOC(self):
        self._helpMessageText.setSource(QtCore.QUrl(self._helpBaseURL))
Example #41
0
File: ohlc.py Project: lite/deone
class OHLCWidget(Canvas):
    def __init__(self, parent=None):
        from matplotlib import rcParams
        rcParams['font.size'] = 6

        self.figure = Figure(facecolor='w', edgecolor='w')
        self.figure.subplots_adjust(left=0.1, right=0.9, wspace=0.6)

        Canvas.__init__(self, self.figure)
        self.setParent(parent)
        self.figure.canvas.mpl_connect('motion_notify_event', self.onmove)

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

    def sizeHint(self):
        w, h = self.get_width_height()
        return QtCore.QSize(w, h)

    def minimumSizeHint(self):
        return QtCore.QSize(10, 10)

    def onmove(self, event):
        if event.xdata == None or event.inaxes == self.info_axes:
            return
        #print(event.x, event.xdata, event.inaxes)
        ind = int(round(event.xdata))
        self.info(ind)

    def info(self, ind):
        print("call info", ind)
        if ind >= len(self.rows) or ind < 0: return ''
        row = self.rows[ind]
        if row == None:
            return
        print(row)
        #today = datetime.datetime(1899,12,30)+datetime.timedelta(days=float(row[0]))
        y, m, d = row[0].split('-')
        today = datetime.datetime(int(y), int(m), int(d))
        open = float(row[1])
        high = float(row[2])
        low = float(row[3])
        close = float(row[4])
        volume = int(float(row[5]))
        print(today, open, high, low, close, volume)

        self.info_axes.clear()
        self.info_axes.text(0.1, 0.95, 'Date')
        self.info_axes.text(0.15, 0.93, today.strftime("%Y%m%d"), color='b')
        self.info_axes.text(0.1, 0.90, 'Open')
        self.info_axes.text(0.15, 0.88, open, color='b')
        self.info_axes.text(0.1, 0.85, 'High')
        self.info_axes.text(0.15, 0.83, high, color='b')
        self.info_axes.text(0.1, 0.80, 'Low')
        self.info_axes.text(0.15, 0.78, low, color='b')
        self.info_axes.text(0.1, 0.75, 'Close')
        self.info_axes.text(0.15, 0.73, close, color='b')
        self.info_axes.text(0.1, 0.70, 'Volume')
        self.info_axes.text(0.15, 0.68, volume, color='b')
        self.info_axes.set_xticklabels([])
        self.info_axes.set_yticklabels([])

        self.figure.canvas.draw()

    def query(self, sql, parameters=None):
        self.figure.clear()

        self.vol_axes = self.figure.add_axes([0.06, 0.01, 0.87, 0.24],
                                             axisbg='#cccccc',
                                             autoscale_on=True)
        self.ohlc_axes = self.figure.add_axes([0.06, 0.25, 0.87, 0.74],
                                              axisbg='#cccccc',
                                              autoscale_on=True)
        self.info_axes = self.figure.add_axes([0.93, 0.01, 0.06, 0.98],
                                              axisbg='#cccccc',
                                              autoscale_on=True)

        # select data from sqlite3 db
        deone_db = r'data/DEONE.db'
        con = sqlite3.connect(deone_db)
        con.text_factory = str
        cur = con.cursor()
        #t = u'深发展A'.encode('utf-8')
        #cur.execute(u'select * from StockHist where 股票名称=?'.encode('utf-8'), (t,))
        #cur.execute('select * from StockHist')
        cur.execute(sql, parameters)

        dates = []
        ind = 0
        self.rows = []
        for ind in xrange(100):
            row = cur.fetchone()
            if row == None:
                break
            #print(row)
            self.rows += [row]

            #today = datetime.datetime(1899,12,30)+datetime.timedelta(days=float(row[0]))
            y, m, d = row[0].split('-')
            today = datetime.datetime(int(y), int(m), int(d))
            dates += [today]
            open = float(row[1])
            high = float(row[2])
            low = float(row[3])
            close = float(row[4])
            volume = int(float(row[5]))
            #print(ind, today, open, high, low, close, volume)

            if close > open:
                col = "r"
            elif close < open:
                col = "g"
            else:
                col = "w"
                self.ohlc_axes.hlines(open, ind - 0.3, ind + 0.3, colors='w')

            self.ohlc_axes.bar(ind,
                               close - open,
                               0.6,
                               open,
                               color=col,
                               align='center')
            self.ohlc_axes.vlines(ind, low, high, color=col)
            self.vol_axes.bar(ind, volume, 0.6, color=col, align='center')

        con.close()

        formatter = MyFormatter(dates)
        self.ohlc_axes.xaxis.set_major_formatter(formatter)
        self.vol_axes.xaxis.set_major_formatter(formatter)

        self.ohlc_axes.set_xlim(-0.5, ind + 1.5)
        self.ohlc_axes.grid(True)
        self.vol_axes.set_xlim(-0.5, ind + 1.5)
        self.vol_axes.grid(True)

        self.vol_axes.set_xticklabels([])
        self.info_axes.set_xticklabels([])
        self.info_axes.set_yticklabels([])

        self.figure.autofmt_xdate()

        self.info(ind - 1)
Example #42
0
class SolverWidget(QtGui.QWidget):
    """ Widget used to run and monitor the Ember solver """
    def __init__(self, conf, *args, **kwargs):
        QtGui.QWidget.__init__(self)

        self.conf = conf
        self.setLayout(QtGui.QVBoxLayout())

        # Buttons
        self.startButton = QtGui.QPushButton('Start')
        self.stopButton = QtGui.QPushButton('Stop')
        self.resetButton = QtGui.QPushButton('Reset')
        self.buttons = QtGui.QWidget()
        self.buttons.setLayout(QtGui.QHBoxLayout())
        self.buttons.layout().addWidget(self.startButton)
        self.buttons.layout().addWidget(self.stopButton)
        self.buttons.layout().addWidget(self.resetButton)
        self.layout().addWidget(self.buttons)

        self.startButton.pressed.connect(self.run)
        self.stopButton.pressed.connect(self.stop)
        self.resetButton.pressed.connect(self.reset)

        # Progress Bar
        self.progressBar = QtGui.QProgressBar()
        self.layout().addWidget(self.progressBar)
        self.progressBar.setRange(0, 1000)
        self.progressBar.setValue(0)

        # Graphs
        self.graphContainer = QtGui.QWidget()
        self.graphContainer.setLayout(QtGui.QHBoxLayout())
        self.layout().addWidget(self.graphContainer)

        self.fig = Figure(figsize=(600,400), dpi=72)
        self.fig.subplots_adjust(0.09, 0.08, 0.93, 0.96, wspace=0.3)
        self.ax1 = self.fig.add_subplot(1,2,1)
        self.ax1.set_xlabel('time [ms]')
        self.ax1.set_ylabel('Consumption Speed, $S_c$ [cm/s]')
        self.Sc_timeseries = self.ax1.plot([0],[0], lw=2)[0]

        self.ax2a = self.fig.add_subplot(1,2,2)
        self.ax2b = self.ax2a.twinx()
        self.ax2a.set_xlabel('flame coordinate [mm]')
        self.ax2a.set_ylabel('Temperature [K]')
        self.ax2b.set_ylabel('Heat Release Rate [MW/m$^3$]')

        self.T_profile = self.ax2a.plot([0],[0], 'b', lw=2)[0]
        self.hrr_profile = self.ax2b.plot([0],[0], 'r', lw=2)[0]

        self.canvas = FigureCanvas(self.fig)
        self.graphContainer.layout().addWidget(self.canvas)
        bgcolor = self.palette().color(QtGui.QPalette.Window)
        self.fig.set_facecolor((bgcolor.redF(), bgcolor.greenF(), bgcolor.blueF()))
        #self.fig.patch.set_alpha(0.1)

        # internals
        self.solver = None
        self.solverThread = None
        self.updateTimer = QtCore.QTimer()
        self.updateTimer.setInterval(0.5)
        self.updateTimer.timeout.connect(self.updateStatus)
        self.running = False
        self.updateButtons()

    def run(self):
        if self.solverThread is not None and self.solverThread.is_alive():
            return

        if self.solver is None:
            self.conf.validate()
            self.solver = _ember.FlameSolver(self.conf)
            self.solver.initialize()

        self.solverThread = SolverThread(solver=self.solver,
                                         conf=self.conf)
        self.solverThread.start()
        self.updateTimer.start()
        self.running = True
        self.updateButtons()

    def stop(self):
        if self.solverThread:
            self.solverThread.stop()
            self.updateTimer.stop()
        self.running = False
        self.startButton.setText('Resume')
        self.updateButtons()

    def reset(self):
        self.progressBar.setValue(0)
        self.T_profile.set_data([0], [0])
        self.hrr_profile.set_data([0], [0])
        self.Sc_timeseries.set_data([0], [0])
        self.canvas.draw()
        self.solver = None
        self.startButton.setText('Start')
        self.updateButtons()

    def updateButtons(self):
        running = self.running and self.solverThread is not None and self.solverThread.is_alive()
        self.startButton.setEnabled(not running)
        self.stopButton.setEnabled(running)
        self.resetButton.setEnabled(self.solver is not None and not running)

    def updateStatus(self):
        if not self.solver:
            return

        if not self.solverThread.is_alive():
            self.running = False
            self.updateTimer.stop()
            self.updateButtons()

        if self.solver.progress > 0:
            self.progressBar.setValue(1000 * self.solver.progress)
        with self.solver.lock:
            t = np.array(self.solver.timeseriesWriter.t)
            Sc = np.array(self.solver.timeseriesWriter.Sc)

            self.T_profile.set_data(self.solver.x * 1000,
                                    self.solver.T)
            self.hrr_profile.set_data(self.solver.x * 1000,
                                      self.solver.qDot / 1e6)
        self.Sc_timeseries.set_data(1000 * t, Sc * 100)

        for ax in (self.ax1, self.ax2a, self.ax2b):
            ax.relim()
            ax.autoscale_view(False, True, True)
        self.canvas.draw()
Example #43
0
class Plot():
    '''
    A container for holding variables and methods needed for 
    animating the interactive plot, is a child of a PlotPage object
    '''
    def __init__(self, parent, seconds, scale, num):
        self.parent = parent
        self.scale = scale
        self.scale['command'] = self.updatePos

        self.scale_pos = 0
        self.num = num  # Which number servo, for plot title
        self.length = 0

        self.click = False  # Node follows mouse only when clicked
        self.point_index = None  # Track which node has been selected

        # For keeping values within range of servo degrees
        self.upper_limit = 179
        self.lower_limit = 0
        self.limit_range = lambda n: max(min(self.upper_limit, n), self.
                                         lower_limit)

        # Initial Graph -----
        self.fig = Figure(figsize=(10, 5), dpi=100)
        self.fig.subplots_adjust(bottom=0.18)
        self.ax = self.fig.add_subplot(111)

        self.xs = [i for i in range(self.length)]
        self.ys = [self.lower_limit for i in self.xs]

        self.setPlot()
        self.drawPlot()

    def updatePos(self, *args):
        '''Read the scale to move plot viewing area,
           args are a tuple of scale value automatically passed in'''
        self.scale_pos = self.scale.get()
        self.update()

    def setPlot(self):
        '''Elements of the plot which do not need to be redrawn every update '''

        self.ax.set_ylim([-10, 190])
        self.ax.set_yticks(range(0, 190, 20))

        self.ax.grid(alpha=.5)
        self.ax.set_xlabel('Seconds')
        self.ax.set_ylabel('Degree of Motion',
                           fontname='BPG Courier GPL&GNU',
                           fontsize=14)

    def clearPlotLines(self):
        '''Remove plotted lines so they can be redrawn'''

        self.line.remove()
        self.nodes.remove()
        self.upper.remove()
        self.lower.remove()

    def drawPlot(self):
        '''Draw the actual plot'''

        self.ax.set_title(label=self.parent.name, fontsize=18, y=1.03)

        x_window = 20  # Num of ticks in 'viewport'
        pos = round(self.scale_pos *
                    2)  # scale_pos is in seconds, pos is in ticks
        pos = max(pos, 0)

        # Confine y-values to within upper and lower limits
        self.ys = [self.limit_range(node) for node in self.ys]

        # Only 'x_window' of plot is viewable
        self.ax.set_xlim([pos - .5, pos + x_window + .5])
        self.ax.set_xticks([i for i in range(pos, pos + x_window + 1)])
        self.ax.set_xticklabels([i / 2 for i in self.ax.get_xticks()])
        for tick in self.ax.get_xticklabels():
            tick.set_rotation(45)

        #~ # Plot upper and lower limits
        self.upper, = self.ax.plot(self.xs,
                                   [self.upper_limit for i in self.xs],
                                   'k--',
                                   alpha=.6,
                                   linewidth=1)
        self.lower, = self.ax.plot(self.xs,
                                   [self.lower_limit for i in self.xs],
                                   'k--',
                                   alpha=.6,
                                   linewidth=1)

        # Line
        self.line, = self.ax.plot(self.xs,
                                  self.ys,
                                  color='orange',
                                  markersize=10)

        # Clickable nodes
        self.nodes, = self.ax.plot(self.xs,
                                   self.ys,
                                   'k.',
                                   markersize=10,
                                   picker=5.0)

    def onPress(self, event):
        '''Which node has been clicked'''

        point = event.artist
        index = event.ind

        self.point_index = int(index[0])

        if not event.mouseevent.dblclick:
            self.click = True

        else:
            # If node is double-clicked open popup to change value
            sleep(.1)  # Short delay to end all events on mainloop
            ValuePopup(self, self.point_index)

    def onMotion(self, event):
        if self.click and event.inaxes:
            # Point follows mouse on y-axis
            self.ys[self.point_index] = self.limit_range(event.ydata)
            # Round to nearest whole degree
            self.ys[self.point_index] = int(round(self.ys[self.point_index]))

            self.update()

    def onRelease(self, event):
        if self.point_index is not None:
            self.click = False
            self.point_index = None

    def update(self):
        '''Re-draw plot after moving a point'''

        self.clearPlotLines()

        self.drawPlot()
        self.fig.canvas.draw()
Example #44
0
class GraphStyleDialog(wx.Dialog):
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Dialog.__init__(self, *args, **kwds)
        self.list_modes = wx.ListBox(self, -1, choices=[])
        self.sizer_list_modes_staticbox = wx.StaticBox(
            self, -1, _("List of graph style modes"))
        self.sizer_preview_staticbox = wx.StaticBox(self, -1, _("Preview"))
        self.label_bg_color = wx.StaticText(self, -1,
                                            _("Background color") + ": ")
        self.button_bg_color = wx.ColourPickerCtrl(self, -1, '#FFFFFF')
        self.label_grid_color = wx.StaticText(self, -1, _("Grid color") + ": ")
        self.button_grid_color = wx.ColourPickerCtrl(self, -1, '#666666')
        self.label_line_color = wx.StaticText(self, -1, _("Line color") + ": ")
        self.button_line_color = wx.ColourPickerCtrl(self, -1, '#0000FF')
        self.label_line_style = wx.StaticText(self, -1, _("Line style") + ": ")
        self.combo_line_style = wx.ComboBox(
            self,
            -1,
            choices=[_("Solid"),
                     _("Dashed"),
                     _("Dashdot"),
                     _("Dotted")],
            style=wx.CB_DROPDOWN | wx.CB_READONLY)
        self.label_line_width = wx.StaticText(self, -1, _("Line width") + ": ")
        self.spin_line_width = wx.SpinCtrl(self, -1, "", min=1, max=10)
        self.sizer_customize_staticbox = wx.StaticBox(self, -1, _("Customize"))
        self.button_apply_style = wx.Button(self, -1, _("Apply graph style"))
        self.first_time = True
        self.is_customized = False

        self.dpi = 70
        self.fig = Figure((3.0, 3.0), dpi=self.dpi)
        self.fig.subplots_adjust(
            left=0.05, right=0.945, top=0.95,
            bottom=0.06)  # Adjust the chart to occupy as much space the canvas
        self.axes = self.fig.add_subplot(111)
        self.plot_data = self.axes.plot([])[0]
        example_data_x = numpy.linspace(0, 10)
        example_data_y = numpy.power(2, example_data_x) / 10
        self.plot_data.set_xdata(example_data_x)
        self.plot_data.set_ydata(example_data_y)
        self.axes.set_xbound(lower=5, upper=10)
        self.axes.set_ybound(lower=1, upper=90)

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

        self.__insert_style_modes()
        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_LISTBOX, self.on_select_mode, self.list_modes)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.on_dclick_list_modes,
                  self.list_modes)
        self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_change_bg_color,
                  self.button_bg_color)
        self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_change_grid_color,
                  self.button_grid_color)
        self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_change_line_color,
                  self.button_line_color)
        self.Bind(wx.EVT_COMBOBOX, self.on_change_line_style,
                  self.combo_line_style)
        self.Bind(wx.EVT_SPINCTRL, self.on_change_line_width,
                  self.spin_line_width)
        self.Bind(wx.EVT_BUTTON, self.on_apply_style, self.button_apply_style)

    def __set_properties(self):
        self.SetTitle(_("Graph style configuration"))
        self.SetSize((700, 530))
        self.list_modes.SetSelection(0)
        self.combo_line_style.SetSelection(0)
        self.button_apply_style.SetMinSize((230, 37))
        self.__set_colors('#FFFFFF', '#666666', '#0000FF', 0, 1)

    def __do_layout(self):
        separator = wx.BoxSizer(wx.VERTICAL)
        sizer_div = wx.BoxSizer(wx.HORIZONTAL)
        sizer_subdiv = wx.BoxSizer(wx.VERTICAL)
        self.sizer_customize_staticbox.Lower()
        sizer_customize = wx.StaticBoxSizer(self.sizer_customize_staticbox,
                                            wx.HORIZONTAL)
        grid_sizer_customize = wx.FlexGridSizer(5, 2, 5, 0)
        self.sizer_preview_staticbox.Lower()
        sizer_preview = wx.StaticBoxSizer(self.sizer_preview_staticbox,
                                          wx.HORIZONTAL)
        self.sizer_list_modes_staticbox.Lower()
        sizer_list_modes = wx.StaticBoxSizer(self.sizer_list_modes_staticbox,
                                             wx.HORIZONTAL)
        sizer_list_modes.Add(self.list_modes, 1, wx.ALL | wx.EXPAND, 5)
        sizer_div.Add(sizer_list_modes, 3, wx.ALL | wx.EXPAND, 5)
        sizer_preview.Add(self.canvas, 1, wx.EXPAND, 0)
        sizer_subdiv.Add(sizer_preview, 1, wx.ALL | wx.EXPAND, 5)
        grid_sizer_customize.Add(self.label_bg_color, 0,
                                 wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_customize.Add(self.button_bg_color, 0, wx.EXPAND, 0)
        grid_sizer_customize.Add(self.label_grid_color, 0,
                                 wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_customize.Add(self.button_grid_color, 0, wx.EXPAND, 0)
        grid_sizer_customize.Add(self.label_line_color, 0,
                                 wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_customize.Add(self.button_line_color, 0, wx.EXPAND, 0)
        grid_sizer_customize.Add(self.label_line_style, 0,
                                 wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_customize.Add(self.combo_line_style, 0, wx.EXPAND, 0)
        grid_sizer_customize.Add(self.label_line_width, 0,
                                 wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_customize.Add(self.spin_line_width, 0, wx.EXPAND, 0)
        grid_sizer_customize.AddGrowableCol(1)
        sizer_customize.Add(grid_sizer_customize, 1, wx.ALL | wx.EXPAND, 5)
        sizer_subdiv.Add(sizer_customize, 0, wx.ALL | wx.EXPAND, 5)
        sizer_div.Add(sizer_subdiv, 4, wx.EXPAND, 0)
        separator.Add(sizer_div, 1, wx.EXPAND, 0)
        separator.Add(self.button_apply_style, 0,
                      wx.RIGHT | wx.BOTTOM | wx.ALIGN_RIGHT, 5)
        self.SetSizer(separator)
        self.Layout()

    def __insert_style_modes(self):
        # Format for adding new graphics style modes:
        # self.list_modes.Append(<Mode name>, ModeStyle(<bg color>, <grid color>, <line color>, <num line style>, <num line width>))

        self.list_modes.Append(
            _("Default"), ModeStyle('#FFFFFF', '#666666', '#0000FF', 0, 1))
        self.list_modes.Append(
            "Contrast", ModeStyle('#000000', '#FFFFFF', '#FFFFFF', 0, 1))
        self.list_modes.Append(
            "Simple", ModeStyle('#FFFFFF', '#000000', '#000000', 0, 1))
        self.list_modes.Append(
            "Hacker", ModeStyle('#000000', '#00FF00', '#00FF00', 0, 1))
        self.list_modes.Append(
            "Aqua", ModeStyle('#0E2581', '#FFFFFF', '#00EDF6', 0, 1))
        self.list_modes.Append(
            "Inferno", ModeStyle('#6B0000', '#FFFFFF', '#FF0000', 0, 1))
        self.list_modes.Append(
            "Tropical", ModeStyle('#00B829', '#006207', '#FFFF00', 1, 2))
        self.list_modes.Append(
            "Desert", ModeStyle('#A94000', '#FFC800', '#FFB612', 0, 1))
        self.list_modes.Append(
            "Night", ModeStyle('#000000', '#FFFF00', '#FFFF00', 3, 2))

    def __get_name_line_style(self, n):
        name = None
        if n == 0: name = "solid"
        elif n == 1: name = "dashed"
        elif n == 2: name = "dashdot"
        elif n == 3: name = "dotted"
        return name

    def __set_colors(self, bg_color, grid_color, line_color, line_style,
                     line_width):
        self.button_bg_color.SetColour(bg_color)
        self.button_grid_color.SetColour(grid_color)
        self.button_line_color.SetColour(line_color)
        self.combo_line_style.SetSelection(line_style)
        self.spin_line_width.SetValue(line_width)

        self.axes.set_axis_bgcolor(bg_color)
        self.axes.grid(True, color=grid_color)
        self.plot_data.set_color(line_color)
        self.plot_data.set_linestyle(self.__get_name_line_style(line_style))
        self.plot_data.set_linewidth(line_width)

        self.canvas.draw()

    def on_dclick_list_modes(self, event):
        style_conf = self.list_modes.GetClientData(
            self.list_modes.GetSelection())
        self.__set_colors(style_conf.bg_color, style_conf.grid_color,
                          style_conf.line_color, style_conf.line_style,
                          style_conf.line_width)
        self.EndModal(0)

    def on_select_mode(self, event):
        if self.first_time and self.is_customized:
            self.list_modes.SetSelection(wx.NOT_FOUND)
            self.first_time = False
        else:
            style_conf = self.list_modes.GetClientData(
                self.list_modes.GetSelection())
            self.__set_colors(style_conf.bg_color, style_conf.grid_color,
                              style_conf.line_color, style_conf.line_style,
                              style_conf.line_width)

    def on_change_bg_color(self, event):
        new_bg_color = GetColorString(self.button_bg_color.GetColour())
        self.axes.set_axis_bgcolor(new_bg_color)
        self.canvas.draw()
        self.list_modes.SetSelection(wx.NOT_FOUND)

    def on_change_grid_color(self, event):
        new_grid_color = GetColorString(self.button_grid_color.GetColour())
        self.axes.grid(True, color=new_grid_color)
        self.canvas.draw()
        self.list_modes.SetSelection(wx.NOT_FOUND)

    def on_change_line_color(self, event):
        new_line_color = GetColorString(self.button_line_color.GetColour())
        self.plot_data.set_color(new_line_color)
        self.canvas.draw()
        self.list_modes.SetSelection(wx.NOT_FOUND)

    def on_change_line_style(self, event):
        new_line_style = self.combo_line_style.GetSelection()
        self.plot_data.set_linestyle(
            self.__get_name_line_style(new_line_style))
        self.canvas.draw()
        self.list_modes.SetSelection(wx.NOT_FOUND)

    def on_change_line_width(self, event):
        new_line_width = self.spin_line_width.GetValue()
        self.plot_data.set_linewidth(new_line_width)
        self.canvas.draw()
        self.list_modes.SetSelection(wx.NOT_FOUND)

    def on_apply_style(self, event):
        self.EndModal(0)

    def GetModeName(self):
        name_mode = None
        if self.list_modes.GetSelection() == wx.NOT_FOUND:
            name_mode = _("Customized")
        elif self.list_modes.GetSelection() == 0:
            name_mode = self.list_modes.GetString(
                self.list_modes.GetSelection())
        else:
            name_mode = _("{0} mode").format(
                self.list_modes.GetString(self.list_modes.GetSelection()))
        return name_mode

    def GetBgColor(self):
        return GetColorString(self.button_bg_color.GetColour())

    def GetGridColor(self):
        return GetColorString(self.button_grid_color.GetColour())

    def GetLineColor(self):
        return GetColorString(self.button_line_color.GetColour())

    def GetLineStyle(self):
        return self.__get_name_line_style(self.combo_line_style.GetSelection())

    def GetLineWidth(self):
        return self.spin_line_width.GetValue()

    def GetModeNumber(self):
        return self.list_modes.GetSelection()

    def GetLineStyleNumber(self):
        return self.combo_line_style.GetSelection()

    def SetModeNumber(self, nr_mode):
        self.list_modes.SetSelection(nr_mode)

        # It is neccesary to work on OSX systems
        style_conf = self.list_modes.GetClientData(nr_mode)
        self.__set_colors(style_conf.bg_color, style_conf.grid_color,
                          style_conf.line_color, style_conf.line_style,
                          style_conf.line_width)

    def SetCustomizedMode(self, bg_color, grid_color, line_color, line_style,
                          line_width):
        self.is_customized = True
        self.__set_colors(bg_color, grid_color, line_color, line_style,
                          line_width)
        self.list_modes.SetSelection(wx.NOT_FOUND)
Example #45
0
                    weightlist[0][0] * -1 + weightlist[0][1] * test1_x1[item_te1] + weightlist[0][2] * test1_x2[item_te1]))
                t_test1_x2.append(sigmoid(
                    weightlist[1][0] * -1 + weightlist[1][1] * test1_x1[item_te1] + weightlist[1][2] * test1_x2[item_te1]))
            for item_te2 in range(len(test2_x1)):
                t_test2_x1.append(sigmoid(
                    weightlist[0][0] * -1 + weightlist[0][1] * test2_x1[item_te2] + weightlist[0][2] * test2_x2[item_te2]))
                t_test2_x2.append(sigmoid(
                    weightlist[1][0] * -1 + weightlist[1][1] * test2_x1[item_te2] + weightlist[1][2] * test2_x2[item_te2]))

    display_output_weight = tk.Label(
        window, width=35, height=2, text=weightlist[-1], fg='black', anchor='w', wraplength=250)
    display_output_weight.place(x=30, y=200)

    # draw
    f = Figure(figsize=(3, 6), dpi=150)
    f.subplots_adjust(left=0.25, right=0.95, top=0.90, bottom=0.1)
    f_plot = f.add_subplot(211)
    f_plot2 = f.add_subplot(212)
    f_plot.tick_params(labelsize=8)
    f_plot2.tick_params(labelsize=8)
    canvas = FigureCanvasTkAgg(f, window)
    canvas.get_tk_widget().place(x=300, y=0)

    # original
    f_plot.clear()
    legend_train1 = f_plot.scatter(
        train1_x1, train1_x2, c='r', marker='o', s=8)
    legend_train2 = f_plot.scatter(
        train2_x1, train2_x2, c='r', marker='x', s=8)
    if case == 1:
        if test_y[0] == 0:
Example #46
0
class graph_panel(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        self.previous_patterns = []
        self.history_size = 100
        self.hi_contrast = False
        self.build()

    def build(self):
        self.fig = Figure(dpi=110)
        #self.fig.set_facecolor('#d4d0c8')
        self.fig.set_facecolor('#888888')
        self.canvas = FigCanvas(self, -1, self.fig)
        self.Bind(wx.EVT_SIZE, self.sizeHandler)
        self.SetMinSize((400, 200))
        self.clear()
        self.draw()

    def sizeHandler(self, *args, **kwargs):
        ''' makes sure that the canvas is properly resized '''
        self.canvas.SetSize(self.GetSize())

    ########################

    def set_hi_contrast(self, event):
        ''' set the contrast '''
        self.hi_contrast = event.IsChecked()

    def clear(self):
        ''' called when the pattern changes '''
        self.need_data = True
        self.singles_curves = []
        self.coincidence_curves = []

    def add_counts(self, data):
        ''' add a set of counts '''
        new_singles = filter(lambda x: len(x[1]) == 1, data)
        new_coincidences = filter(lambda x: len(x[1]) > 1, data)

        if self.need_data:
            self.singles_curves = [
                curve(q[0], self.history_size) for q in new_singles
            ]
            self.coincidence_curves = [
                curve(q[0], self.history_size) for q in new_coincidences
            ]
            self.need_data = False

        for i in range(len(self.singles_curves)):
            self.singles_curves[i].add_point(new_singles[i][2])

        for i in range(len(self.coincidence_curves)):
            self.coincidence_curves[i].add_point(new_coincidences[i][2])
        self.draw()

    def draw_curve_set(self, curves, subplot_index):
        ax = self.fig.add_subplot(subplot_index)
        ax.set_axis_bgcolor('#000000')
        for c in curves:
            c.draw(ax, self.hi_contrast)
        ax.set_xlim(0, self.history_size)
        yfm = ax.yaxis.get_major_formatter()
        yfm.set_powerlimits([0, 1])

    def draw(self):
        ''' draw all of the curves etc '''
        self.fig.clf()
        self.draw_curve_set(self.singles_curves, 211)
        self.draw_curve_set(self.coincidence_curves, 212)
        self.fig.subplots_adjust(left=.05, right=.98, top=.97, bottom=.05)
        self.canvas.draw()
Example #47
0
class Graph_viewer:
    def __init__(self, graph, actions=['nothing'], callback=None):
        """
            weights : dictionary mapping name to weight
                      kmers will be colored in rank order of weight
        
        """

        self.graph = graph
        self.callback = callback

        self.window = gtk.Window()
        self.window.connect('destroy', lambda x: gtk.main_quit())
        self.window.set_default_size(800, 600)
        self.window.set_title('Graph viewer')

        vbox = gtk.VBox()
        self.window.add(vbox)

        self.figure = Figure(figsize=(8, 6), dpi=50)
        self.axes = self.figure.add_subplot(111)

        colors = numpy.empty((len(graph.names), 3))
        sizes = numpy.empty(len(graph.names))

        sizes[:] = 2.0

        #if weights is None:
        #    #self.axes.plot(graph.positions[:,0], graph.positions[:,1], ',')
        #
        #    colors[:,:] = [[0.0,0.0,0.0]]
        #
        #else:

        #names = weights.keys()
        #values = weights.values()
        ##names.sort(key=lambda x: weights[x])
        #idents = numpy.array([ graph.name_to_ident[name] for name in names ])

        #x = numpy.array(values, dtype='float64')
        x = numpy.array(graph.weights, dtype='float64')

        x = numpy.log(x)

        x -= numpy.minimum.reduce(x)
        x /= numpy.average(x) * 2.0
        #x /= numpy.sum(x*x)*2.0/numpy.sum(x)

        xx = numpy.minimum(x, 1.0)
        #x = numpy.arange(len(graph.names)) / float(len(graph.names))

        colors[:, 0] = 0.5 - xx * 0.5
        colors[:, 1] = 0.75 - xx * 0.5
        colors[:, 2] = 1.0 - xx * 0.5

        sizes[:] = numpy.maximum(x, 1.0)**2  #*2.0

        #n = 20
        #for i in xrange(n):
        #    start = i*len(names)//n
        #    end = (i+1)*len(names)//n
        #    if start == end: continue
        #
        #    x = (1.0-float(i)/(n-1))
        #    position_block = graph.positions[idents[start:end]]
        #    self.axes.scatter(position_block[:,0],
        #               position_block[:,1],
        #               linewidths=0,
        #               marker='s',
        #               s=10.0,
        #               c=(0.0,x,x*0.5+0.5),
        #               zorder=i)

        dots = Dots(graph.positions[:, 1], graph.positions[:, 0], colors,
                    sizes)
        self.axes.add_artist(dots)

        #if len(graph.links) < 1000:
        #    for i, (other, other_sign, other_travel) in enumerate(graph.links):
        #        for j in other:
        #            if j > i:
        #                self.axes.plot([graph.positions[i,0],graph.positions[j,0]],
        #                           [graph.positions[i,1],graph.positions[j,1]],
        #                           'k-')

        self.axes.axis('scaled')
        self.axes.set_xlim(0.0,
                           numpy.maximum.reduce(graph.positions[:, 0]) * 1.1)
        self.axes.set_ylim(0.0,
                           numpy.maximum.reduce(graph.positions[:, 1]) * 1.1)

        self.figure.subplots_adjust(top=0.99,
                                    bottom=0.05,
                                    right=0.99,
                                    left=0.05)

        #pylab.connect('button_press_event', self._on_click)

        self.annotation_pylab = []
        self.clear_annotation()

        self.canvas = FigureCanvas(self.figure)  # a gtk.DrawingArea
        self.canvas.mpl_connect('button_press_event', self._on_down)
        self.canvas.mpl_connect('button_release_event', self._on_up)

        vbox.pack_start(self.canvas)

        hbox = gtk.HBox()
        vbox.pack_start(hbox, False, False, 10)

        label = gtk.Label('Middle click:')
        hbox.pack_start(label, False, False, 5)

        self.radios = {}
        last = None
        for action in actions:
            radio = gtk.RadioButton(group=last, label=action)
            last = radio
            self.radios[action] = radio
            hbox.pack_start(radio, False, False, 5)

        label = gtk.Label('Right click: clear')
        hbox.pack_end(label, False, False, 5)

        self.radios[actions[0]].set_active(True)

        toolbar = NavigationToolbar(self.canvas, self.window)
        vbox.pack_start(toolbar, False, False)

    def run(self):
        self.window.show_all()
        gtk.main()

    def clear_annotation(self):
        self.annotation = {}

    def label(self, name, label):
        ident = self.graph.name_to_ident[name]
        self.axes.text(self.graph.positions[ident, 0],
                       self.graph.positions[ident, 1],
                       label,
                       horizontalalignment='center',
                       verticalalignment='bottom',
                       zorder=100000)

    def arrow(self, names, label):
        positions = [
            self.graph.positions[self.graph.name_to_ident[name]]
            for name in names if self.graph.has(name)
        ]

        if not positions: return  #Error?

        max_positions = max(4, (len(positions) + 29) // 30)  #20
        if len(positions) > max_positions:
            positions = [
                positions[i * (len(positions) - 1) // (max_positions - 1)]
                for i in xrange(max_positions)
            ]

        arrow = Arrow(positions, label, True)

        #names = [ name for name in names if self.graph.has(name) ]
        #
        #if len(names) < 2: return #Error?
        #
        #ident1 = self.graph.name_to_ident[names[0]]
        #ident2 = self.graph.name_to_ident[names[-1]]
        #
        #arrow = Arrow(self.graph.positions[ident1],
        #              self.graph.positions[ident2],
        #              label,
        #              True)
        self.axes.add_artist(arrow)

    def annotate(self, name, mass, r, g, b):
        r *= mass
        g *= mass
        b *= mass
        old_mass, old_r, old_g, old_b = self.annotation.get(
            name, (0.0, 0.0, 0.0, 0.0))
        self.annotation[name] = (old_mass + mass, old_r + r, old_g + g,
                                 old_b + b)

    def refresh_annotation(self):
        while self.annotation_pylab:
            item = self.annotation_pylab.pop(-1)
            item.remove()

        xs = []
        ys = []
        colors = []
        sizes = []
        for name in self.annotation:
            mass, r, g, b = self.annotation[name]
            if not mass: continue

            ident = self.graph.name_to_ident[name]
            xs.append(self.graph.positions[ident, 0])
            ys.append(self.graph.positions[ident, 1])
            colors.append((r / mass, g / mass, b / mass))
            sizes.append(mass)

        if xs:
            #thing = self.axes.scatter(
            #    xs,
            #    ys,
            #    s=sizes,
            #    c=colors,
            #    linewidths=0,
            #    marker='s',
            #    zorder=10000)
            thing = Dots(numpy.array(ys),
                         numpy.array(xs),
                         numpy.array(colors),
                         numpy.array(sizes),
                         zorder=2)
            self.axes.add_artist(thing)
            self.annotation_pylab.append(thing)

        self.canvas.draw()

    def name_from_position(self, x, y):
        xoff = self.graph.positions[:, 0] - x
        yoff = self.graph.positions[:, 1] - y
        dist2 = xoff * xoff + yoff * yoff
        best = numpy.argmin(dist2)

        return self.graph.names[best]

    def _on_down(self, event):
        self.down_name = self.name_from_position(event.xdata, event.ydata)

    def _on_up(self, event):
        if event.inaxes and event.button == 3:
            self.clear_annotation()
            self.refresh_annotation()

        elif event.inaxes and event.button == 2:
            name = self.name_from_position(event.xdata, event.ydata)

            if self.callback:
                action = None
                for item in self.radios:
                    if self.radios[item].get_active():
                        action = item

                self.callback(self, action, self.down_name, name)
                self.refresh_annotation()

            del self.down_name
Example #48
0
class MasterPlot(Plot):
  k1={'amd64' :
      ['amd64_core','amd64_core','amd64_sock','lnet','lnet',
       'ib_sw','ib_sw','cpu'],
      'intel_pmc3' : ['intel_pmc3', 'intel_pmc3', 'intel_pmc3', 'intel_pmc3',
                      'lnet', 'lnet', 'ib_ext','ib_ext','cpu','mem','mem','mem'],
      'intel_nhm' : ['intel_nhm', 'intel_nhm', 'intel_nhm', 'intel_nhm', 
                     'lnet', 'lnet', 'ib_ext','ib_ext','cpu','mem','mem','mem'],
      'intel_wtm' : ['intel_wtm', 'intel_wtm', 'intel_wtm', 'intel_wtm', 
                     'lnet', 'lnet', 'ib_ext','ib_ext','cpu','mem','mem','mem'],
      'intel_snb' : ['intel_snb_imc', 'intel_snb_imc', 'intel_snb', 
                     'lnet', 'lnet', 'ib_sw','ib_sw','cpu',
                     'intel_snb', 'intel_snb', 'intel_snb', 'mem', 'mem','mem'],
      'intel_hsw' : ['intel_hsw_imc', 'intel_hsw_imc', 'intel_hsw', 
                     'lnet', 'lnet', 'ib_sw','ib_sw','cpu',
                     'intel_hsw', 'intel_hsw', 'intel_hsw', 'mem', 'mem','mem'],
      'intel_ivb' : ['intel_ivb_imc', 'intel_ivb_imc', 'intel_ivb', 
                     'lnet', 'lnet', 'ib_sw','ib_sw','cpu',
                     'intel_ivb', 'intel_ivb', 'intel_ivb', 'mem', 'mem','mem'],

      }
  
  k2={'amd64':
      ['SSE_FLOPS','DCSF','DRAM','rx_bytes','tx_bytes',
       'rx_bytes','tx_bytes','user'],
      'intel_pmc3' : ['MEM_UNCORE_RETIRED_REMOTE_DRAM',
                      'MEM_UNCORE_RETIRED_LOCAL_DRAM',
                      'FP_COMP_OPS_EXE_SSE_PACKED',
                      'FP_COMP_OPS_EXE_SSE_SCALAR',
                      'rx_bytes','tx_bytes', 
                      'port_recv_data','port_xmit_data','user', 'MemUsed', 
                      'FilePages','Slab'],
      'intel_nhm' : ['MEM_UNCORE_RETIRED_REMOTE_DRAM',
                     'MEM_UNCORE_RETIRED_LOCAL_DRAM',
                     'FP_COMP_OPS_EXE_SSE_PACKED',
                     'FP_COMP_OPS_EXE_SSE_SCALAR', 
                     'rx_bytes','tx_bytes', 
                     'port_recv_data','port_xmit_data','user', 'MemUsed', 
                     'FilePages','Slab'],
      'intel_wtm' : ['MEM_UNCORE_RETIRED_REMOTE_DRAM',
                     'MEM_UNCORE_RETIRED_LOCAL_DRAM',
                     'FP_COMP_OPS_EXE_SSE_PACKED',
                     'FP_COMP_OPS_EXE_SSE_SCALAR', 
                     'rx_bytes','tx_bytes', 
                     'port_recv_data','port_xmit_data','user', 'MemUsed', 
                     'FilePages','Slab'],
      'intel_snb' : ['CAS_READS', 'CAS_WRITES', 'LOAD_L1D_ALL',
                     'rx_bytes','tx_bytes', 'rx_bytes','tx_bytes','user',
                     'SSE_DOUBLE_SCALAR', 'SSE_DOUBLE_PACKED', 
                     'SIMD_DOUBLE_256', 'MemUsed', 'FilePages','Slab'],
      'intel_hsw' : ['CAS_READS', 'CAS_WRITES', 'LOAD_L1D_ALL',
                     'rx_bytes','tx_bytes', 'rx_bytes','tx_bytes','user',
                     'SSE_DOUBLE_SCALAR', 'SSE_DOUBLE_PACKED', 
                     'SIMD_DOUBLE_256', 'MemUsed', 'FilePages','Slab'],
      'intel_ivb' : ['CAS_READS', 'CAS_WRITES', 'LOAD_L1D_ALL',
                     'rx_bytes','tx_bytes', 'rx_bytes','tx_bytes','user',
                     'SSE_DOUBLE_SCALAR', 'SSE_DOUBLE_PACKED', 
                     'SIMD_DOUBLE_256', 'MemUsed', 'FilePages','Slab'],

      }

  fname='master'

  def plot(self,jobid,job_data=None):
    if not self.setup(jobid,job_data=job_data): return

    if self.wide:
      self.fig = Figure(figsize=(15.5,12),dpi=110)
      self.ax=self.fig.add_subplot(6,2,2)
      cols = 2
      shift = 2
    else:
      self.fig = Figure(figsize=(8,12),dpi=110)
      self.ax=self.fig.add_subplot(6,1,1)
      cols = 1
      shift = 1
    if self.mode == 'hist':
      plot=self.plot_thist
    elif self.mode == 'percentile':
      plot=self.plot_mmm
    else:
      plot=self.plot_lines

    k1_tmp=self.k1[self.ts.pmc_type]
    k2_tmp=self.k2[self.ts.pmc_type]
    processor_schema = self.ts.j.schemas[self.ts.pmc_type]
    # Plot key 1 for flops
    plot_ctr = 0
    try:
      if 'SSE_D_ALL' in processor_schema and 'SIMD_D_256' in processor_schema:
        idx0 = k2_tmp.index('SSE_D_ALL')
        idx1 = None
        idx2 = k2_tmp.index('SIMD_D_256')
      elif 'SSE_DOUBLE_SCALAR' in processor_schema and 'SSE_DOUBLE_PACKED' in processor_schema and 'SIMD_DOUBLE_256' in processor_schema:
        idx0 = k2_tmp.index('SSE_DOUBLE_SCALAR')
        idx1 = k2_tmp.index('SSE_DOUBLE_PACKED')
        idx2 = k2_tmp.index('SIMD_DOUBLE_256')
      elif 'FP_COMP_OPS_EXE_SSE_PACKED' in processor_schema and 'FP_COMP_OPS_EXE_SSE_SCALAR' in processor_schema:
        idx0 = k2_tmp.index('FP_COMP_OPS_EXE_SSE_SCALAR')
        idx1 = k2_tmp.index('FP_COMP_OPS_EXE_SSE_PACKED')
        idx2 = None
      else: 
        print("FLOP stats not available for JOBID",self.ts.j.id)
        raise
      plot_ctr += 1
      ax = self.fig.add_subplot(6,cols,plot_ctr*shift)      
      for host_name in self.ts.j.hosts.keys():
        flops = self.ts.assemble([idx0],host_name,0)
        if idx1: flops += 2*self.ts.assemble([idx1],host_name,0)
        if idx2: flops += 4*self.ts.assemble([idx2],host_name,0)
        
        flops = numpy.diff(flops)/numpy.diff(self.ts.t)/1.0e9
        ax.step(self.ts.t/3600., numpy.append(flops, [flops[-1]]), 
                where="post")

      ax.set_ylabel('Dbl GFLOPS')
      ax.set_xlim([0.,self.ts.t[-1]/3600.])
      tspl_utils.adjust_yaxis_range(ax,0.1)
    except: 
      print sys.exc_info()[0]
      print("FLOP plot not available for JOBID",self.ts.j.id)

    # Plot key 2
    try:
      if 'CAS_READS' in k2_tmp and 'CAS_WRITES' in k2_tmp:
        idx0=k2_tmp.index('CAS_READS')
        idx1=k2_tmp.index('CAS_WRITES')
      elif 'MEM_UNCORE_RETIRED_REMOTE_DRAM' in k2_tmp and 'MEM_UNCORE_RETIRED_LOCAL_DRAM' in k2_tmp:
        idx0=k2_tmp.index('MEM_UNCORE_RETIRED_REMOTE_DRAM')
        idx1=k2_tmp.index('MEM_UNCORE_RETIRED_LOCAL_DRAM')
      else:
        print(self.ts.pmc_type + ' missing Memory Bandwidth data' + ' for jobid ' + self.ts.j.id )
        raise      
      plot_ctr += 1
      plot(self.fig.add_subplot(6,cols,plot_ctr*shift), [idx0,idx1], 3600., 
           1.0/64.0*1024.*1024.*1024., ylabel='Total Mem BW GB/s')
    except:
      print(self.ts.pmc_type + ' missing Memory Bandwidth plot' + ' for jobid ' + self.ts.j.id )

    #Plot key 3
    idx0=k2_tmp.index('MemUsed')
    idx1=k2_tmp.index('FilePages')
    idx2=k2_tmp.index('Slab')
    plot_ctr += 1
    plot(self.fig.add_subplot(6,cols,plot_ctr*shift), [idx0,-idx1,-idx2], 3600.,2.**30.0, 
         ylabel='Memory Usage GB',do_rate=False)

    # Plot lnet sum rate
    idx0=k1_tmp.index('lnet')
    idx1=idx0 + k1_tmp[idx0+1:].index('lnet') + 1
    plot_ctr += 1
    plot(self.fig.add_subplot(6,cols,plot_ctr*shift), [idx0,idx1], 3600., 1024.**2, ylabel='Total lnet MB/s')

    # Plot remaining IB sum rate
    if 'ib_ext' in self.ts.j.hosts.values()[0].stats:
      try:
        idx2=k1_tmp.index('ib_sw')
        idx3=idx2 + k1_tmp[idx2+1:].index('ib_sw') + 1
      except:
        idx2=k1_tmp.index('ib_ext')
        idx3=idx2 + k1_tmp[idx2+1:].index('ib_ext') + 1
      try:
        plot_ctr += 1
        plot(self.fig.add_subplot(6,cols,plot_ctr*shift),[idx2,idx3,-idx0,-idx1],3600.,2.**20,
             ylabel='Total (ib-lnet) MB/s') 
      except: pass

    #Plot CPU user time
    idx0 = [k2_tmp.index('user')]
    plot_ctr += 1

    wayness = len(self.ts.j.hosts.values()[0].stats['cpu'].keys())
    plot(self.fig.add_subplot(6,cols,plot_ctr*shift),idx0,3600.,wayness,
         xlabel='Time (hr)',
         ylabel='cpu usage %')
    
    self.fig.subplots_adjust(hspace=0.35)
    self.output('master')
Example #49
0
class MyFigureCanvas(FigureCanvas):
    """
    Main class of generating figs in GUI using matplot.backend_qt5agg

    Contains:
    drawing functions
        plot_acc_response_
        plot_launch_
        plot_max_acc_
        plot_pedal_map_
        plot_raw_data
        plot_radar_map_

    """
    def __init__(self,
                 parent=None,
                 width=10,
                 height=10,
                 dpi=100,
                 plot_type='3d',
                 **kwargs):
        self.fig = Figure(figsize=(width, height), dpi=100)
        super(MyFigureCanvas, self).__init__(self.fig)
        self.kwargs = kwargs
        # self.data = data
        # self.parameter1 = para1
        # FigureCanvas.__init__(self, fig)  # 初始化父类   堆栈溢出问题!
        # self.setParent(parent)
        if plot_type == '2d':
            self.axes = self.fig.add_axes([0.1, 0.1, 0.8, 0.8])
        elif plot_type == '3d':
            self.fig.subplots_adjust(left=0.08,
                                     top=0.92,
                                     right=0.95,
                                     bottom=0.1)
            self.axes = self.fig.add_subplot(111, projection='3d')
        elif plot_type == '2d-poly':
            self.axes = self.fig.add_subplot(111, polar=True)
        elif plot_type == '2d-multi':
            pass
        elif plot_type == '3d-subplot':
            pass
        elif plot_type == '2d-subplot':
            pass

    def plot_acc_response(self, data, ped_avg):  # 目前做不到先画图,后统一输出,只能在主线程里面同步画

        for i in range(0, len(data[1])):
            self.axes.plot(data[1][i],
                           data[0][i],
                           data[2][i],
                           label=int(round(ped_avg[i] / 5) * 5))
            self.axes.legend(bbox_to_anchor=(1.02, 1), loc=1, borderaxespad=0)
            self.axes.set_xlabel('Velocity (kph)', fontsize=12)
            self.axes.set_ylabel('Pedal (%)', fontsize=12)
            self.axes.set_zlabel('Acc (g) ', fontsize=12)

    def plot_launch(self, data):

        for i in range(0, len(data[2])):
            self.axes.plot(data[2][i],
                           data[1][i],
                           label=int(round(np.mean(data[0][i]) / 5) * 5))
            self.axes.legend()
            self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
        self.axes.set_xlabel('Time (s)', fontsize=12)
        self.axes.set_ylabel('Acc (g)', fontsize=12)
        self.axes.set_title('Launch', fontsize=12)

    def plot_max_acc(self, data):

        # self.axes.plot(data[0], data[1], color='green', linestyle='dashed', marker='o', markerfacecolor='blue',
        #                markersize=8)
        self.axes.plot(data[0],
                       data[1],
                       linestyle='dashed',
                       marker='o',
                       markersize=8)
        self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
        self.axes.legend()
        self.axes.set_xlabel('Pedal (%)', fontsize=12)
        self.axes.set_ylabel('Acc (g)', fontsize=12)
        self.axes.set_title('Acc-Pedal', fontsize=12)

    def plot_pedal_map(self, data):

        pedalmap = self.axes.scatter(data[1],
                                     data[2],
                                     c=data[0],
                                     marker='o',
                                     linewidths=0.1,
                                     s=6,
                                     cmap=cm.get_cmap('RdYlBu_r'))
        self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
        self.axes.set_xlabel('Engine Speed (rpm)', fontsize=12)
        self.axes.set_ylabel('Torque (Nm)', fontsize=12)
        self.axes.set_title('PedalMap', fontsize=12)

    def plot_shift_map(self, data):

        str_label = [
            '1->2', '2->3', '3->4', '4->5', '5->6', '6->7', '7->8', '8->9',
            '9->10'
        ]
        for i in range(1, int(max(data[0])) + 1):
            # 选择当前Gear, color=colour[i]
            self.axes.plot(data[2][np.where(data[0] == i)],
                           data[1][np.where(data[0] == i)],
                           marker='o',
                           linestyle='-',
                           linewidth=3,
                           markerfacecolor='blue',
                           markersize=4,
                           label=str_label[i - 1])
            self.axes.legend()
        self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
        self.axes.set_xlabel('Vehicle Speed (km/h)', fontsize=12)
        self.axes.set_ylabel('Pedal (%)', fontsize=12)
        self.axes.set_title('ShiftMap', fontsize=12)

    def plot_systemgain_curve(self, vehspd_sg, acc_sg):
        speedIndex = np.arange(10, 170, 10)
        speedIndex = speedIndex.tolist()
        acc_banana = np.zeros((5, len(speedIndex)))
        acc_banana[0, :] = [
            0.0144, 0.0126, 0.0111, 0.0097, 0.0084, 0.0073, 0.0064, 0.0056,
            0.0048, 0.0042, 0.0037, 0.0032, 0.0028, 0.0024, 0.0021, 0.0018
        ]
        acc_banana[1, :] = [
            0.0172, 0.0152, 0.0134, 0.0119, 0.0104, 0.0092, 0.0081, 0.0071,
            0.0063, 0.0055, 0.0049, 0.0043, 0.0038, 0.0034, 0.0030, 0.0026
        ]
        acc_banana[2, :] = [
            0.0200, 0.0178, 0.0158, 0.0141, 0.0125, 0.0111, 0.0098, 0.0087,
            0.0078, 0.0069, 0.0062, 0.0055, 0.0049, 0.0043, 0.0038, 0.0033
        ]
        acc_banana[3, :] = [
            0.0228, 0.0204, 0.0182, 0.0163, 0.0145, 0.0129, 0.0115, 0.0103,
            0.0092, 0.0082, 0.0074, 0.0066, 0.0059, 0.0053, 0.0047, 0.0042
        ]
        acc_banana[4, :] = [
            0.0256, 0.0230, 0.0206, 0.0185, 0.0166, 0.0149, 0.0133, 0.0119,
            0.0107, 0.0096, 0.0086, 0.0077, 0.0069, 0.0062, 0.0055, 0.0049
        ]

        # self.axes.plot(vehspd_sg, acc_sg, color='green', linestyle='-')
        self.axes.plot(vehspd_sg, acc_sg, linestyle='-')
        self.axes.plot(speedIndex,
                       acc_banana[0, :],
                       color='blue',
                       linestyle='--')
        self.axes.plot(speedIndex,
                       acc_banana[1, :],
                       color='red',
                       linestyle='--')
        self.axes.plot(speedIndex,
                       acc_banana[2, :],
                       color='black',
                       linestyle='--')
        self.axes.plot(speedIndex,
                       acc_banana[3, :],
                       color='blue',
                       linestyle='--')
        self.axes.plot(speedIndex,
                       acc_banana[4, :],
                       color='red',
                       linestyle='--')
        self.axes.plot([speedIndex[0]] * 5,
                       acc_banana[:, 0],
                       color='blue',
                       linestyle='-')
        self.axes.set_xlabel('velocity(km/h)')
        self.axes.set_ylabel('acc(g/mm)')
        self.axes.set_xlim(0, 120)
        self.axes.set_ylim(0, 0.03)
        self.axes.grid(True, linestyle="-", color="grey", linewidth="0.4")

    def plot_constant_speed(self, vehspd_cs, pedal_cs):

        # self.axes.plot(vehspd_cs, pedal_cs, color='green', linestyle='dashed', marker='o', markerfacecolor='blue',
        # markersize=8)
        self.axes.plot(vehspd_cs,
                       pedal_cs,
                       linestyle='dashed',
                       marker='o',
                       markersize=8)
        self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
        self.axes.legend()
        self.axes.set_xlabel('velocity (kph)', fontsize=12)
        self.axes.set_ylabel('pedal (%)', fontsize=12)
        self.axes.set_title('Constant Speed', fontsize=12)

    def plot_acc_response_(self):
        '''


        :return:
        '''
        self.xdata = self.kwargs['data'][1]
        self.ydata = self.kwargs['data'][0]
        self.zdata = self.kwargs['data'][2]
        self.pedal_avg = self.kwargs['pedal_avg']
        for i in range(0, len(self.xdata)):
            self.axes.plot(self.xdata[i],
                           self.ydata[i],
                           self.zdata[i],
                           label=int(round(self.pedal_avg[i] / 5) * 5))
            self.axes.legend(bbox_to_anchor=(1.02, 1), loc=1, borderaxespad=0)
        self.axes.set_xlabel('Vehicle Speed (km/h)', fontsize=12)
        self.axes.set_ylabel('Pedal(%)', fontsize=12)
        self.axes.set_zlabel('Acc (g)', fontsize=12)
        self.axes.set_title('Acc-3D Map', fontsize=12)

    def plot_launch_(self):
        self.xdata = self.kwargs['data'][2]
        self.ydata = self.kwargs['data'][1]
        self.pedal = self.kwargs['data'][0]
        for i in range(0, len(self.xdata)):
            self.axes.plot(self.xdata[i],
                           self.ydata[i],
                           label=int(round(np.mean(self.pedal[i]) / 5) * 5))
            self.axes.legend()
        self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
        self.axes.set_xlabel('Time (s)', fontsize=12)
        self.axes.set_ylabel('Acc (g)', fontsize=12)
        self.axes.set_title('Launch', fontsize=12)

    def plot_max_acc_(self):
        self.xdata = self.kwargs['xdata']
        self.ydata = self.kwargs['ydata']
        self.axes.plot(self.xdata,
                       self.ydata,
                       color='green',
                       linestyle='dashed',
                       marker='o',
                       markerfacecolor='blue',
                       markersize=8)
        self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
        self.axes.legend()
        self.axes.set_xlabel('Pedal (%)', fontsize=12)
        self.axes.set_ylabel('Acc (g)', fontsize=12)
        self.axes.set_title('Acc-Pedal', fontsize=12)

    def plot_pedal_map_(self):
        self.xdata = self.kwargs['data'][1]
        self.ydata = self.kwargs['data'][2]
        self.zdata = self.kwargs['data'][0]
        self.axes.scatter(self.xdata,
                          self.ydata,
                          c=self.zdata,
                          marker='o',
                          linewidths=0.1,
                          s=6,
                          cmap=cm.get_cmap('RdYlBu_r'))
        self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
        self.axes.set_xlabel('Engine Speed (rpm)', fontsize=12)
        self.axes.set_ylabel('Torque (Nm)', fontsize=12)
        self.axes.set_title('PedalMap', fontsize=12)

    def plot_raw_data(self, time, df, **kwargs):

        pos = [0.02, 0.1, 0.8, 0.8]
        colors = ['r', 'b', 'g', 'y', 'orchid', 'orange', 'navy']
        font_size = 10

        for i in range(df.shape[1]):
            if i == 0:
                self.axes = self.fig.add_axes(
                    pos, axisbg='w', label=str(df.columns[i]))  # 设置初始的图层底色为白色
                self.axes.tick_params(axis='x', colors='black', labelsize=10)
                self.axes.set_xlabel('time (s)', fontsize=12)
            else:
                self.axes = self.fig.add_axes(
                    pos, axisbg='none',
                    label=str(df.columns[i]))  # 设置随后的图层底色为透明

            self.axes.spines['right'].set_position(
                ('outward', 60 * i))  # 图的右侧边框向外移动
            self.axes.spines['right'].set_color(colors[i])
            self.axes.spines['right'].set_linewidth(2)
            self.axes.plot(time, df.iloc[:, i], linewidth=1, color=colors[i])
            self.axes.yaxis.set_ticks_position('right')
            self.axes.tick_params(axis='y', colors=colors[i])
            self.axes.set_ylabel(str(df.columns[i]),
                                 fontsize=font_size,
                                 color=colors[i])
            self.axes.yaxis.set_label_position('right')

    def plot_radar_map_(self):
        self.theta = self.kwargs['theta']
        self.data = self.kwargs['data']
        self.legends = self.kwargs['legends']
        # plt.thetagrids(theta*(180/np.pi), labels=labels, fontproperties=myfont)
        self.axes.set_ylim(0, 100)
        colour_Bar = [
            'blue', 'red', 'c', 'royalblue', 'lightcoral', 'yellow',
            'lightgreen', 'brown', 'teal', 'orange', 'coral', 'gold', 'lime',
            'olive'
        ]
        if self.data.size <= 7:  # 一条数据绘制
            # 画雷达图,并填充雷达图内部区域
            self.axes.plot(self.theta,
                           self.data,
                           "o-",
                           color='blue',
                           linewidth=2)
            self.axes.fill(self.theta, self.data, color="blue", alpha=0.25)
            self.axes.set_rgrids(np.arange(20, 100, 20),
                                 labels=np.arange(20, 100, 20),
                                 angle=0)
            self.axes.set_thetagrids(self.theta * (180 / np.pi),
                                     labels=np.array(
                                         ["A", "B", "C", "D", "E", "F"]))
            self.axes.set_title("Rating")
        else:
            for i in range(self.data.size // 7):
                self.axes.plot(self.theta,
                               self.data[i],
                               'o-',
                               color=colour_Bar[i],
                               linewidth=2)
                self.axes.fill(self.theta,
                               self.data[i],
                               color=colour_Bar[i],
                               alpha=0.25)
            self.axes.set_rgrids(np.arange(20, 100, 20),
                                 labels=np.arange(20, 100, 20),
                                 angle=0)
            self.axes.set_thetagrids(self.theta * (180 / np.pi),
                                     labels=np.array(
                                         ["A", "B", "C", "D", "E", "F"]))
            self.axes.set_title("Rating Comparison")
        self.axes.legend(self.legends)

    def plot_original_fig_sb(self, original_data):
        self.axes = self.fig.add_axes([0.1, 0.1, 0.8, 0.8])

        time_data = original_data.time_data
        sr_x_data = original_data.sr_x_data
        sr_y_data = original_data.sr_y_data
        sr_z_data = original_data.sr_z_data

        self.axes.plot(time_data, sr_x_data, color='black')
        self.axes.plot(time_data, sr_y_data, color='red')
        self.axes.plot(time_data, sr_z_data, color='blue')
        exam_x = np.where(sr_x_data > 10)
        exam_y = np.where(sr_y_data > 10)
        exam_z = np.where(sr_z_data > 10)

        if exam_x[0].shape[0] > 0:
            for nn in exam_x:
                self.axes.plot(time_data[nn],
                               sr_x_data[nn],
                               color='red',
                               marker='x',
                               markersize=12)
                sr_x_data[nn] = 0
        if exam_y[0].shape[0] > 0:
            for nn in exam_y:
                self.axes.plot(time_data[nn],
                               sr_y_data[nn],
                               color='red',
                               marker='x',
                               markersize=12)
        if exam_z[0].shape[0] > 0:
            for nn in exam_z:
                self.axes.plot(time_data[nn],
                               sr_z_data[nn],
                               color='red',
                               marker='x',
                               markersize=12)

        self.axes.set_xlabel('Time (s)', fontsize=10)
        self.axes.set_ylabel('Acc (g)', fontsize=10)
        self.axes.set_title('Speed bump 20kph', fontsize=12)

    def plot_filter_fig_sb(self, filter_data):
        time_data = filter_data.time_data
        sr_x_filter = filter_data.sr_x_data
        sr_y_filter = filter_data.sr_y_data
        sr_z_filter = filter_data.sr_z_data
        self.axes.plot(time_data, sr_x_filter, color='black')
        self.axes.plot(time_data, sr_y_filter, color='red')
        self.axes.plot(time_data, sr_z_filter, color='blue')
        self.axes.set_xlabel('Time (s)', fontsize=10)
        self.axes.set_ylabel('Acc (g)', fontsize=10)
        self.axes.set_title('Speed bump 20kph', fontsize=14)

    def plot_result_keyonff(self, key_on_off_fig, original_data):
        # 作图,把计算得到的特征点标注在图中
        index_st = key_on_off_fig.index_st
        index_snd = key_on_off_fig.index_snd
        index_crank_st = key_on_off_fig.index_crank_st
        index_crank_snd = key_on_off_fig.index_crank_snd
        index_flare = key_on_off_fig.index_flare
        spd_flare = key_on_off_fig.spd_flare
        time_data = original_data.time_data
        spd_data = original_data.spd_data

        self.axes.set_title('Result of key on and off', fontsize=14)
        self.axes.set_xlabel('time', fontsize=12)
        self.axes.set_ylabel('eng_spd', fontsize=12)
        self.axes.plot(time_data, spd_data, color='blue', linewidth=2)

        offset_x = 1
        offset_y = 2
        for NN in range(len(index_st)):
            self.axes.plot(time_data[index_st[NN]],
                           spd_data[index_st[NN]],
                           color='red',
                           marker='.',
                           markersize=18,
                           linewidth=2)
            self.axes.text(time_data[index_st[NN]] + offset_x,
                           spd_data[index_st[NN]] + offset_y, 'start')

            self.axes.plot(time_data[index_snd[NN]],
                           spd_data[index_snd[NN]],
                           color='red',
                           marker='^',
                           markersize=10,
                           linewidth=2)
            self.axes.text(time_data[index_snd[NN]] + offset_x,
                           spd_data[index_snd[NN]] + offset_y, 'end')

            self.axes.plot(time_data[index_crank_st[NN]],
                           spd_data[index_crank_st[NN]],
                           color='b',
                           marker='.',
                           markersize=18,
                           linewidth=2)
            self.axes.text(time_data[index_crank_st[NN]] + offset_x,
                           spd_data[index_crank_st[NN]] + offset_y,
                           'crank_start')

            self.axes.plot(time_data[index_crank_snd[NN]],
                           spd_data[index_crank_snd[NN]],
                           color='b',
                           marker='^',
                           markersize=10,
                           linewidth=2)
            self.axes.text(time_data[index_crank_snd[NN]] + offset_x,
                           spd_data[index_crank_snd[NN]] + offset_y,
                           'crank_end')

            self.axes.plot(time_data[index_flare[NN]],
                           spd_flare[NN],
                           color='black',
                           marker='.',
                           markersize=18,
                           linewidth=2)
            self.axes.text(time_data[index_flare[NN]] + offset_x,
                           spd_data[index_flare[NN]] + offset_y, 'flare')

    def reset_i(self):
        self.i = 0

    def plot_acc_response_subplot(self, history_data):
        pic_num = len(history_data)
        for m in range(pic_num):
            self.axes = self.fig.add_subplot(1,
                                             pic_num,
                                             m + 1,
                                             projection='3d')
            data = history_data[m].sysGain_class.accresponce.data
            ped_avg = history_data[m].sysGain_class.accresponce.pedal_avg
            for i in range(0, len(data[1])):
                self.axes.plot(data[1][i],
                               data[0][i],
                               data[2][i],
                               label=int(round(ped_avg[i] / 5) * 5))
                self.axes.legend(bbox_to_anchor=(1.02, 1),
                                 loc=1,
                                 borderaxespad=0)
                self.axes.set_xlabel('Velocity (kph)', fontsize=12)
                self.axes.set_ylabel('Pedal (%)', fontsize=12)
                self.axes.set_zlabel('Acc (g) ', fontsize=12)

    def plot_launch_subplot(self, history_data):
        pic_num = len(history_data)
        for m in range(pic_num):
            self.axes = self.fig.add_subplot(1, pic_num, m + 1)
            data = history_data[m].sysGain_class.launch.data

            for i in range(0, len(data[2])):
                self.axes.plot(data[2][i],
                               data[1][i],
                               label=int(round(np.mean(data[0][i]) / 5) * 5))
                self.axes.legend()
                self.axes.grid(True,
                               linestyle="--",
                               color="k",
                               linewidth="0.4")
            self.axes.set_xlabel('Time (s)', fontsize=12)
            self.axes.set_ylabel('Acc (g)', fontsize=12)
            self.axes.set_title('Launch', fontsize=12)

    def plot_shift_map_subplot(self, history_data):
        pic_num = len(history_data)
        for m in range(pic_num):
            self.axes = self.fig.add_subplot(1, pic_num, m + 1)
            data = history_data[m].sysGain_class.shiftmap.data

            str_label = [
                '1->2', '2->3', '3->4', '4->5', '5->6', '6->7', '7->8', '8->9',
                '9->10'
            ]
            for i in range(1, int(max(data[0])) + 1):
                # 选择当前Gear, color=colour[i]
                self.axes.plot(data[2][np.where(data[0] == i)],
                               data[1][np.where(data[0] == i)],
                               marker='o',
                               linestyle='-',
                               linewidth=3,
                               markerfacecolor='blue',
                               markersize=4,
                               label=str_label[i - 1])
                self.axes.legend()
            self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
            self.axes.set_xlabel('Vehicle Speed (km/h)', fontsize=12)
            self.axes.set_ylabel('Pedal (%)', fontsize=12)
            self.axes.set_title('ShiftMap', fontsize=12)

    def plot_pedal_map_subplot(self, history_data):
        pic_num = len(history_data)
        for m in range(pic_num):
            self.axes = self.fig.add_subplot(1, pic_num, m + 1)
            data = history_data[m].sysGain_class.pedalmap.data

            pedalmap = self.axes.scatter(data[1],
                                         data[2],
                                         c=data[0],
                                         marker='o',
                                         linewidths=0.1,
                                         s=6,
                                         cmap=cm.get_cmap('RdYlBu_r'))
            self.axes.grid(True, linestyle="--", color="k", linewidth="0.4")
            self.axes.set_xlabel('Engine Speed (rpm)', fontsize=12)
            self.axes.set_ylabel('Torque (Nm)', fontsize=12)
            self.axes.set_title('PedalMap', fontsize=12)
Example #50
0
class Qt5MplCanvas(FigureCanvas):
    """  A customized Qt widget for matplotlib figure.
    It can be used to replace GraphicsView of QtGui
    """
    def __init__(self, parent, width=4.5, height=4):
        """  Initialization
        """
        # from mpl_toolkits.axes_grid1 import host_subplot
        # import mpl_toolkits.axisartist as AA
        # import matplotlib.pyplot as plt

        # Instantiating matplotlib Figure
        
        self.fig = Figure(figsize=(width, height))
        self.fig.patch.set_facecolor('white')
#        self.fig.patch.set_facecolor('gray')

        self.axes = self.fig.add_subplot(111)  # return: matplotlib.axes.AxesSubplot
        self.fig.subplots_adjust(left=0.0)
        self.fig.subplots_adjust(right=1.0)
        self.fig.subplots_adjust(top=1.0)
        self.fig.subplots_adjust(bottom=0.0)
        self.axes.axis('off')

        
        # Initialize parent class and set parent
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        # Set size policy to be able to expanding and resizable with frame
        FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        # Variables to manage all lines/subplot
        self._lineDict = {}
        self._lineIndex = 0

        # legend and color bar
        self._colorBar = None
        self._isLegendOn = False
        self._legendFontSize = 8


    def _update_canvas(self, img, ROIS=[]):
        """ Add an image by file
        """
#        import scipy.ndimage as ndimage

        #import matplotlib.image as mpimg

        self.clear_canvas()
        # set aspect to auto mode
        self.axes.set_aspect('auto')

        im = img[:,:,0]
#        im = ndimage.gaussian_filter(im, sigma=(8, 8), order=0)

        # lum_img = img[:,:,0]
        # FUTURE : refactor for image size, interpolation and origin
        self.axes.imshow(  np.fliplr( im[:,:].T ) ) 
        
        for rois in ROIS:            
            x1,y1, x2,y2 = rois
            self.axes.plot([x1,x2],[y1,y1], 'k')
            self.axes.plot([x1,x1],[y1,y2], 'k')
            self.axes.plot([x1,x2],[y2,y2], 'k')
            self.axes.plot([x2,x2],[y1,y2], 'k')

            
        self.axes.axis('off')
        self.draw()
    
    def addImage(self, img):
        """ Add an image by file
        """
        #import matplotlib.image as mpimg
        self.clear_canvas()

        # set aspect to auto mode
        self.axes.set_aspect('auto')

        #img = matplotlib.image.imread( imagefilename )
        self.axes.imshow(  img ) 
        
        # lum_img = img[:,:,0]
        # FUTURE : refactor for image size, interpolation and origin
        self.axes.axis('off')
        self.draw()
        
    def difference(self, SimPat, img):
        """ Add an image by file
        """
        #import matplotlib.image as mpimg
        self.clear_canvas()

        # set aspect to auto mode
        self.axes.set_aspect('auto')

#        img = matplotlib.image.imread( imagefilename )
        self.axes.imshow(  np.fliplr( SimPat[:,:,0].T ) - img ) 
        
        # lum_img = img[:,:,0]
        # FUTURE : refactor for image size, interpolation and origin
        self.axes.set_xticks([])
        self.axes.set_yticks([])
        self.draw()        

            
    def clear_canvas(self):
        """ Clear data including lines and image from canvas
        """
        
        # clear image
        self.axes.cla()

# END-OF-CLASS (MplGraphicsView) 
Example #51
0
class GraphFrame(wx.Frame):
	""" The main frame of the application
	"""
	title = 'Demo: dynamic matplotlib graph'
	T = []
	def __init__(self):
		wx.Frame.__init__(self, None, -1, self.title)

		self.showSPO2 = 0
		self.showPulse = 0
		self.paused = False
		self.plotData = [0]
		self.data_lock = threading.Lock()
		self.create_main_panel()
		self.flag = ""

		self.redraw_timer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)
		self.redraw_timer.Start(fs)
		self.Bind(wx.EVT_CLOSE, self.OnClose)

		self.on_timer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, functools.partial(self.Send, msg='mode:On'), self.on_timer)

		self.off_timer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, functools.partial(self.Send, msg='mode:Off'), self.off_timer)

		self.check_timer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, self.check_file, self.check_timer)

		self.disconnect_timer = wx.Timer(self)
		self.T = []
		# self.T.append(self.on_timer)
		# self.T.append(self.off_timer)
		# self.T.append(self.disconnect_timer)


	def OnClose(self, event):
		global en_flag
		print "closing"
		en_flag = False
		self.Destroy()

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

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

		self.comport_control = ComportPanel(self.panel,-1)
		self.comport_control.disconnect_button.Disable()

		self.hbox2 = wx.BoxSizer(wx.HORIZONTAL)
		self.hbox2.Add(self.comport_control, border=5, flag=wx.ALL)

		self.vbox = wx.BoxSizer(wx.HORIZONTAL)
		self.vbox.Add(self.hbox2, 0, flag=wx.ALIGN_CENTER | wx.TOP)
		self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW)

		self.panel.SetSizer(self.vbox)
		self.vbox.Fit(self)

	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.fig.subplots_adjust(left=0.03, right=0.995, bottom = 0.03, top = 0.95)
		self.axes.set_axis_bgcolor('black')
		self.axes.set_title('MiniPSG', size=12)
		self.axes.get_yaxis().set_visible(True)
		self.axes.yaxis.set_ticks([ ])

		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 = []
		self.plot_data.extend(
			self.axes.plot(
				np.arange(len(self.plotData)),
				self.plotData[:],
				'r',
				linewidth=1,
			)
		)

	def draw_plot(self):
		""" Redraws the plot
		"""
		show_len = 30 * fs
		if self.data_lock.acquire():
			ymin = 0
			ymax = 300
			xmax = len(self.plotData) if len(self.plotData) > show_len else show_len
			xmin = xmax - show_len
			xmax = xmax/float(fs)
			xmin = xmin/float(fs)
			self.axes.set_xbound(lower=xmin, upper=xmax)
			self.axes.set_ybound(lower=ymin, upper=ymax)
			self.axes.grid(True, color='gray')

			pylab.setp(self.axes.get_xticklabels(), visible=True)

			if len(self.plotData) < show_len:
				self.plot_data[0].set_xdata(np.arange(0,len(self.plotData),1.0)/float(fs))
				self.plot_data[0].set_ydata(np.array(self.plotData))
			else:
				self.plot_data[0].set_xdata(np.arange(len(self.plotData)-show_len,len(self.plotData),1.0)/float(fs))
				self.plot_data[0].set_ydata(np.array(self.plotData[-show_len:]))

			self.data_lock.release()

		self.canvas.draw()

	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.)
        #

		self.draw_plot()

	def on_exit(self, event):
		self.Destroy()

	def connect(self, event):
		global en_flag
		en_flag = True
		self.plotData = []

		if (self.check_timer.IsRunning()):
			self.check_timer.Stop()
		if self.comport_control.file_textctrl.GetValue()=="":
			filename = "./rawData/test.txt"
		else:
			filename = "./rawData/"+self.comport_control.file_textctrl.GetValue()+".txt"

		dataThread = SerialThread(self.plotData, self.data_lock, filename)
		self.comport_control.connect_button.Disable()
		self.comport_control.disconnect_button.Enable()
		dataThread.start()
		self.Bind(wx.EVT_TIMER, functools.partial(self.auto_disconnect, e=event), self.disconnect_timer)
		self.schedule()

	def schedule(self):
		self.on_timer.Start(5000)
		self.off_timer.Start(25000)
		self.disconnect_timer.Start(30000)

	def check_file(self, event):
		if(os.path.exists('result.txt')):
			f = open('result.txt', 'r')
			r = f.read().splitlines()
			result = 'result:' + r[0]
			self.SendTo(result)
			self.check_timer.Stop()
			f.close()
			os.remove('result.txt')


	def auto_disconnect(self, event, e):
		self.disconnect(e)

	def Send(self, event, msg):
		self.SendTo(msg)

	def disconnect(self, event):
		global en_flag
		en_flag = False
		print(self.disconnect_timer.IsRunning())
		self.disconnect_timer.Stop()
		if(self.on_timer.IsRunning()):
			self.on_timer.Stop()
		if(self.off_timer.IsRunning()):
			self.off_timer.Stop()
		print("stop record",time.ctime())
		self.check_timer.Start(500)
		self.comport_control.connect_button.Enable()
		self.comport_control.disconnect_button.Disable()
		filename = "./rawData/"+self.comport_control.file_textctrl.GetValue()+".txt"
		copyfile(filename, "./testing.txt")				

		print "disconnect!"

	def SendTo(self, message):
		# Create a TCP/IP socket
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

		# Connect the socket to the port where the server is listening
		#server_address = ('localhost', 10000)
		server_address = (sys.argv[1], 10000)
		print ('\n########################')
		print("send", time.ctime())
		print >>sys.stderr, 'connecting to %s port %s' % server_address
		sock.connect(server_address)

		try:
			# Send data
			#message = 'This is the message.  It will be repeated.'
			print ('------------------------')
			print >>sys.stderr, 'send: "%s"' % message
			sock.sendall(message)


			# # Look for the response
			# amount_received = 0
			# amount_expected = len(message)
			#
			# while amount_received < amount_expected:
			# 	data = sock.recv(16)
			# 	amount_received += len(data)
			# 	print >>sys.stderr, 'received "%s"' % data

		finally:
			#print >>sys.stderr, 'closing socket'
			if(message == 'mode:On'):
				print(self.on_timer.IsRunning())
				self.on_timer.Stop()
			elif(message == 'mode:Off'):
				print(self.off_timer.IsRunning())
				self.off_timer.Stop()
			print ('########################')
			sock.close()

	def devSelect(self, event):
		global chan
		index = event.GetSelection()
		chan = devChoice[index]
		print chan
Example #52
0
class appGui:
    def __init__(self):
        gladefile = "paViewerGUI.glade"
        self.windowname = "MainWindow"
        self.wTree = gtk.glade.XML(gladefile, self.windowname)
        dic = {
            "on_MainWindow_destroy": gtk.main_quit,
            "on_ButtonQuit_clicked": gtk.main_quit,
            "on_ButtonOpen_clicked": self.Open,
            "on_ButtonPlane_clicked": self.ChangePlane,
            "on_change_Current": self.ChangeCurrent,
            "on_ButtonSave_clicked": self.SaveFigure
        }
        self.wTree.signal_autoconnect(dic)
        self.window = self.wTree.get_widget(self.windowname)

        self.XmaxIndicator = self.wTree.get_widget("LabelXMax")
        self.YmaxIndicator = self.wTree.get_widget("LabelYMax")
        self.ZmaxIndicator = self.wTree.get_widget("LabelZMax")

        self.XScaler = self.wTree.get_widget("ScaleX")
        self.YScaler = self.wTree.get_widget("ScaleY")
        self.ZScaler = self.wTree.get_widget("ScaleZ")

        self.XText = self.wTree.get_widget("EntryX")
        self.YText = self.wTree.get_widget("EntryY")
        self.ZText = self.wTree.get_widget("EntryZ")

        self.PlaneSwitcher = self.wTree.get_widget("ButtonPlane")
        self.PlaneIndicator = self.wTree.get_widget("LabelPlane")

        self.window.show()

        self.OpenFileName = os.getcwd()

        self.plane = "xy"
        self.lock = 0
        self.draw_lock = 0
        self.pa = None
        self.TitleOfPlots = []
        self.ax = []

        self.figure = Figure(figsize=(6, 6), dpi=72)
        self.figure.subplots_adjust(left=0.05,
                                    right=1.0,
                                    bottom=0.07,
                                    top=0.95,
                                    wspace=0.2,
                                    hspace=0.1)

        self.canvas = FigureCanvasGTKAgg(self.figure)  # a gtk.DrawingArea
        self.canvas.show()

        self.view = self.wTree.get_widget("ViewFrame")
        self.view.add(self.canvas)

    def DirectOpen(self, filename):
        self.OpenFileName = filename
        self.pa = PA.PA(file=self.OpenFileName)

        self.currentX = self.pa.nx() / 2
        self.currentY = self.pa.ny() / 2
        self.currentZ = self.pa.nz() / 2

        self.XmaxIndicator.set_text(str(self.pa.nx()))
        self.YmaxIndicator.set_text(str(self.pa.ny()))
        self.ZmaxIndicator.set_text(str(self.pa.nz()))

        self.XScaler.set_range(0.0, self.pa.nx())
        self.XScaler.set_value(self.currentX)
        self.YScaler.set_range(0.0, self.pa.ny())
        self.YScaler.set_value(self.currentY)
        self.ZScaler.set_range(0.0, self.pa.nz())
        self.ZScaler.set_value(self.currentZ)

        self.XText.set_text(str(self.currentX))
        self.YText.set_text(str(self.currentY))
        self.ZText.set_text(str(self.currentZ))

        self.DrawPicture(self.window)

    def Open(self, widget):
        # A SIMPLE FILE CHOOSE DIALOG
        dialog = gtk.FileChooserDialog("Please select your PA File...",
                                       self.window,
                                       gtk.FILE_CHOOSER_ACTION_OPEN, None,
                                       None)
        dialog.add_button("Cancel", gtk.RESPONSE_CANCEL)
        dialog.add_button("Select", gtk.RESPONSE_OK)
        if self.OpenFileName != os.getcwd():
            dialog.set_current_folder(os.path.split(self.OpenFileName)[0])
        else:
            dialog.set_current_folder(os.getcwd())
        result = dialog.run()
        if result == gtk.RESPONSE_OK:
            self.OpenFileName = dialog.get_filename()
            dialog.destroy()
        else:
            dialog.destroy()
            return 0

        # SO EVERYTHING GOOD, LETS OPEN THE FILE
        self.pa = PA.PA(file=self.OpenFileName)

        self.currentX = self.pa.nx() / 2
        self.currentY = self.pa.ny() / 2
        self.currentZ = self.pa.nz() / 2

        self.XmaxIndicator.set_text(str(self.pa.nx()))
        self.YmaxIndicator.set_text(str(self.pa.ny()))
        self.ZmaxIndicator.set_text(str(self.pa.nz()))

        self.XScaler.set_range(0.0, self.pa.nx())
        self.XScaler.set_value(self.currentX)
        self.YScaler.set_range(0.0, self.pa.ny())
        self.YScaler.set_value(self.currentY)
        self.ZScaler.set_range(0.0, self.pa.nz())
        self.ZScaler.set_value(self.currentZ)

        self.XText.set_text(str(self.currentX))
        self.YText.set_text(str(self.currentY))
        self.ZText.set_text(str(self.currentZ))

        self.DrawPicture(self.window)

    def DrawPicture_thread(self, widget):
        drawFigureThreat().start()

    def DrawPicture(self, widget):
        # Nothing open
        if self.pa == None:
            return 0

        self.wTree.get_widget("View").set_text(self.OpenFileName)
        # CHECK WHO WANTS TO BE PLOTTED?
        self.TitleOfPlots = []
        if self.wTree.get_widget("CheckRaw").get_active() == True:
            self.TitleOfPlots.append("Raw")
        if self.wTree.get_widget("CheckGeo").get_active() == True:
            self.TitleOfPlots.append("Geometry")
        if self.wTree.get_widget("CheckPot").get_active() == True:
            self.TitleOfPlots.append("Potential")

        # CLEAR FIGURE IS IMPORTANT!
        self.figure.clear()
        self.ax = []
        i = 0
        while i < len(self.TitleOfPlots):
            num = 100 + 10 * len(self.TitleOfPlots) + 1 + i
            self.ax.append(self.figure.add_subplot(num))
            if self.plane == "xy":
                self.ax[i].set_xlabel('Y')
                self.ax[i].set_ylabel('X')
            elif self.plane == "xz":
                self.ax[i].set_xlabel('Z')
                self.ax[i].set_ylabel('X')
            elif self.plane == "yz":
                self.ax[i].set_xlabel('Z')
                self.ax[i].set_ylabel('Y')
            self.ax[i].set_title(self.TitleOfPlots[i])
            i = i + 1
        data_raw = []
        data_geo = []
        data_pot = []
        if self.plane == "xy":
            i = 0
            while i < self.pa.nx():
                j = 0
                data_raw.append([])
                data_geo.append([])
                data_pot.append([])
                while j < self.pa.ny():
                    data_pot[i].append(self.pa.potential(i, j, self.currentZ))
                    data_geo[i].append(self.pa.electrode(i, j, self.currentZ))
                    data_raw[i].append(self.pa.raw(i, j, self.currentZ))
                    j = j + 1
                i = i + 1
        elif self.plane == "xz":
            i = 0
            while i < self.pa.nx():
                j = 0
                data_raw.append([])
                data_geo.append([])
                data_pot.append([])
                while j < self.pa.nz():
                    data_pot[i].append(self.pa.potential(i, self.currentY, j))
                    data_geo[i].append(self.pa.electrode(i, self.currentY, j))
                    data_raw[i].append(self.pa.raw(i, self.currentY, j))
                    j = j + 1
                i = i + 1
        elif self.plane == "yz":
            i = 0
            while i < self.pa.ny():
                j = 0
                data_raw.append([])
                data_geo.append([])
                data_pot.append([])
                while j < self.pa.nz():
                    data_pot[i].append(self.pa.potential(self.currentX, i, j))
                    data_geo[i].append(self.pa.electrode(self.currentX, i, j))
                    data_raw[i].append(self.pa.raw(self.currentX, i, j))
                    j = j + 1
                i = i + 1
        i = 0
        while i < len(self.TitleOfPlots):
            if self.TitleOfPlots[i] == "Raw":
                self.ax[i].imshow(data_raw)
                self.figure.colorbar(self.ax[i].imshow(data_raw),
                                     ax=self.ax[i],
                                     shrink=(1.1 -
                                             len(self.TitleOfPlots) / 10.0),
                                     pad=0.01)
            elif self.TitleOfPlots[i] == "Geometry":
                self.ax[i].imshow(data_geo)
                self.figure.colorbar(self.ax[i].imshow(data_geo),
                                     ax=self.ax[i],
                                     shrink=(1.1 -
                                             len(self.TitleOfPlots) / 10.0),
                                     pad=0.01)
            elif self.TitleOfPlots[i] == "Potential":
                self.ax[i].imshow(data_pot)
                self.figure.colorbar(self.ax[i].imshow(data_pot),
                                     ax=self.ax[i],
                                     shrink=(1.1 -
                                             len(self.TitleOfPlots) / 10.0),
                                     pad=0.01)

            i = i + 1
        self.canvas.draw()

    def ChangePlane(self, widget):
        if self.plane == "xy":
            self.plane = "xz"
            self.PlaneIndicator.set_text("XZ")
        elif self.plane == "xz":
            self.plane = "yz"
            self.PlaneIndicator.set_text("YZ")
        elif self.plane == "yz":
            self.plane = "xy"
            self.PlaneIndicator.set_text("XY")
        self.DrawPicture(self.window)

    def ChangeCurrent(self, widget):
        if self.lock == 1:
            return 0
        self.lock = 1
        if widget.get_name() == "ScaleX":
            self.currentX = int(self.XScaler.get_value())
        elif widget.get_name() == "ScaleY":
            self.currentY = int(self.YScaler.get_value())
        elif widget.get_name() == "ScaleZ":
            self.currentZ = int(self.ZScaler.get_value())


#		elif widget.get_name() == "CheckRaw" or widget.get_name() == "CheckGeo" or widget.get_name() == "CheckPot":

        else:
            self.currentX = int(float(self.XText.get_text()))
            self.currentY = int(float(self.YText.get_text()))
            self.currentZ = int(float(self.ZText.get_text()))
        self.XText.set_text(str(self.currentX))
        self.YText.set_text(str(self.currentY))
        self.ZText.set_text(str(self.currentZ))
        self.XScaler.set_value(self.currentX)
        self.YScaler.set_value(self.currentY)
        self.ZScaler.set_value(self.currentZ)
        self.DrawPicture(self.window)
        self.lock = 0

    def SaveFigure(self, widget):
        # A SIMPLE FILE CHOOSE DIALOG
        dialog = gtk.FileChooserDialog("Please select your PA File...",
                                       self.window,
                                       gtk.FILE_CHOOSER_ACTION_SAVE, None,
                                       None)
        dialog.add_button("Cancel", gtk.RESPONSE_CANCEL)
        dialog.add_button("Select", gtk.RESPONSE_OK)
        result = dialog.run()
        if result == gtk.RESPONSE_OK:
            FileName = dialog.get_filename()
            dialog.destroy()
        else:
            dialog.destroy()
            return 0
        self.figure.savefig((FileName + ".pdf"))
Example #53
0
class DoubleMyMplCanvas(FigureCanvas):
    def __init__(self, parent=None, width = 6, height = 5, dpi = 100, sharex = None, sharey = None):
        self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF')
        self.ax = self.fig.add_subplot(211, sharex = sharex, sharey = sharey)
        self.ax2 = self.fig.add_subplot(212, sharex = sharex, sharey = sharey)
        self.axList = [self.ax, self.ax2]
        self.fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9)
        self.plotTitle = ''
        self.xtitle="X"#"Drift Time (ms)"
        self.ytitle="Y"#"Intensity"
        self.ax.set_xlabel(self.xtitle, fontsize = 9)
        self.ax.set_ylabel(self.ytitle, fontsize = 9)
        self.grid_status = True
        self.xaxis_style = 'linear'
        self.yaxis_style = 'linear'
        self.format_labels()
        self.ax.hold(True)


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



    def format_labels(self, xItalic = False):
        for ax in self.axList:
            ax.set_title(self.plotTitle)
            ax.title.set_fontsize(10)
            xLabel = self.xtitle#self.ax.get_xlabel()
            yLabel = self.ytitle#self.ax.get_ylabel()
            if xItalic:
                ax.set_xlabel(xLabel, fontsize = 9, fontstyle = 'italic')
            else:
                ax.set_xlabel(xLabel, fontsize = 9)
            ax.set_ylabel(yLabel, fontsize = 9)
            labels_x = ax.get_xticklabels()
            labels_y = ax.get_yticklabels()

            for xlabel in labels_x:
                xlabel.set_fontsize(8)
            for ylabel in labels_y:
                ylabel.set_fontsize(8)
                ylabel.set_color('b')
            if ax.get_legend() != None:
                self.ax.legend(borderaxespad = 0.03, axespad=0.25)
                texts = ax.get_legend().get_texts()
                for text in texts:
                    text.set_fontsize(8)

    def sizeHint(self):
        w, h = self.get_width_height()
        return QtCore.QSize(w, h)

    def minimumSizeHint(self):
        return QtCore.QSize(10, 10)

    def sizeHint(self):
        w, h = self.get_width_height()
        return QtCore.QSize(w, h)

    def minimumSizeHint(self):
        return QtCore.QSize(10, 10)
Example #54
0
class Mplot(FCanvas):
    def __init__(self, parent, B=[]):
        self.parent = parent
        self.deph = parent.deph.value()
        self.w = parent.Width.value() - 200
        self.h = parent.Height.value()

        self.a = float(parent.a.text())
        self.c = float(parent.c.text())
        self.b = round(
            float((self.c - self.a) / 2 * self.h / self.w) +
            float(parent.d.text()), 6)
        self.d = round(
            -float((self.c - self.a) / 2 * self.h / self.w) +
            float(parent.d.text()), 6)

        self.D = [self.a, self.b]
        self.B = B
        self.colorMap = parent.CMap.currentText()

        self.const = complex(float(self.parent.const_re.text()),
                             float(self.parent.const_im.text()))
        ###
        self.fig = Figure(figsize=(self.w, self.h), dpi=1)

        FCanvas.__init__(self, self.fig)
        self.setParent(parent)

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

        self.plot()

    def plot(self):
        if len(self.B) == 0:
            global c
            c = self.const
            exec(
                '''global F, G
F = lambda z,w:''' + self.parent.func.text() + '''
G = lambda z,w:''' + self.parent.func2.text(), globals(), locals())

            A1 = np.linspace(self.a, self.c, self.w)
            A2 = np.linspace(self.d, self.b, self.h)

            A = np.array([[complex(i, e) for i in A1] for e in A2])

            self.B = np.array([[0 for i in range(self.w)]
                               for e in range(self.h)])

            for i in range(len(A)):
                for e in range(len(A[i])):
                    N = A[i][e]
                    M = A[i][e]  #self.const
                    for j in range(self.deph):
                        N, M = F(N, M), G(N, M)
                        if abs(N) > 5:
                            break
                    self.B[i][e] = j  #abs(N)

        self.fig.subplots_adjust(left=0, right=1.0, top=1.0, bottom=0)
        ax = self.fig.add_subplot(111)
        ax.axis('scaled')
        ax.axis([0, self.w, 0, self.h])
        ax.xaxis.set_major_formatter(plt.NullFormatter())
        ax.yaxis.set_major_formatter(plt.NullFormatter())
        ax.imshow(self.B, cmap=self.colorMap)

        self.show()

    def mousePressEvent(self, event):
        if self.parent.i:
            self.a = round(
                (self.c - self.a) * event.pos().x() / self.w + self.a, 6)
            self.b = round(
                (self.d - self.b) * event.pos().y() / self.h + self.b, 6)

    def mouseReleaseEvent(self, event):
        if self.parent.i:
            self.c = round(
                (self.c - self.D[0]) * event.pos().x() / self.w + self.D[0], 6)
            self.d = round(
                (self.d - self.D[1]) * event.pos().y() / self.h + self.D[1], 6)
            self.parent.find(self.a, self.b, self.c, self.d)
            self.parent.i = False
Example #55
0
class simpleapp_tk(tkinter.Tk):
    def __init__(self, parent):
        tkinter.Tk.__init__(self, parent)

        self.parent = parent

        if USE_EMULATION:
            self.inst = keithley_2450_fake()
        else:
            self.inst = keithley_2450()
        self.data = data()

        col = self.winfo_rgb(self.cget('bg'))
        self.bgcolor = (float(col[0]) / 65536, float(col[1]) / 65536,
                        float(col[2]) / 65536)

        self.waitingOnImport = 0

        self.selectWindow = None

        self.ConnectToDB()
        self.initialize()

    def initialize(self):
        self.grid()

        #cretae menu bar
        self.menubar = tkinter.Menu(self)
        filemenu = tkinter.Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.OnMenuOpen)
        filemenu.add_command(label="Save", command=self.OnMenuSave)
        filemenu.add_separator()
        filemenu.add_command(label="Print", command=self.OnMenuPrint)
        filemenu.add_separator()
        filemenu.add_command(label="Quit", command=self.OnMenuQuit)
        self.menubar.add_cascade(label="File", menu=filemenu)
        self.config(menu=self.menubar)

        # create the entry boxes
        FrameEntry = tkinter.Frame(self)
        FrameScan = tkinter.Frame(FrameEntry)
        FrameDevice = tkinter.Frame(FrameEntry)

        self.CreateScanLabel(FrameScan)
        self.CreateDeviceLabel(FrameDevice)

        self.entryVariableV0.set(self.inst.parV0)
        self.entryVariableV1.set(self.inst.parV1)
        self.entryVariableST.set(self.inst.parST)
        self.entryVariableDT.set(self.inst.parDT)
        self.entryVariableUS.set(self.data.userName)
        self.entryVariableSI.set(self.data.sipmID)
        self.entryVariableTE.set(self.data.temperature)
        self.UpdateDate()

        FrameDevice.grid(column=0, row=0, padx=10, pady=20, sticky='EW')
        FrameScan.grid(column=0, row=1, padx=10, pady=20, sticky='EW')

        #create the plotter
        FramePlot = tkinter.Frame(self)
        self.CreatePlotter(FramePlot)

        # create the buttons
        FrameButton = tkinter.Frame(self)
        self.CreateButtons(FrameButton)

        # create the logger
        FrameLogger = tkinter.Frame(self)
        self.CreateLogger(FrameLogger)

        #create frame import
        FrameImport = tkinter.Frame(self)
        self.CreateImportList(FrameImport)

        #place frames, try to make it look nice
        fillLabel = tkinter.Label(self, text=" ", height=2)
        fillLabel2 = tkinter.Label(self, text=" ", width=20)
        FrameEntry.grid(column=0, row=0, padx=10, pady=10, sticky='EW')
        FramePlot.grid(column=1,
                       row=0,
                       sticky='EW',
                       padx=10,
                       pady=10,
                       rowspan=2)
        fillLabel.grid(column=0, row=1)
        FrameButton.grid(column=0,
                         row=2,
                         sticky='EW',
                         padx=10,
                         pady=10,
                         columnspan=2)
        FrameLogger.grid(column=0,
                         row=3,
                         sticky='EW',
                         padx=10,
                         pady=5,
                         columnspan=2)
        fillLabel2.grid(column=3, row=0)
        FrameImport.grid(column=4,
                         row=0,
                         sticky='EW',
                         padx=10,
                         pady=5,
                         rowspan=4)

        self.grid_columnconfigure(0, weight=1)
        self.resizable(False, False)
        self.update()
        self.geometry(self.geometry())

    #---------------------------------------------------------------------------------
    def OnMenuOpen(self):
        filename = None
        if USING_PYTHON_3:
            filename = tkinter.filedialog.askopenfilename(
                initialdir=os.getcwd(),
                title="Select file",
                filetypes=(("text files", "*.txt"), ("all files", "*.*")))
        else:
            filename = tkFileDialog.askopenfilename(
                initialdir=os.getcwd(),
                title="Select file",
                filetypes=(("text files", "*.txt"), ("all files", "*.*")))
        if (self.data.read(filename, self.inst) == 0):
            self.EmitLogText("Error: Could not read " + filename)
            return

        self.entryVariableV0.set(self.inst.parV0)
        self.entryVariableV1.set(self.inst.parV1)
        self.entryVariableST.set(self.inst.parST)
        self.entryVariableDT.set(self.inst.parDT)
        self.entryVariableSI.set(self.data.sipmID)
        self.entryVariableUS.set(self.data.userName)
        self.entryVariableTE.set(self.data.temperature)
        self.entryVariableDA.set(self.data.date)
        self.data.hasData = 1
        self.RefreshPlot()
        self.EmitLogText("Loaded content of " + filename)

    def OnMenuSave(self):

        self.RefreshParams()
        self.RefreshPlot()

        if (self.ValidateSaveData() == 0): return

        filename = None
        if USING_PYTHON_3:
            filename = tkinter.filedialog.asksaveasfilename(
                initialdir=os.getcwd(),
                title="Select file",
                filetypes=(("text files", "*.txt"), ("all files", "*.*")))
        else:
            filename = tkFileDialog.asksaveasfilename(
                initialdir=os.getcwd(),
                title="Select file",
                filetypes=(("text files", "*.txt"), ("all files", "*.*")))
        result = self.data.write(filename, self.inst)
        if (result == 0):
            self.EmitLogText("Error: Problem saving file " + filename +
                             ". Try again")
        self.EmitLogText("Saved into file " + filename)

    def OnMenuPrint(self):
        filename = None
        if USING_PYTHON_3:
            filename = tkinter.filedialog.asksaveasfilename(
                initialdir=os.getcwd(),
                title="Select file",
                filetypes=(("pdf files", "*.pdf"), ("all files", "*.*")))
        else:
            filename = tkFileDialog.asksaveasfilename(
                initialdir=os.getcwd(),
                title="Select file",
                filetypes=(("pdf files", "*.pdf"), ("all files", "*.*")))
        self.figure.savefig(filename)
        self.EmitLogText("Printed plot into file " + filename)

    def OnMenuQuit(self):
        global app
        self.inst.disconnect()
        app.destroy()

    #---------------------------------------------------------------------------------
    def CreateDeviceLabel(self, frame):
        label0 = tkinter.Label(frame, text="Device", font="bold", height=2)
        self.entryVariableTE = tkinter.StringVar()
        self.entryVariableUS = tkinter.StringVar()
        self.entryVariableSI = tkinter.StringVar()
        self.entryVariableDA = tkinter.StringVar()

        self.labelUS = tkinter.Label(frame, text="User name")
        self.labelSI = tkinter.Label(frame, text="Device ID")
        self.labelTE = tkinter.Label(frame, text="Temperature [C]")
        self.labelDA = tkinter.Label(frame, text="Date")

        self.entryUS = tkinter.Entry(frame,
                                     width=10,
                                     textvariable=self.entryVariableUS)
        self.entrySI = tkinter.Entry(frame,
                                     width=10,
                                     textvariable=self.entryVariableSI)
        self.entryTE = tkinter.Entry(frame,
                                     width=10,
                                     textvariable=self.entryVariableTE)
        self.entryDA = tkinter.Label(frame, textvariable=self.entryVariableDA)

        label0.grid(
            column=0,
            row=0,
            sticky='W',
            columnspan=2,
        )
        self.FinalizeEntryLabel(self.labelUS, self.entryUS, 1,
                                self.OnValidateUS)
        self.FinalizeEntryLabel(self.labelSI, self.entrySI, 2,
                                self.OnValidateSI)
        self.FinalizeEntryLabel(self.labelTE, self.entryTE, 3,
                                self.OnValidateTE)
        self.labelDA.grid(column=0, row=4, sticky='E', padx=5)
        self.entryDA.grid(column=1, row=4, sticky='EW', padx=5)

    def CreateScanLabel(self, frame):
        label0 = tkinter.Label(frame,
                               text="Scan parameters",
                               font="bold",
                               height=2)
        self.entryVariableV0 = tkinter.StringVar()
        self.entryVariableV1 = tkinter.StringVar()
        self.entryVariableST = tkinter.StringVar()
        self.entryVariableDT = tkinter.StringVar()
        self.entryVariableTE = tkinter.StringVar()

        self.labelV0 = tkinter.Label(frame, text="V0 [V]")
        self.labelV1 = tkinter.Label(frame, text="V1 [V]")
        self.labelST = tkinter.Label(frame, text="# Step")
        self.labelDT = tkinter.Label(frame, text="dT [s]")

        self.entryV0 = tkinter.Entry(frame,
                                     width=10,
                                     textvariable=self.entryVariableV0)
        self.entryV1 = tkinter.Entry(frame,
                                     width=10,
                                     textvariable=self.entryVariableV1)
        self.entryST = tkinter.Entry(frame,
                                     width=10,
                                     textvariable=self.entryVariableST)
        self.entryDT = tkinter.Entry(frame,
                                     width=10,
                                     textvariable=self.entryVariableDT)

        label0.grid(column=0, row=0, sticky='W', columnspan=2)
        self.FinalizeEntryLabel(self.labelV0, self.entryV0, 1,
                                self.OnValidateV0)
        self.FinalizeEntryLabel(self.labelV1, self.entryV1, 2,
                                self.OnValidateV1)
        self.FinalizeEntryLabel(self.labelST, self.entryST, 3,
                                self.OnValidateST)
        self.FinalizeEntryLabel(self.labelDT, self.entryDT, 4,
                                self.OnValidateDT)

    def FinalizeEntryLabel(self, label, entry, irow, cmd):
        label.grid(column=0, row=irow, sticky='E', padx=5)
        entry.grid(column=1, row=irow, sticky='EW', padx=5)
        entry.bind("<Return>", cmd)

    def OnValidateV0(self, event):
        #self.inst.parV0 = self.ValidateParInt(self.entryVariableV0, self.inst.parV0, 0, min(self.inst.Vmax,self.inst.parV1), "V0")
        self.inst.parV0 = self.ValidateParFloat(
            self.entryVariableV0, self.inst.parV0, 0,
            min(self.inst.Vmax, self.inst.parV1), "V0")

    def OnValidateV1(self, event):
        #self.inst.parV1 = self.ValidateParInt(self.entryVariableV1, self.inst.parV1, max(0,self.inst.parV0), self.inst.Vmax, "V1")
        self.inst.parV1 = self.ValidateParFloat(self.entryVariableV1,
                                                self.inst.parV1,
                                                max(0, self.inst.parV0),
                                                self.inst.Vmax, "V1")

    def OnValidateST(self, event):
        self.inst.parST = self.ValidateParInt(self.entryVariableST,
                                              self.inst.parST, 1,
                                              self.inst.STmax, "STEP")

    def OnValidateDT(self, event):
        self.inst.parDT = self.ValidateParFloat(self.entryVariableDT,
                                                self.inst.parDT,
                                                self.inst.DTmin,
                                                self.inst.DTmax, "DT")

    def OnValidateUS(self, event):
        self.data.userName = self.entryVariableUS.get()
        self.EmitLogText("set user name to " + self.data.userName)

    def OnValidateSI(self, event):
        self.data.sipmID = self.entryVariableSI.get()
        self.EmitLogText("set device ID to " + self.data.sipmID)

    def OnValidateTE(self, event):
        self.data.temperature = self.ValidateParFloat(self.entryVariableTE,
                                                      self.data.temperature,
                                                      -100.0, 100.0,
                                                      "Temperature")

    #---------------------------------------------------------------------------------
    def CreatePlotter(self, frame):
        self.figure = Figure(figsize=(5, 5), dpi=100, facecolor=self.bgcolor)
        self.figure.subplots_adjust(left=0.2)
        self.figure.subplots_adjust(bottom=0.2)
        self.plotter = self.figure.add_subplot(111)
        self.plotter.plot(self.data.I, self.data.V)
        self.plotter.set_xlabel("V [V]")
        self.plotter.set_ylabel("I [A]")
        self.figure.suptitle("I-V curve for " + self.data.sipmID,
                             fontsize=14,
                             fontweight='bold')
        self.canvasFig = FigureCanvasTkAgg(self.figure, master=frame)
        self.canvasFig.show()
        self.canvasFig.get_tk_widget().grid(column=0, row=2)

    #---------------------------------------------------------------------------------
    def CreateButtons(self, frame):
        self.buttonConnect = tkinter.Button(frame,
                                            text=u"Connect",
                                            font='bold',
                                            command=self.OnButtonConnect)
        self.buttonDisconnect = tkinter.Button(frame,
                                               state="disabled",
                                               text=u"Disconnect",
                                               font='bold',
                                               command=self.OnButtonDisconnect)
        self.buttonMeasure = tkinter.Button(frame,
                                            state="disabled",
                                            text=u"Measure",
                                            font='bold',
                                            command=self.OnButtonMeasure)

        self.buttonConnect.grid(column=0, row=0, padx=10)
        self.buttonDisconnect.grid(column=1, row=0, padx=10)
        self.buttonMeasure.grid(column=2, row=0, padx=10)

    def OnButtonConnect(self):
        if (self.inst.connect() == 1):
            self.label.configure(bg="green")
            self.labelVariable.set("Connected to " + self.inst.name)
            self.buttonConnect.configure(state="disabled")
            self.buttonDisconnect.configure(state="active")
            self.buttonMeasure.configure(state="active")
        self.EmitLogText(self.inst.logMessage)

    def OnButtonDisconnect(self):
        self.inst.disconnect()
        self.label.configure(bg="red")
        self.labelVariable.set("Disconnected")
        self.buttonConnect.configure(state="active")
        self.buttonDisconnect.configure(state="disabled")
        self.buttonMeasure.configure(state="disabled")
        self.buttonImport.configure(state="disabled")

    def OnButtonMeasure(self):
        if (self.inst.checkConnection() == 1):
            self.RefreshParams()
            self.inst.measureIV(self.data)
            self.data.hasData = 1
            self.buttonExport.configure(state="active")
            self.RefreshPlot()
            self.UpdateDate()
        else:
            self.OnButtonDisconnect()
            self.EmitLogText(self.inst.logMessage)

    #---------------------------------------------------------------------------------
    def CreateImportList(self, frame):
        label0 = tkinter.Label(frame,
                               text="Measurements",
                               font="bold",
                               height=2)
        label0.grid(column=0, row=0, sticky='W')

        self.scroller2 = tkinter.Scrollbar(frame)
        self.scroller2.grid(column=2, row=1, sticky='ns')

        self.listImport = tkinter.Listbox(frame,
                                          height=25,
                                          width=50,
                                          yscrollcommand=self.scroller2.set)
        self.scroller.config(command=self.listImport.yview)
        self.listImport.grid(column=0, row=1, sticky='EW')

        FrameButton = tkinter.Frame(frame)

        self.entryVariableFilterSI = tkinter.StringVar()
        self.entryVariableFilterUS = tkinter.StringVar()
        self.labelFSI = tkinter.Label(FrameButton, text="Sipm ID filter: ")
        self.labelFUS = tkinter.Label(FrameButton, text="User filter: ")
        self.entryFSI = tkinter.Entry(FrameButton,
                                      width=10,
                                      textvariable=self.entryVariableFilterSI)
        self.entryFUS = tkinter.Entry(FrameButton,
                                      width=10,
                                      textvariable=self.entryVariableFilterUS)

        self.buttonExport = tkinter.Button(FrameButton,
                                           state="disabled",
                                           text=u"Export",
                                           font='bold',
                                           command=self.OnButtonExport)
        self.buttonImport = tkinter.Button(FrameButton,
                                           state="disabled",
                                           text=u"Import",
                                           font='bold',
                                           command=self.OnButtonImport)
        self.buttonFilter = tkinter.Button(FrameButton,
                                           state="disabled",
                                           text=u"Filter",
                                           font='bold',
                                           command=self.OnButtonFilter)

        self.labelFSI.grid(column=0, row=1, padx=10, pady=20, sticky='EW')
        self.entryFSI.grid(column=1, row=1, padx=10, pady=20, sticky='EW')
        self.labelFUS.grid(column=0, row=2, padx=10, sticky='EW')
        self.entryFUS.grid(column=1, row=2, padx=10, sticky='EW')

        self.buttonImport.grid(column=0, row=0, padx=10, sticky='EW')
        self.buttonExport.grid(column=1, row=0, padx=10, sticky='EW')
        self.buttonFilter.grid(column=2, row=0, padx=10, sticky='EW')
        FrameButton.grid(column=0, row=2, pady=20, sticky='EW')

        self.listImport.bind("<Return>", self.HandleListboxReturnKey)

        self.GenerateImportList()

    def OnButtonExport(self):
        self.RefreshParams()
        self.RefreshPlot()
        valid = self.ValidateSaveData()

        if valid == 0:
            self.EmitLogText("ERROR: Cannot export data (Missing data)")
            return

        if self.connectedToDB == 0:
            self.EmitLogText(
                "ERROR: Cannot export data (Not connected to database)")
            return

        self.EmitLogText('Exporting data to DB')
        self.WriteEntry()

    def OnButtonImport(self):
        if self.waitingOnImport != 0:
            self.EmitLogText("ERROR: Already waiting for import selection")
            return 0

        if self.connectedToDB != 1:
            self.EmitLogText(
                "ERROR: Cannot import data (Not connected to database)")
            return 0

        if (self.listImport.curselection()):
            self.ImportSingleEntry(
                self.listImport.get(self.listImport.curselection()))

    def OnButtonFilter(self):
        importSipmID = self.entryVariableFilterSI.get()
        importUser = self.entryVariableFilterUS.get()
        self.GenerateImportList(importSipmID, importUser)

    def HandleListboxReturnKey(self, event):
        if (self.buttonImport.cget("state") == "active"):
            self.buttonImport.invoke()

    def GenerateImportList(self, importSipmID="", importUser=""):
        self.listImport.delete(0, tkinter.END)

        try:
            session = self.Session()

            if (importSipmID == "" and importUser == ""):
                importList = session.query(Entry).all()
            if (importSipmID != "" and importUser != ""):
                importList = session.query(Entry).filter_by(
                    sipmid=importSipmID, username=importUser)
            if (importSipmID == "" and importUser != ""):
                importList = session.query(Entry).filter_by(
                    username=importUser)
            if (importSipmID != "" and importUser == ""):
                importList = session.query(Entry).filter_by(
                    sipmid=importSipmID)

            entryNum = 1
            for curEntry in importList:
                self.listImport.insert(
                    entryNum, curEntry.date + " | " + curEntry.sipmid + " | " +
                    curEntry.username)
                entryNum += 1

            self.buttonImport.configure(state="disabled")
            if (entryNum > 1):
                self.listImport.select_set(0)
                self.buttonImport.configure(state="active")
                self.buttonFilter.configure(state="active")

        except:
            session.rollback()
            self.EmitLogText("ERROR: Communication problem with SQL database")
            raise

        finally:
            session.close()

    def ImportSingleEntry(self, selectionString):
        importDate = selectionString.split("|")[0].strip()
        importSipmID = selectionString.split("|")[1].strip()

        if self.connectedToDB != 1:
            self.EmitLogText(
                "ERROR: Cannot import data (Not connected to database)")
            return 0

        try:
            session = self.Session()

            our_entry = session.query(Entry).filter_by(
                sipmid=importSipmID, date=importDate).first()

            if our_entry == None:
                self.EmitLogText("ERROR: Cannot import data (Entry not found)")
                return 0

            self.data.userName = our_entry.username
            self.data.sipmID = our_entry.sipmid
            self.data.temperature = our_entry.temperature
            self.data.date = our_entry.date
            self.inst.parV0 = our_entry.v0
            self.inst.parV1 = our_entry.v1
            self.inst.parST = our_entry.steps
            self.inst.parDT = our_entry.deltat
            self.data.V = our_entry.varray
            self.data.I = our_entry.iarray

            self.entryVariableV0.set(self.inst.parV0)
            self.entryVariableV1.set(self.inst.parV1)
            self.entryVariableST.set(self.inst.parST)
            self.entryVariableDT.set(self.inst.parDT)
            self.entryVariableSI.set(self.data.sipmID)
            self.entryVariableUS.set(self.data.userName)
            self.entryVariableTE.set(self.data.temperature)
            self.entryVariableDA.set(self.data.date)
            self.data.hasData = 1
            self.RefreshPlot()
            self.EmitLogText('Successfully imported device \"' +
                             self.data.sipmID + '\" from DB')

        except:
            session.rollback()
            self.EmitLogText("ERROR: Communication problem with SQL database")
            raise
        finally:
            session.close()

        return

    def WriteEntry(self):
        try:
            session = self.Session()

            query_entry = session.query(Entry).filter_by(
                sipmid=self.data.sipmID, date=self.data.date).first()
            if query_entry != None:
                self.EmitLogText("Replacing existing entry...")
                session.delete(query_entry)
                session.commit()

            new_entry = Entry(username=str(self.data.userName),
                              sipmid=str(self.data.sipmID),
                              temperature=float(self.data.temperature),
                              date=str(self.data.date),
                              v0=float(self.inst.parV0),
                              v1=float(self.inst.parV1),
                              steps=int(self.inst.parST),
                              deltat=float(self.inst.parDT),
                              varray=self.data.V,
                              iarray=self.data.I)

            session.add(new_entry)
            session.commit()

            our_entry = session.query(Entry).filter_by(
                sipmid=self.data.sipmID).first()
            if our_entry == None:
                self.EmitLogText("ERROR: Could not export to DB")
                return 0

            self.EmitLogText("New Entry: " + our_entry.__repr__())

            entries = session.query(Entry).all()
            self.EmitLogText("Number of entries in DB: " + str(len(entries)))
            self.GenerateImportList()

        except:
            session.rollback()
            self.EmitLogText("ERROR: Could not export to DB")
            raise
        finally:
            session.close()
            return 1

    #---------------------------------------------------------------------------------
    def CreateLogger(self, frame):
        self.labelVariable = tkinter.StringVar()
        self.labelColor = tkinter.StringVar()
        self.labelColor.set("red")
        self.labelVariable.set(u"Not connected")
        self.label = tkinter.Label(frame,
                                   textvariable=self.labelVariable,
                                   anchor="w",
                                   fg="white",
                                   bg=self.labelColor.get())
        self.label.grid(column=0, row=0, sticky='EW', pady=5)

        self.scroller = tkinter.Scrollbar(frame)
        self.scroller.grid(column=2, row=1, sticky='ns')
        self.logtext = tkinter.Text(frame,
                                    height=5,
                                    yscrollcommand=self.scroller.set)
        self.scroller.config(command=self.logtext.yview)
        self.logtext.insert(tkinter.INSERT, "Good day\n")
        self.logtext.configure(state="disabled")
        self.logtext.grid(column=0, row=1, sticky='EW')

    #---------------------------------------------------------------------------------
    def ConnectToDB(self):

        self.engine = None
        self.Session = None
        self.connectedToDB = 0

        try:
            if CONNECT_TO_REAL_DB:
                pw = DB_PASSWORD
                self.engine = create_engine(
                    'mysql+mysqldb://root:' + pw + '@localhost/' + DB_NAME +
                    '?unix_socket=//opt/local/var/run/mysql56/mysqld.sock',
                    echo=ECHO_SQL_COMMANDS)
            else:
                self.engine = create_engine('sqlite:///:memory:',
                                            echo=ECHO_SQL_COMMANDS)
            Base.metadata.create_all(self.engine)
            self.Session = sessionmaker(bind=self.engine)
            self.connectedToDB = 1
            print("Connected to DB")
            return 1
        except:
            return 0

    def UpdateDate(self):
        now = datetime.datetime.now()
        self.data.date = "%s-%s-%s %s:%s:%s" % (
            now.year, now.month, now.day, now.hour, now.minute, now.second)
        self.entryVariableDA.set(self.data.date)

    def RefreshParams(self):
        self.inst.parV0 = float(self.entryVariableV0.get())
        self.inst.parV1 = float(self.entryVariableV1.get())
        self.inst.parST = int(self.entryVariableST.get())
        self.inst.parDT = float(self.entryVariableDT.get())
        self.data.sipmID = self.entryVariableSI.get()
        self.data.userName = self.entryVariableUS.get()
        self.data.temperature = float(self.entryVariableTE.get())

    def RefreshPlot(self):
        self.plotter.clear()
        self.finterp = interp1d(self.data.V, self.data.I, kind='cubic')
        xnew = np.linspace(self.data.V[0],
                           self.data.V[-1],
                           num=max(self.inst.parST, 100),
                           endpoint=True)
        self.plotter.plot(self.data.V, self.data.I, 'o', xnew,
                          self.finterp(xnew), '-')
        #self.plotter.plot(self.data.V,self.data.I)
        self.plotter.set_xlabel("V [V]")
        self.plotter.set_ylabel("I [A]")
        self.figure.suptitle("I-V curve for " + self.data.sipmID,
                             fontsize=14,
                             fontweight='bold')

        self.canvasFig.draw()

    def EmitLogText(self, text):
        self.logtext.config(state='normal')
        self.logtext.insert(tkinter.END, text + "\n")
        self.logtext.see(tkinter.END)
        self.logtext.config(state='disabled')

    def ValidateParInt(self, entryVar, oldPar, bound0, bound1, parName):
        try:
            par = int(entryVar.get())
            if (par < bound0 or par > bound1): raise ValueError
            self.EmitLogText("set " + parName + " to " + str(par))
            return par

        except ValueError:
            self.EmitLogText("Error: " + parName + " must be in the range " +
                             str(bound0) + "....." + str(bound1))
            entryVar.set(oldPar)
            return oldPar

    def ValidateParFloat(self, entryVar, oldPar, bound0, bound1, parName):
        try:
            par = float(entryVar.get())
            if (par < bound0 or par > bound1): raise ValueError
            self.EmitLogText("set " + parName + " to " + str(par))
            return par

        except ValueError:
            self.EmitLogText("Error: " + parName + " must be in the range " +
                             str(bound0) + ".." + str(bound1))
            entryVar.set(oldPar)
            return oldPar

    def ValidateSaveData(self):
        if (self.data.userName == ""):
            self.EmitLogText(
                "Error: Username missing, so we know who to blame later...")
            return 0

        if (self.data.sipmID == ""):
            self.EmitLogText("Error: device ID missing")
            return 0

        if (self.data.hasData == 0):
            self.EmitLogText("Error: No measurement available")
            return 0

        return 1
Example #56
0
class Advanced2dCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width=6, height=6, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9)
        super().__init__(self.fig)
        self.fig.canvas.setFocusPolicy(Qt.ClickFocus)
        self.fig.canvas.setFocus()

    def _imshow(self, imgs, scale=0, normalization=0, name=''):
        self.fig.clf()
        ax_num = len(imgs)
        # set a primary image
        img = imgs[-1]
        #self.ax.cla()

        if scale == 0:
            # Linear.. nothing happened
            #scaled2d = self.flux2d.copy()
            scaled2d = img.copy()
        elif scale == 1:
            # log transformation.. scaled = log(1+ img)/log(1+img_max)
            #if self.flux2d.min() < 0:
            #	scaled2d = np.log(-self.flux2d.min() + self.flux2d) / np.log(-self.flux2d.min() + self.flux2d.max())
            if img.min() < 0:
                scaled2d = np.log(-img.min() + img) / np.log(-img.min() +
                                                             img.max())
            else:
                #scaled2d = np.log(1 + self.flux2d) / np.log(1 + self.flux2d.max())
                scaled2d = np.log(1 + img) / np.log(1 + img.max())
        elif scale == 2:
            # square root transformation..
            # pixel values > 0 ==> regular sqrt; pixel values <0 ==> 1.absolute value 2.sqrt 3.add minus sign
            #scaled2d = copy.deepcopy(self.flux2d)
            scaled2d = copy.deepcopy(img)
            scaled2d[scaled2d >= 0] = np.sqrt(scaled2d[scaled2d >= 0])
            scaled2d[scaled2d < 0] = -np.sqrt(-scaled2d[scaled2d < 0])
        elif scale == 3:
            #scaled2d = self.flux2d**2
            scaled2d = img**2

        # normalization next
        # send scaling limits back to toolbar
        if type(normalization) is int:
            #print(scaled2d)
            if normalization == 0:
                pass
                #self.send_scale_limits.emit([scaled2d.min(), scaled2d.max()])
            elif normalization == 1:
                # minmax 100% range
                scaled2d = (scaled2d - scaled2d.min()) / (scaled2d.max() -
                                                          scaled2d.min())
            elif normalization < 10:  # this magic num from n_combobox in toolbar
                if normalization == 2:  # 99.5%
                    low, up = np.percentile(scaled2d, [0.25, 99.75])
                elif normalization == 3:  # 99%
                    low, up = np.percentile(scaled2d, [0.5, 99.5])
                elif normalization == 4:  # 98%
                    low, up = np.percentile(scaled2d, [1., 99.])
                elif normalization == 5:  # 97%
                    low, up = np.percentile(scaled2d, [1.5, 98.5])
                elif normalization == 6:  # 96%
                    low, up = np.percentile(scaled2d, [2., 98.])
                elif normalization == 7:  # 95%
                    low, up = np.percentile(scaled2d, [2.5, 97.5])
                elif normalization == 8:  # 92.5%
                    low, up = np.percentile(scaled2d, [3.75, 96.25])
                elif normalization == 9:  # 90%
                    low, up = np.percentile(scaled2d, [5., 95.])

                scaled2d = (scaled2d - low) / (up - low)

            elif normalization == 10:  # Z-score
                scaled2d = (scaled2d - scaled2d.mean()) / scaled2d.std()

        elif type(normalization) == list:
            tmp = (scaled2d - scaled2d.min()) / (scaled2d.max() -
                                                 scaled2d.min())
            scaled2d = tmp * (normalization[1] -
                              normalization[0]) + normalization[0]

        if 'STAMP' not in name:
            self.ax = self.fig.add_subplot(ax_num, 1, 1)  # flux
            self.ax.imshow(imgs[0],
                           origin='lower',
                           vmin=imgs[0].min(),
                           vmax=imgs[0].max())
            self.ax.set_title(name[0] + ' of Current Object')
            self.ax.tick_params(labelbottom=False)

            ax_add = [self.ax]
            for i in range(1, ax_num):
                ax_add.append(
                    self.fig.add_subplot(ax_num, 1, i + 1, sharex=self.ax))
                if i + 1 == ax_num:
                    if scale == 1:
                        cax = ax_add[-1].imshow(img,
                                                origin='lower',
                                                vmin=scaled2d.min(),
                                                vmax=scaled2d.max() * 0.01)
                    else:
                        cax = ax_add[-1].imshow(img,
                                                origin='lower',
                                                vmin=scaled2d.min(),
                                                vmax=scaled2d.max())
                    ax_cb = self.fig.colorbar(cax,
                                              ax=ax_add[-1],
                                              location='bottom')
                    ax_add[-1].tick_params(labelbottom=True)
                else:
                    ax_add[-1].imshow(imgs[i],
                                      origin='lower',
                                      vmin=imgs[i].min(),
                                      vmax=imgs[i].max())
                    ax_add[-1].tick_params(labelbottom=False)

                ax_add[-1].set_title(name[i] + ' of Current Object')
                ax_add[-1].set_aspect('auto')

        else:
            if len(imgs) > 1:
                wcs = imgs[0]
                self.ax = self.fig.add_subplot(1, 1, 1, projection=wcs)
                self.ax.set_xlabel('RA')
                self.ax.set_ylabel('DEC')
            else:
                self.ax = self.fig.add_subplot(1, 1, 1)
            self.ax.imshow(img,
                           origin='lower',
                           vmin=scaled2d.min(),
                           vmax=scaled2d.max())
            if len(name) > 1:
                self.ax.set_title(name + ' of Current Object')

        ax_xlim = self.ax.get_xlim()
        self.ax.set_aspect('auto')
        #self.ax2d.set_xlim(xlim_spec1d)
        #self.fig.tight_layout()

        self.draw()

        return [scaled2d.min(), scaled2d.max()]
Example #57
0
    def __init__(self,parent):
        Tk.Frame.__init__(self,parent)
        fig = Figure(figsize=(7, 7), dpi=100)
        fig.subplots_adjust(left=0.01, bottom=0.01, right=0.99, top=0.99)
        self.mainplot = fig.add_subplot(111,aspect=1)

        self.mainplot.set_xticks([])
        self.mainplot.set_yticks([])

        self.vsfreq_curves=[]
        self.curves=[]
        self.dots=[]

        PlotSmith(self.mainplot)

        parent.bind('<Up>',self.test)

        self.settings={'centerfreq':2.0e9,
                       'lowerfreq':1.5e9,
                       'upperfreq':2.5e9,
                       'stepsize':0.1e9,
                       'SmithImpedance':50.0,
                       'InputImpedance':50,
                       'LoadImpedance':50}

        #Menu
        menu=Tk.Menu(self.master)
        self.master.config(menu=menu)
        File=Tk.Menu(menu)
        menu.add_cascade(label="File",menu=File)
        menu.add_cascade(label="Plotting",menu=File)
        menu.add_cascade(label="Settings",menu=File)
        menu.add_cascade(label="Help",menu=File)
        
        #SLIDER FRAME
        Slider_Frame=Tk.Frame(root)
        Slider_Frame.grid(row=0,column=0,sticky=Tk.S)
        
        slider_canvas=Tk.Canvas(Slider_Frame)
        slider=SliderFrame(slider_canvas,self.callback)

        #COMPONENT CONTROL BUTTON FRAMES (i.e. delete, edit)
        CmpCntrl = Tk.Frame()
        CmpCntrl.grid(row=1,column=0,padx=5,pady=10,sticky=Tk.S)
        button_del=Tk.Button(CmpCntrl,width=10,text="Delete",command=self.delete_element)
        button_del.grid(row=2,column=0,padx=5,pady=1)
        button_edit=Tk.Button(CmpCntrl,width=10,text="Edit",command=self.edit_element)
        button_edit.grid(row=2,column=1,padx=5,pady=10)

        ser_c_icon=Tk.PhotoImage(file="./icons/button_Cse.gif")
        #button_ser_c=Tk.Button(CmpCntrl,image=ser_c_icon,command=self.add_series_c)#command=self.add_series_c,image=series_c_photo
        button_ser_c=Tk.Button(CmpCntrl,width=10,text="Series C",command=self.add_series_c)#command=self.add_series_c,image=series_c_photo
        button_ser_c.grid(row=0,column=0)
        button2=Tk.Button(CmpCntrl,width=10,text="Shunt C", command=self.add_shunt_c)
        button2.grid(row=0,column=1)
        button3=Tk.Button(CmpCntrl,width=10,text="Series L", command=self.add_series_l)
        button3.grid(row=1,column=0)
        button4=Tk.Button(CmpCntrl,width=10,text="Shunt L", command=self.add_shunt_l)
        button4.grid(row=1,column=1)
        CmpCntrl.config(background="white")

        #PLOT FRAME
        PlotFrame = Tk.Frame()
        PlotFrame.grid(row=1,column=1)
        self.pltcanvas = FigureCanvasTkAgg(fig, master=PlotFrame)
        self.pltcanvas.get_tk_widget().grid(row=1,column=1)

        self.net=network()

        L1=ind(0.80e-9)
        C1=cap(6.3e-12,shunt=1)    
        L2=ind(2.0e-9)
        C2=cap(1.6e-12,shunt=1)
        L3=ind(5e-9,shunt=1)

        self.net.element_array.append(C2)
        self.net.element_array.append(L2)
        self.net.element_array.append(C1)
        self.net.element_array.append(L1)
        self.net.element_array.append(L3)

        #TEST CASE -- matching 50.0 Ohms to ~5.0 Ohms at 2 GHz
        #SCHEMATIC FRAME
        self.im_size=100
        SchemFrame = Tk.Frame(root)
        SchemFrame.grid(row=2,column=0,columnspan=6,sticky=Tk.N+Tk.S+Tk.W+Tk.E)
        self.Schem = SchematicFrame(SchemFrame,self.net,self.draw_plot,slider) #Pass re-draw function to schematic ########
        #Schem.grid(row=0,column=0)

        #Draw
        #self.center_freq=2.0e9
        self.draw_plot()
Example #58
0
                              avg_dz_m, n_gl=con['n_gl'])

fig_height = 3.5 # in.
fig_width = 5 # in.

fig = Figure(figsize=(fig_width, fig_height))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.set_title('Varied Erosion History', fontsize=12)
ax.invert_xaxis()
ax.invert_yaxis()
var_line, = ax.plot(t * 1e-6, z_targ, 'r')
ax.set_xlabel('Time Before Present (Myr)', fontsize=10)
ax.set_ylabel('Depth (m)', fontsize=10)
ax.grid(linestyle='-', color='0.75')
fig.subplots_adjust(bottom=0.13)
ax.set_xlim(left=2)
ax.set_ylim(bottom=75)
canvas.print_figure('var_hist.png', dpi=500)
ax.set_title('Steady Erosion History', fontsize=12)
const_line, = ax.plot(t * 1e-6, z_const, 'b')
ax.lines.remove(var_line)
canvas.print_figure('const_hist.png', dpi=500)

fig_height = 5 # in.
fig_width = 3.5 # in.

# interpolate a production function
max_possible_depth = con['n_gl'] * con['max_dz'] + con['bottom_depth']
p = production.interpolate_P_tot(max_possible_depth, 
                                 npts=con['n_prod_interp_pts'], alt=con['alt'],
Example #59
0
class App(tk.Frame):
    def __init__(self, parent,file_path):
        tk.Frame.__init__(self, parent)
        parent.deiconify()
        self.events_flag = False
        self.baseline_flag = False
        self.overlay_flag = False
        self.file_path = file_path
                
        ##### Trace plotting widgets #####
        self.trace_frame = tk.LabelFrame(parent,text='Current Trace')
        self.trace_fig = Figure(figsize=(7,5), dpi=100)
        self.trace_canvas = FigureCanvasTkAgg(self.trace_fig, master=self.trace_frame)
        self.trace_toolbar_frame = tk.Frame(self.trace_frame)
        self.trace_toolbar = NavigationToolbar2Tk(self.trace_canvas, self.trace_toolbar_frame)
        self.trace_toolbar.update()

        
        self.trace_frame.grid(row=0,column=0,columnspan=6,sticky=tk.N+tk.S)
        self.trace_toolbar_frame.grid(row=1,column=0,columnspan=6)
        self.trace_canvas.get_tk_widget().grid(row=0,column=0,columnspan=6)


        

        ##### PSD plotting widgets #####
        self.psd_frame = tk.LabelFrame(parent,text='Power Spectrum')
        self.psd_fig = Figure(figsize=(7,5), dpi=100)
        self.psd_canvas = FigureCanvasTkAgg(self.psd_fig, master=self.psd_frame)
        self.psd_toolbar_frame = tk.Frame(self.psd_frame)
        self.psd_toolbar = NavigationToolbar2Tk(self.psd_canvas, self.psd_toolbar_frame)
        self.psd_toolbar.update()
        

        self.psd_frame.grid(row=0,column=6,columnspan=6,sticky=tk.N+tk.S)
        self.psd_toolbar_frame.grid(row=1,column=6,columnspan=6)
        self.psd_canvas.get_tk_widget().grid(row=0,column=6,columnspan=6)



        ##### Control widgets #####
        self.control_frame = tk.LabelFrame(parent, text='Controls')
        self.control_frame.grid(row=2,column=0,columnspan=6,sticky=tk.N+tk.S+tk.E+tk.W)


        self.start_entry = tk.Entry(self.control_frame)
        self.start_entry.insert(0,'0')
        self.start_label = tk.Label(self.control_frame, text='Start Time (s)')
        self.start_label.grid(row=0,column=0,sticky=tk.E+tk.W)
        self.start_entry.grid(row=0,column=1,sticky=tk.E+tk.W)

        self.end_entry = tk.Entry(self.control_frame)
        self.end_entry.insert(0,'10')
        self.end_label = tk.Label(self.control_frame, text='End Time (s)')
        self.end_label.grid(row=0,column=2,sticky=tk.E+tk.W)
        self.end_entry.grid(row=0,column=3,sticky=tk.E+tk.W)

        self.psd_length_entry = tk.Entry(self.control_frame)
        self.psd_length_label = tk.Label(self.control_frame, text='PSD Length (s)')
        self.psd_length_label.grid(row=0,column=4,sticky=tk.E+tk.W)
        self.psd_length_entry.grid(row=0,column=5,sticky=tk.E+tk.W)

        self.cutoff_entry = tk.Entry(self.control_frame)
        self.cutoff_entry.insert(0,'900000')
        self.cutoff_label = tk.Label(self.control_frame, text='Cutoff (Hz)')
        self.cutoff_label.grid(row=1,column=0,sticky=tk.E+tk.W)
        self.cutoff_entry.grid(row=1,column=1,sticky=tk.E+tk.W)

        self.order_entry = tk.Entry(self.control_frame)
        self.order_entry.insert(0,'8')
        self.order_label = tk.Label(self.control_frame, text='Filter Order')
        self.order_label.grid(row=1,column=2,sticky=tk.E+tk.W)
        self.order_entry.grid(row=1,column=3,sticky=tk.E+tk.W)

        self.downsample_entry = tk.Entry(self.control_frame)
        self.downsample_label = tk.Label(self.control_frame, text='Downsample')
        self.downsample_label.grid(row=1,column=4,sticky=tk.E+tk.W)
        self.downsample_entry.grid(row=1,column=5,sticky=tk.E+tk.W)

        self.plot_trace = tk.Button(self.control_frame, text='Update Trace', command=self.update_trace)
        self.plot_trace.grid(row=2,column=0,columnspan=2,sticky=tk.E+tk.W)

        self.normalize = tk.IntVar()
        self.normalize.set(0)
        self.normalize_check = tk.Checkbutton(self.control_frame, text='Normalize', variable = self.normalize)
        self.normalize_check.grid(row=2,column=2,sticky=tk.E+tk.W)
        
        self.plot_psd = tk.Button(self.control_frame, text='Update PSD', command=self.update_psd)
        self.plot_psd.grid(row=2,column=3,sticky=tk.E+tk.W)

        self.update_data = tk.Button(self.control_frame, text='Update Data', command=self.update_data)
        self.update_data.grid(row=2,column=4,columnspan=1,sticky=tk.E+tk.W)

        self.overlay_cusum = tk.Button(self.control_frame, text='Overlay CUSUM', command=self.overlay_cusum)
        self.overlay_cusum.grid(row=2,column=5,columnspan=1,sticky=tk.E+tk.W)
        

        ##### Feedback Widgets #####
        self.feedback_frame = tk.LabelFrame(parent, text='Status')
        self.feedback_frame.grid(row=2,column=6,columnspan=6,sticky=tk.N+tk.S+tk.E+tk.W)
        
        self.wildcard = tk.StringVar()
        self.wildcard_label = tk.Label(self.feedback_frame, textvariable=self.wildcard)
        self.wildcard_label.grid(row=0,column=0,columnspan=6,sticky=tk.E+tk.W)
        self.export_psd = tk.Button(self.feedback_frame, text='Export PSD',command=self.export_psd)
        self.export_psd.grid(row=1,column=0,columnspan=6,sticky=tk.E+tk.W)
        self.export_trace = tk.Button(self.feedback_frame, text='Export Trace',command=self.export_trace)
        self.export_trace.grid(row=2,column=0,columnspan=6,sticky=tk.E+tk.W)
        self.get_filenames(self.file_path)
        self.load_memmaps()
        self.initialize_samplerate()

    ##### utility functions #####

    


    def overlay_cusum(self):
        analysis_dir = tkinter.filedialog.askdirectory(initialdir='G:/NPN/Filter Scaling/K435PC/500bp',title='Choose analysis directory')
        baseline_path = analysis_dir + '/baseline.csv'
        ratefile_path = analysis_dir + '/rate.csv'
        config_path = analysis_dir + '/summary.txt'
        self.events_flag = True
        self.baseline_flag = True
        self.overlay_flag = True
        try:
            self.ratefile = pd.read_csv(ratefile_path,encoding='utf-8')
        except IOError:
            self.overlay_flag = False
            self.wildcard.set('rate.csv not found in given directory')
        try:
            self.baseline_file = pd.read_csv(baseline_path,encoding='utf-8')
        except IOError:
            self.overlay_flag = False
            self.wildcard.set('baseline.csv not found in given directory')
        with open(config_path,'r') as config:
            for line in config:
                if 'threshold' in line and 'intra' not in line:
                    line = re.split('=|\n',line)
                    self.threshold = float(line[1])
                if 'hysteresis' in line and 'intra' not in line:
                    line = re.split('=|\n',line)
                    self.hysteresis = float(line[1])
                if 'cutoff' in line:
                    line = re.split('=|\n',line)
                    self.config_cutoff = int(line[1])
                if 'poles' in line:
                    line = re.split('=|\n',line)
                    self.config_order = int(line[1])


    def export_psd(self):
        try:
            data_path = tkinter.filedialog.asksaveasfilename(defaultextension='.csv',initialdir='G:/PSDs for Sam')
            np.savetxt(data_path,np.c_[self.f, self.Pxx, self.rms],delimiter=',')
        except AttributeError:
            self.wildcard.set('Plot the PSD first')

    def export_trace(self):
        try:
            data_path = tkinter.filedialog.asksaveasfilename(defaultextension='.csv',initialdir='G:/Analysis/Pores/NPN/PSDs')
            np.savetxt(data_path,self.plot_data,delimiter=',')
        except AttributeError:
            self.wildcard.set('Plot the trace first')

    def get_file_index(self, samplenum):
        i = 0
        try:
            while self.file_start_index[i+1] < samplenum:
                i += 1
        except IndexError:
            i = len(self.file_start_index)
        return i
        
        
    def load_mapped_data(self):
        if self.start_entry.get()!='':
            self.start_time = float(self.start_entry.get())
            start_index = int((float(self.start_entry.get())*self.samplerate))
        else:
            self.start_time = 0
            start_index = 0
            
        
        start_f = self.get_file_index(start_index)


        if self.end_entry.get()!='':
            self.end_time = float(self.end_entry.get())
            end_index = int((float(self.end_entry.get())*self.samplerate))
            if end_index > self.total_samples:
                end_index = self.total_samples
        else:
            end_index = start_index + len(self.maps[start_f])        
        
        end_f = self.get_file_index(end_index)

        if start_f == end_f:
            filesize = len(self.maps[start_f])
            tempdata = self.maps[start_f][start_index - self.file_start_index[start_f]:end_index - self.file_start_index[start_f]]
            settings = self.settings[start_f]
            data = self.scale_raw_data(tempdata,settings)     
        else:
            filesize = len(self.maps[start_f])
            tempdata = self.maps[start_f][start_index - self.file_start_index[start_f]:]
            settings = self.settings[start_f]
            data = self.scale_raw_data(tempdata,settings)
            for i in range(start_f+1,end_f):
                tempdata = self.maps[i]
                settings = self.settings[i]
                data = np.concatenate((data,self.scale_raw_data(tempdata,settings)))
            tempdata = self.maps[end_f]
            settings = self.settings[end_f]
            filesize = len(self.maps[end_f])
            data = np.concatenate((data, self.scale_raw_data(self.maps[end_f][:end_index - self.file_start_index[end_f]],settings)))
        self.data = data

    def scale_raw_data(self,tempdata,settings):
        samplerate = np.floor(np.squeeze(settings['ADCSAMPLERATE']))
        TIAgain = np.squeeze(settings['SETUP_TIAgain'])
        preADCgain = np.squeeze(settings['SETUP_preADCgain'])
        currentoffset = np.squeeze(settings['SETUP_pAoffset'])
        voltageoffset = np.squeeze(settings['SETUP_mVoffset'])
        ADCvref = np.squeeze(settings['SETUP_ADCVREF'])
        ADCbits = np.squeeze(settings['SETUP_ADCBITS'])
        if samplerate != self.samplerate:
            self.wildcard.set('One of your files does not match the global sampling rate!')
        closedloop_gain = TIAgain*preADCgain
        bitmask = (2**16 - 1) - (2**(16-ADCbits) - 1)
        tempdata = tempdata.astype(np.uint16) & bitmask
        tempdata = ADCvref - (2*ADCvref) * tempdata.astype(float)/ float(2**16)
        tempdata = -tempdata/float(closedloop_gain) + float(currentoffset)
        return tempdata * 1e12
            
    def load_memmaps(self):
        columntypes = np.dtype([('current', np.uint16)])
        self.maps = [np.memmap(str(f), dtype=columntypes, mode='r')['current'] for f in self.sorted_files]
        self.settings = [sio.loadmat(f.replace('.log','.mat')) for f in self.sorted_files]
        total = 0
        self.file_start_index = [0]
        for m in self.maps:
            total += len(m)
            self.file_start_index.append(total)
        self.total_samples = total
        self.file_start_index = np.array(self.file_start_index,dtype=np.int64)
        
    def get_filenames(self, initialfile):
        pattern = initialfile[:-19] + '*.log'
        files = glob.glob(pattern)
        timelist = [os.path.basename(fname)[-19:-4] for fname in files]
        etimestamps = [time.mktime(time.strptime(stamp,"%Y%m%d_%H%M%S")) for stamp in timelist]
        self.sorted_files = [fname for (estamp, fname) in sorted(zip(etimestamps, files), key=lambda pair: pair[0])]
        self.wildcard.set('Found {0} files matching {1}'.format(len(self.sorted_files),pattern))
        
    def integrate_noise(self, f, Pxx):
        df = f[1]-f[0]
        return np.sqrt(np.cumsum(Pxx * df))

    def filter_data(self):
        cutoff = float(self.cutoff_entry.get())
        order = int(self.order_entry.get())
        Wn = 2.0 * cutoff/float(self.samplerate)
        b, a = bessel(order,Wn,'low')
        padding = 1000
        padded = np.pad(self.data, pad_width=padding, mode='median')
        self.filtered_data = filtfilt(b, a, padded, padtype=None)[padding:-padding]

    def downsample_data(self):
        self.downsampled_data = self.filtered_data[::int(self.samplerate / self.downsample_entry.get())]

    def initialize_samplerate(self):
        settings = self.settings[0]
        self.samplerate = np.floor(np.squeeze(settings['ADCSAMPLERATE']))

    ##### Plot Updating functions #####
    def update_trace(self):
        self.load_mapped_data()
        self.filtered_data = self.data
        self.plot_data = self.filtered_data
        plot_samplerate = self.samplerate
        
        if self.cutoff_entry.get()!='' and self.order_entry!='':
            self.filter_data()
            self.plot_data = self.filtered_data
        if self.downsample_entry.get()!='':
            self.downsample_data()
            self.plot_data = self.downsampled_data
            plot_samplerate = float(self.downsample_entry.get())
        

        
        
        self.trace_fig.clf()
        a = self.trace_fig.add_subplot(111)

        if self.events_flag and self.overlay_flag == True:
            db = self.ratefile
            start_time = self.start_time
            end_time = self.end_time
            good_start = np.atleast_1d(np.squeeze(sqldf('SELECT start_time_s from db WHERE start_time_s >= {0} AND start_time_s < {1} AND type IN (0,1)'.format(start_time,end_time),locals()).values)*1e6)
            bad_start = np.atleast_1d(np.squeeze(sqldf('SELECT start_time_s from db WHERE start_time_s >= {0} AND start_time_s < {1} AND type>1'.format(start_time,end_time),locals()).values)*1e6)
            good_end = np.atleast_1d(np.squeeze(sqldf('SELECT end_time_s from db WHERE end_time_s >= {0} AND end_time_s < {1} AND type IN (0,1)'.format(start_time,end_time),locals()).values)*1e6)
            bad_end = np.atleast_1d(np.squeeze(sqldf('SELECT end_time_s from db WHERE end_time_s >= {0} AND end_time_s < {1} AND type>1'.format(start_time,end_time),locals()).values)*1e6)
            
            if len(good_start) > 0 and len(good_end) > 0:
                if good_start[0] > good_end[0]:
                    good_start = good_start[1:]
            if len(bad_start) > 0 and len(bad_end) > 0:
                if bad_start[0] > bad_end[0]:
                    bad_start = bad_start[1:]
            for gs, ge in zip(np.atleast_1d(good_start),np.atleast_1d(good_end)):
                 a.axvspan(gs,ge,color='g',alpha=0.3)
            for bs, be in zip(np.atleast_1d(bad_start),np.atleast_1d(bad_end)):
                a.axvspan(bs,be,color='r',alpha=0.3)

        

        time = np.linspace(1.0/plot_samplerate,len(self.plot_data)/float(plot_samplerate),len(self.plot_data))+self.start_time
        
        a.set_xlabel(r'Time ($\mu s$)')
        a.set_ylabel('Current (pA)')
        self.trace_fig.subplots_adjust(bottom=0.14,left=0.21)
        a.plot(time*1e6,self.plot_data,'.',markersize=1)

        if self.baseline_flag:
            if self.config_cutoff != int(self.cutoff_entry.get()) or self.config_order != int(self.order_entry.get()):
                self.wildcard.set('Filter settings in config file do not match plotting filter settings, overlay will be inaccurate')
            db = self.baseline_file
            start_time = self.start_time
            end_time = self.end_time
            times = np.squeeze(sqldf('SELECT time_s from db',locals()).values)
            times = np.sort(times)

            start_block = times[0]
            for time in times:
                if time <= start_time and time >= start_block:
                    start_block = time
            


            baseline_db = sqldf('SELECT * from db WHERE time_s >= {0} and time_s < {1}'.format(start_block,end_time),locals())
            times = baseline_db['time_s'].values
            means = baseline_db['baseline_pA'].values
            stdevs = baseline_db['stdev_pA'].values
  
            numblocks = len(means)
            for i in range(numblocks):
                if i == 0:
                    xmin = start_time
                else:
                    xmin = times[i]
                if i+1 == numblocks:
                    xmax = end_time
                else:
                    xmax = times[i+1]
                
                sign = np.sign(means[i])
                a.plot((xmin*1e6,xmax*1e6), (means[i]-sign*(self.threshold - self.hysteresis)*stdevs[i],means[i]-sign*(self.threshold - self.hysteresis)*stdevs[i]), '--',color='y')
                a.plot((xmin*1e6,xmax*1e6), (means[i]-sign*self.threshold*stdevs[i],means[i]-sign*self.threshold*stdevs[i]), '--',color='y')
                a.plot((xmin*1e6,xmax*1e6), (means[i],means[i]), '--', color='black')
                
        self.trace_canvas.draw()

    def update_psd(self):
        self.load_mapped_data()
        self.filtered_data = self.data
        self.plot_data = self.filtered_data
        plot_samplerate = self.samplerate
        bandwidth = 1.0e6
        
        if self.cutoff_entry.get()!='' and self.order_entry!='':
            self.filter_data()
            self.plot_data = self.filtered_data
            maxf = 2*float(self.cutoff_entry.get())
            bandwidth = maxf/2.0
        else:
            maxf = 2e6
        if (self.psd_length_entry.get()!=''):
            length = 2**np.ceil(np.log2(float(self.psd_length_entry.get())*plot_samplerate))
            if (length > len(self.filtered_data)):
                length = len(self.filtered_data)
        else:
            length = np.minimum(2**20,len(self.filtered_data))
        end_index = int(np.floor(len(self.filtered_data)/length)*length)

        current = np.average(self.filtered_data[:end_index])
        
        f, Pxx = welch(self.filtered_data, plot_samplerate,nperseg=length)
        self.rms = self.integrate_noise(f, Pxx)
        
        if self.normalize.get():
            Pxx /= current**2
            Pxx *= bandwidth
            self.rms /= np.absolute(current)
           
        self.f = f
        self.Pxx = Pxx
        
        minf = 1  
        BW_index = np.searchsorted(f, maxf/2)
        logPxx = np.log10(Pxx[1:BW_index])
        minP = 10**np.floor(np.amin(logPxx))
        maxP = 10**np.ceil(np.amax(logPxx))


        df = f[1]-f[0]
        fitmax = 10000
        freqstop = len(f[f<=100])
        N = len(f[f<fitmax])
        fnorm = self.f[1:N]
        if self.normalize.get():
            Pxx_norm = self.Pxx[1:N]
        else:
            Pxx_norm = self.Pxx[1:N]*bandwidth/current**2

        #popt, pcov = curve_fit(self.fitfunc, fnorm, np.log10(Pxx_norm), p0=[1.0,1,1000.0, 0.0001], sigma=np.sqrt(np.arange(1,N)+np.sqrt(3)/3), maxfev=100000)
            
        #f0 = popt[0]
        #alpha = popt[1]
        #fstar = popt[2]
        #offset = popt[3]
        
        #L_simple = self.old_L(Pxx_norm[:freqstop], df, bandwidth)
        #L_adj = self.corrected_L(fnorm[:freqstop], Pxx_norm[:freqstop], f0, alpha, fstar, offset, df, bandwidth)
        
        self.psd_fig.clf()
        a = self.psd_fig.add_subplot(111)
        a.set_xlabel('Frequency (Hz)')
        a.set_ylabel(r'Spectral Power ($\mathrm{pA}^2/\mathrm{Hz}$)')
        a.set_xlim(minf, maxf)
        a.set_ylim(minP, maxP)
        self.psd_fig.subplots_adjust(bottom=0.14,left=0.21)
        a.loglog(f[1:],Pxx[1:],'b-')
        #if self.normalize.get():
        #    a.loglog(fnorm, 10**self.fitfunc(f[1:N], f0, alpha, fstar, offset),'g')
        #else:
        #    a.loglog(fnorm, 10**self.fitfunc(f[1:N], f0, alpha, fstar, offset)*current**2/bandwidth,'g')
        for tick in a.get_yticklabels():
            tick.set_color('b')

        
        a2 = a.twinx()
        a2.semilogx(f, self.rms, 'r-')
        a2.set_ylabel('RMS Noise (pA)')
        a2.set_xlim(minf, maxf)
        for tick in a2.get_yticklabels():
            tick.set_color('r')
        a2.format_coord = make_format(a2, a)
        
        self.psd_canvas.draw()

        #psd1hz = 10**self.fitfunc(1.0, f0, alpha, fstar, offset)*current**2/bandwidth

       # self.wildcard.set('RMS = {:0.2f} pA\tL[old] = {:.3g}\tL[adjusted] = {:.3g}\tPSD@1Hz = {:.3g} pA\u00b2/Hz'.format(np.std(self.filtered_data), L_simple, L_adj,psd1hz))
  
        
    def fitfunc(self, f, f0, alpha, fstar, offset):
        return np.log10((f0/f)**alpha + alpha*(f0/fstar)**(1+alpha)*(f/f0) + offset)


    def corrected_L(self, f, Pxx, f0, alpha, fstar, offset, df, B):
        integrand = Pxx - alpha*(f0/fstar)**(1+alpha)*(f/f0) - offset
        return np.sqrt(np.sum(integrand)*df/B)

    def old_L(self, Pxx, df, B):
        return np.sqrt(np.sum(Pxx)*df/B)

    
    def update_data(self):
        self.get_filenames(self.file_path)
        self.load_memmaps()
        self.initialize_samplerate()
Example #60
0
class graph_panel(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        self.previous_patterns = []
        self.history_size = 100
        self.hi_contrast = False
        self.big_numbers = False
        self.need_data = True
        self.build()

    def build(self):
        ''' build the whole thing '''
        self.fig = Figure(dpi=110)
        self.fig.set_facecolor('#000000')
        self.canvas = FigCanvas(self, -1, self.fig)
        self.Bind(wx.EVT_SIZE, self.sizeHandler)
        self.SetMinSize((400, 200))
        self.buildgraph()

    def add_axes(self, subplot_index):
        ''' add a new set of axes '''
        ax = self.fig.add_subplot(subplot_index)
        ax.set_axis_bgcolor('#000000')
        ax.set_xlim(0, self.history_size)
        #ax.set_yscale('log', nonposx='clip')
        #ax.set_ylim(ymin=0)
        yfm = ax.yaxis.get_major_formatter()
        yfm.set_powerlimits([0, 1])
        ax.spines['top'].set_color('white')
        ax.spines['bottom'].set_color('white')
        ax.spines['left'].set_color('white')
        ax.spines['right'].set_color('white')
        ax.tick_params(axis='x', colors='white')
        ax.tick_params(axis='y', colors='white')
        ax.yaxis.get_offset_text().set_color('white')
        return ax

    def add_big_text(self, ax):
        ''' add big text '''
        text = ax.text(0.01,
                       0.95,
                       '',
                       transform=ax.transAxes,
                       color='#ffffff',
                       va='top',
                       fontsize=45)
        return text

    def buildgraph(self):
        ''' build the graph bits '''
        self.fig.clf()
        self.axes1 = self.add_axes(211)
        self.axes2 = self.add_axes(212)
        self.fig.subplots_adjust(left=.08, right=.97, top=.96, bottom=.08)

    def sizeHandler(self, *args, **kwargs):
        ''' makes sure that the canvas is properly resized '''
        self.canvas.SetSize(self.GetSize())

    def set_hi_contrast(self, event):
        ''' set the contrast '''
        self.hi_contrast = event.IsChecked()
        for c in self.all_curves:
            if self.hi_contrast:
                c.plot_curve.set_lw(1)
                c.plot_curve.set_color('white')
            else:
                c.plot_curve.set_lw(1)
                c.plot_curve.set_color(c.color)

    def set_big_numbers(self, event):
        ''' set the contrast '''
        self.big_numbers = event.IsChecked()

    def clear(self):
        ''' called when the pattern changes '''
        if self.need_data == False:
            self.buildgraph()
        self.need_data = True
        self.singles_curves = []

    def add_counts(self, data):
        ''' add a set of counts '''
        new_singles = filter(lambda x: len(x[1]) == 1, data)
        new_coincidences = filter(lambda x: len(x[1]) > 1, data)

        if self.need_data:
            self.singles_curves = [
                curve(q[0], q[1], self.axes1, self.history_size)
                for q in new_singles
            ]
            self.coincidence_curves = [
                curve(q[0], q[1], self.axes2, self.history_size)
                for q in new_coincidences
            ]
            self.all_curves = self.singles_curves + self.coincidence_curves
            self.need_data = False

        for i in range(len(self.singles_curves)):
            self.singles_curves[i].add_point(new_singles[i][2])

        for i in range(len(self.coincidence_curves)):
            self.coincidence_curves[i].add_point(new_coincidences[i][2])

        self.draw()

    def get_big_number_text(self, curve_group):
        ''' update the big number text '''
        text = ''
        for c in curve_group:
            s = format(int(c.ydata[-1]), ',d')
            s = '%s: %s\n' % (c.label, s)
            text += s
        return text

    def rescale_axes(self):
        ''' rescale all the axes '''
        self.axes1.relim()
        self.axes1.autoscale_view(True, True, True)
        self.axes2.relim()
        self.axes2.autoscale_view(True, True, True)

    def draw(self):
        ''' draw all of the curves etc '''
        for c in self.all_curves:
            c.update()

        self.rescale_axes()
        self.canvas.draw()