Пример #1
0
class MainFrame(Frame):
    def __init__(self,
                 parent=None,
                 title='',
                 direction='H',
                 size=(750, 750),
                 lfname=None):

        Frame.__init__(self, parent, title, direction, size)

    def Body(self):

        self.CreateMenu()
        self.CenterOnScreen()

        self.fig = Figure(figsize=(7, 5), dpi=100)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.figmgr = FigureManager(self.canvas, 1, self)

        #        self.axes = [self.fig.add_subplot(221),
        #                    self.fig.add_subplot(222),
        #                    self.fig.add_subplot(223),
        #                    self.fig.add_subplot(224)]

        self.axis = self.fig.add_subplot(1, 2, 1)
        self.AddComponent(self.canvas)
        self.Plot()

    def Plot(self):

        self.axis.hold(False)
        for i in range(1):
            x = linspace(0, 200.0, 201)
            self.axis.plot(x, x**2 * sin(x / 200), '-o')
            self.axis.hold(True)

        self.canvas.draw()
        self.canvas.gui_repaint()

    def CreateMenu(self):

        menubar = MenuBar()

        menu = Menu(self)
        menu.Append("&Quit", self.Quit, "Quit", hotkey="Ctrl+Q")

        menubar.Append(menu, "&File")

        self.SetMenuBar(menubar)
        self.CreateStatusBar()

    def Quit(self, event=None):

        self.Close()
Пример #2
0
    def Body(self):

        self.CreateMenu()
        self.CenterOnScreen()

        self.ResetTitle()

        fname = self.base_dir + "/images/plasticity_small_icon.ico"
        self.SetIcon(fname)

        self.fig = Figure(figsize=(7, 5), dpi=100)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.figmgr = FigureManager(self.canvas, 1, self)

        self.axes = [
            self.fig.add_subplot(221),
            self.fig.add_subplot(222),
            self.fig.add_subplot(223),
            self.fig.add_subplot(224)
        ]

        if self.plot_first:
            sim = zpickle.load(self.tmpfile)
            sim['params']['display'] = True
            self.Plot(sim)
Пример #3
0
    def Body(self):
    
        self.CreateMenu()
        self.CenterOnScreen()
        
        self.fig = Figure(figsize=(7,5),dpi=100)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.figmgr = FigureManager(self.canvas, 1, self)

        self.axes = [self.fig.add_subplot(111)]
Пример #4
0
    def Body(self):

        self.CreateMenu()
        self.CenterOnScreen()

        self.fig = Figure(figsize=(7, 5), dpi=100)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.figmgr = FigureManager(self.canvas, 1, self)

        self.axes = [self.fig.add_subplot(111)]
Пример #5
0
 def Body(self):
     
     self.CenterOnScreen()
     self.params=default_params()
     self.ResetTitle()
     
     self.fig = Figure(figsize=(7,5),dpi=100)
     self.axes = [self.fig.add_subplot(221),
                 self.fig.add_subplot(222),
                 self.fig.add_subplot(223),
                 self.fig.add_subplot(224)]
                 
     self.canvas = FigureCanvas(self, -1, self.fig)
     self.CreateStatusBar()
     
     self.Show()
Пример #6
0
    def __init__(self,parent,size=wx.DefaultSize, filename=None, options=None):

        wx.Window.__init__( self, parent, id=-1, style=wx.NO_BORDER)
        self.fig = Figure((21,21),60)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.choice=PlotChoice(self)
        self.choice.mode="Standard"
        self.toolbar.Realize()
        self.parent=parent
        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))
        
        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        self.Fit()

        self.filename=filename
        if DEBUG :
            DEBUG_MSG("plot :"+filename)
        self.n=0
        self.ni=0
        self.vl=0
        self.vl1=0
        self.sw=0
        self.sw1=0
        self.flag_sum=False
        
        try:          
            [dirname,shortfilename]=os.path.split(filename)
            [basename,extension]=os.path.splitext(shortfilename)

            self.title=basename
            self.filename=dirname+"\\"+basename+".spe"            

            if not options:
                self.options={'units': 'ppm',
                              'titles': 'no',
                              'yoffset': '0.001',
                              'yaxis': 'yes'}
            self.grid=False
        except:
            pass
Пример #7
0
    def Body(self):

        self.CreateMenu()
        self.CenterOnScreen()

        self.fig = Figure(figsize=(7, 5), dpi=100)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.figmgr = FigureManager(self.canvas, 1, self)

        #        self.axes = [self.fig.add_subplot(221),
        #                    self.fig.add_subplot(222),
        #                    self.fig.add_subplot(223),
        #                    self.fig.add_subplot(224)]

        self.axis = self.fig.add_subplot(1, 2, 1)
        self.AddComponent(self.canvas)
        self.Plot()
Пример #8
0
    def Body(self):

        self.CenterOnScreen()
        self.params = default_params()
        self.ResetTitle()

        self.fig = Figure(figsize=(7, 5), dpi=100)
        self.axes = [
            self.fig.add_subplot(221),
            self.fig.add_subplot(222),
            self.fig.add_subplot(223),
            self.fig.add_subplot(224)
        ]

        self.canvas = FigureCanvas(self, -1, self.fig)
        self.CreateStatusBar()

        self.Show()
Пример #9
0
 def Body(self):
     
     self.CreateMenu()
     self.CenterOnScreen()
     
     self.ResetTitle()
     
     fname=self.base_dir+"/images/plasticity_small_icon.ico"
     self.SetIcon(fname)
     
     self.fig = Figure(figsize=(7,5),dpi=100)
     self.axes = [self.fig.add_subplot(221),
                 self.fig.add_subplot(222),
                 self.fig.add_subplot(223),
                 self.fig.add_subplot(224)]
                 
     self.canvas = FigureCanvas(self, -1, self.fig)
     
     if self.plot_first:
         sim=zpickle.load(self.tmpfile)
         self.Plot(sim)
Пример #10
0
class MainFrame(Frame):
    def __init__(self,
                 parent=None,
                 title='',
                 direction='H',
                 size=(750, 750),
                 lfname=None,
                 params=None):
        self.fig = None

        # turn off security warning on tmpnam.  why is it here?
        warnings.filterwarnings('ignore')
        fname = os.tempnam()
        warnings.resetwarnings()

        self.base_dir = os.path.dirname(__file__)
        if not self.base_dir:
            self.base_dir = '.'

        self.tmpfile = fname + "_plasticity.dat"
        self.modified = False
        self.running = False
        self.stopping = False
        self.quitting = False
        self.plot_first = False

        if not params:
            self.params = default_params()
        else:
            self.params = params

        for p in self.params['pattern_input']:
            if not os.path.exists(p['filename']):
                p['filename'] = self.base_dir + "/" + p['filename']

        if lfname:
            if not self.__load_sim__(lfname):
                self.plot_first = True

        Frame.__init__(self, parent, title, direction, size)

    def Body(self):

        self.CreateMenu()
        self.CenterOnScreen()

        self.ResetTitle()

        fname = self.base_dir + "/images/plasticity_small_icon.ico"
        self.SetIcon(fname)

        self.fig = Figure(figsize=(7, 5), dpi=100)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.figmgr = FigureManager(self.canvas, 1, self)

        self.axes = [
            self.fig.add_subplot(221),
            self.fig.add_subplot(222),
            self.fig.add_subplot(223),
            self.fig.add_subplot(224)
        ]

        if self.plot_first:
            sim = zpickle.load(self.tmpfile)
            sim['params']['display'] = True
            self.Plot(sim)

    def Stopping(self):
        return self.stopping

    def Yield(self):
        wx.Yield()

    def ResetTitle(self):

        (root, sfname) = os.path.split(self.params['save_sim_file'])
        if self.modified:
            s = ' (*)'
        else:
            s = ''

        title = 'Plasticity: %s%s' % (sfname, s)
        self.SetTitle(title)

    def Plot(self, sim):

        if not sim['params']['display']:
            return

        if sim['params']['display_module']:
            try:
                module = __import__(sim['params']['display_module'],
                                    fromlist=['UserPlot'])
            except ImportError:
                sim['params']['display'] = False
                dlg = MessageDialog(
                    self,
                    "Error",
                    "Error in Import: %s.  Turning display off" %
                    sim['params']['display_module'],
                    icon='error')
                dlg.ShowModal()
                dlg.Destroy()
                return

            try:
                module.UserPlot(self, sim)
                return
            except ValueError:
                sim['params']['display'] = False
                dlg = MessageDialog(self,
                                    "Error",
                                    "Error in display.  Turning display off",
                                    icon='error')
                dlg.ShowModal()
                dlg.Destroy()
                return

        try:

            im = weights2image(sim['params'], sim['weights'])

            self.axes[0].hold(False)
            self.axes[0].set_axis_bgcolor('k')
            self.axes[0].pcolor(im, cmap=gray, edgecolors='k')
            self.axes[0].set_aspect('equal')

            num_moments = sim['moments_mat'].shape[0]

            self.axes[1].hold(False)
            num_neurons = sim['moments_mat'].shape[1]
            for k in range(num_neurons):
                for i in range(num_moments):
                    self.axes[1].plot(sim['moments_mat'][i, k, :], '-o')
                    self.axes[1].hold(True)

            self.axes[2].hold(False)
            response_mat = sim['response_mat']
            response_var_list = sim['response_var_list']
            styles = ['b-o', 'g-o']
            for i, r in enumerate(response_var_list[-1]):
                x = r[1]
                y = r[2]

                self.axes[2].plot(x, y, styles[i])
                self.axes[2].hold(True)

            self.axes[3].hold(False)
            styles = ['b-o', 'g-o']
            for i, r in enumerate(response_mat):
                self.axes[3].plot(r, styles[i])
                self.axes[3].hold(True)

            self.canvas.draw()
            self.canvas.gui_repaint()

        except ValueError:
            sim['params']['display'] = False
            dlg = MessageDialog(self,
                                "Error",
                                "Error in display.  Turning display off",
                                icon='error')
            dlg.ShowModal()
            dlg.Destroy()

    def Run_Pause(self, event):

        if not self.running:
            #            pylab.close()

            self.params['tmpfile'] = self.tmpfile
            if os.path.exists(self.tmpfile):
                self.params['continue'] = 1
            self.modified = True
            self.ResetTitle()
            self.running = True

            ##            d={}
            ##            d['params']=self.params
            ##            zpickle.save(d,'plasticity_tmpparams.dat')
            ##            cmd='./run_sim.py --paramfile plasticity_tmpparams.dat --from_gui 1'
            ##            os.system(cmd)
            self.stopping = False
            run_sim(self.params, self)

            self.params['load_sim_file'] = self.tmpfile
            self.running = False
            if self.quitting:
                self.Quit()

        else:
            self.stopping = True

    def __load_sim__(self, lfname):

        sim = zpickle.load(lfname)

        params = sim['params']

        params['save_sim_file'] = self.params['save_sim_file']
        params['load_sim_file'] = ''
        params['continue'] = False

        try:
            params['initial_weights'] = sim['weights']
            params['initial_moments'] = sim['moments']
        except KeyError:
            self.params = params
            return 1

        params['load_sim_file'] = self.tmpfile
        params['continue'] = True
        sim['params'] = params
        self.params = params

        zpickle.save(sim, self.tmpfile)

        return 0

    def Reset_Simulation(self, event=None):
        if not os.path.exists(self.tmpfile):
            return

        self.canvas.Show(False)
        if self.modified:
            (root, sfname) = os.path.split(self.params['save_sim_file'])
            dlg = MessageDialog(
                self,
                text="Do you want to save the changes you made to %s?" %
                sfname,
                title="Reset",
                ok=0,
                yes_no=1,
                cancel=1)
            result = dlg.ShowModal()
            dlg.Destroy()

            if result == 'cancel':
                self.canvas.Show(True)
                return
            elif result == 'yes':
                filename = self.Save_Simulation()
                if not filename:  # cancelled the save
                    self.canvas.Show(True)
                    return

        self.params['continue'] = False
        self.params['load_sim_file'] = ''
        self.params['initial_weights'] = []
        self.params['initial_moments'] = []

        for a in self.axes:

            a.cla()

        self.canvas.draw()
        self.canvas.Show(True)

    def Restart(self, event=None):

        if not os.path.exists(self.tmpfile):
            return

        self.canvas.Show(False)
        if self.modified:
            (root, sfname) = os.path.split(self.params['save_sim_file'])
            dlg = MessageDialog(
                self,
                text="Do you want to save the changes you made to %s?" %
                sfname,
                title="Restart",
                ok=0,
                yes_no=1,
                cancel=1)
            result = dlg.ShowModal()
            dlg.Destroy()

            if result == 'cancel':
                self.canvas.Show(True)
                return
            elif result == 'yes':
                filename = self.Save_Simulation()
                if not filename:  # cancelled the save
                    self.canvas.Show(True)
                    return

        self.__load_sim__(self.tmpfile)
        self.params['continue'] = False
        self.canvas.Show(True)

    def Load_Simulation(self, event=None):

        self.canvas.Show(False)
        if self.modified:
            (root, sfname) = os.path.split(self.params['save_sim_file'])
            dlg = MessageDialog(
                self,
                text="Do you want to save the changes you made to %s?" %
                sfname,
                title="Load Simulation",
                ok=0,
                yes_no=1,
                cancel=1)
            result = dlg.ShowModal()
            dlg.Destroy()

            if result == 'cancel':
                pass
            elif result == 'yes':
                self.Save_Simulation()

        lfname = ''
        dlg = FileDialog(self,
                         "Load Simulation",
                         default_dir=os.getcwd() + "/sims",
                         wildcard='DAT Files|*.dat|All Files|*.*')
        result = dlg.ShowModal()
        if result == 'ok':
            lfname = dlg.GetPaths()[0]
        dlg.Destroy()

        if not lfname:
            self.canvas.Show(True)
            return

        self.__load_sim__(lfname)

        sim = zpickle.load(self.tmpfile)
        self.Plot(sim)
        self.canvas.Show(True)

    def Save_Simulation(self, event=None):

        if not self.modified:
            return

        sfname = self.params['save_sim_file']
        def_sfname = default_params()['save_sim_file']
        if sfname == def_sfname:
            filename = self.Save_Simulation_As()

        else:
            filename = sfname
            d = zpickle.load(self.tmpfile)
            d['params'] = self.params
            zpickle.save(d, sfname)

            self.modified = False

            self.ResetTitle()

        return filename

    def Save_Simulation_As(self, event=None):

        self.canvas.Show(False)
        dlg = FileDialog(self,
                         "Save Simulation As...",
                         default_dir=os.getcwd() + "/sims/",
                         wildcard='DAT Files|*.dat|All Files|*.*',
                         save=1)
        result = dlg.ShowModal()
        if result == 'ok':
            filename = dlg.GetPaths()[0]
        else:
            filename = None

        dlg.Destroy()

        if filename:
            d = zpickle.load(self.tmpfile)
            self.params['save_sim_file'] = filename
            d['params'] = self.params
            zpickle.save(d, filename)

            self.modified = False

            self.ResetTitle()

        self.canvas.Show(True)

        return filename

    def Set_Simulation_Parameters(self, event):
        self.canvas.Show(False)
        set_simulation_parameters(self.params, self)
        self.canvas.Show(True)

    def Set_Input_Parameters(self, event):
        self.canvas.Show(False)
        set_input_parameters(self.params, self)
        self.canvas.Show(True)

    def Set_Output_Parameters(self, event):
        self.canvas.Show(False)
        set_output_parameters(self.params, self)
        self.canvas.Show(True)

    def Set_Weight_Parameters(self, event):
        self.canvas.Show(False)
        set_weight_parameters(self.params, self)
        self.canvas.Show(True)

    def Save_Parameters_As(self, event):
        save_parameters_as(self.params, self)

    def Set_Parameter_Structure(self, event):
        set_parameter_structure(self.params, self)

    def Load_Parameters(self, event):
        p = load_parameters(None, self)
        if p:
            self.params = p

    def CreateMenu(self):

        menubar = MenuBar()

        menu = Menu(self)
        menu.Append("L&oad State",
                    self.Load_Simulation,
                    "Load a Complete Simulation",
                    hotkey="Ctrl+O")
        menu.Append("Load &Parameters", self.Load_Parameters,
                    "Load Simulation Parameters")
        menu.AppendSeparator()
        menu.Append("Save Parameters As...", self.Save_Parameters_As,
                    "Save Simulation Parameters")
        menu.Append("Save State As...", self.Save_Simulation_As,
                    "Save a Complete Simulation")
        menu.Append("Save State",
                    self.Save_Simulation,
                    "Save a Complete Simulation",
                    hotkey="Ctrl+S")
        menu.AppendSeparator()
        menu.Append("&Run/Pause",
                    self.Run_Pause,
                    "Run a Simulation",
                    hotkey="Ctrl+P")
        menu.Append("Restart from Current State", self.Restart)
        menu.Append("Reset Simulation", self.Reset_Simulation, hotkey="Ctrl+R")
        menu.AppendSeparator()
        menu.Append("Export Figure...", self.Export, "Export the Screen")
        menu.Append("&Quit", self.Quit, "Quit", hotkey="Ctrl+Q")

        menubar.Append(menu, "&File")

        menu = Menu(self)
        menu.Append("&Simulation Parameters", self.Set_Simulation_Parameters)
        menu.Append("&Input Parameters", self.Set_Input_Parameters)
        menu.Append("&Output Neuron Parameters", self.Set_Output_Parameters)
        menu.Append("&Weight Parameters", self.Set_Weight_Parameters)
        menu.AppendSeparator()
        menu.Append("&Display", self.Display)
        menu.Append("Make &New Input Files", self.Nop)
        menu.Append("Parameter Structure", self.Set_Parameter_Structure)

        menubar.Append(menu, "&Edit")

        menu = Menu(self)
        menu.Append("&Help", self.Nop)
        menu.Append("&About", self.About)
        menubar.Append(menu, "&Help")

        self.SetMenuBar(menubar)
        self.CreateStatusBar()

    def Display(self, event=None):

        self.canvas.Show(False)
        dlg = FileDialog(self,
                         "Choose Display Module",
                         default_dir=os.getcwd() + "/",
                         wildcard='Python Plot Files|plot*.py|All Files|*.*')
        result = dlg.ShowModal()
        dlg.Destroy()

        if result == 'ok':
            lfname = dlg.GetPaths()[0]
            modulename = os.path.splitext(os.path.split(lfname)[-1])[0]

            self.params['display_module'] = modulename

            if os.path.exists(self.tmpfile):
                sim = zpickle.load(self.tmpfile)
                self.Plot(sim)

        self.canvas.Show(True)

    def About(self, event):

        win = AboutWindow()
        win.Show()

    def Nop(self, event):
        self.canvas.Show(False)
        dlg = MessageDialog(self,
                            "Error",
                            "Function Not Implemented",
                            icon='error')
        dlg.ShowModal()
        dlg.Destroy()
        self.canvas.Show(True)

    def Export(self, event=None):
        export_fig(self)

    def Quit(self, event=None):

        if self.running:
            self.quitting = True
            self.stopping = True
            return

        self.canvas.Show(False)
        if self.modified:
            (root, sfname) = os.path.split(self.params['save_sim_file'])
            dlg = MessageDialog(
                self,
                text="Do you want to save the changes you made to %s?" %
                sfname,
                title="Quit",
                ok=0,
                yes_no=1,
                cancel=1)
            result = dlg.ShowModal()
            dlg.Destroy()

            if result == 'cancel':
                self.canvas.Show(True)
                return
            elif result == 'yes':
                self.Save_Simulation()

        self.Close()
        if os.path.exists(self.tmpfile):
            os.remove(self.tmpfile)
Пример #11
0
    def show_plot(name, plot_args):
        pwin = wx.Frame(root, -1, name)

        #iplot.figure.clear() #delaxes(plot)
        figure = Figure(facecolor='#ffffff')
        plot = [gen_plot(figure, plot_args)]

        #iplot.figure.clear()
        #iplot.figure.add_axes(plot)

        frame_box = wx.BoxSizer(wx.VERTICAL)
        pwin.SetSizer(frame_box)

        graph_panel = wx.Panel(pwin, -1, style=wx.SUNKEN_BORDER)
        graph_vbox = wx.BoxSizer(wx.VERTICAL)
        graph_panel.SetSizer(graph_vbox)

        canvas = FigureCanvasWx(graph_panel, -1, figure)
        canvas.draw()
        graph_vbox.Add(canvas, 1, wx.ALL | wx.EXPAND)

        toolbar = NavigationToolbar2Wx(canvas)
        toolbar.Realize()
        graph_vbox.Add(toolbar, 0, wx.LEFT | wx.EXPAND)
        toolbar.update()

        edit_panel = wx.Panel(pwin, -1, style=wx.SUNKEN_BORDER)
        edit_box = wx.GridSizer(4, 2)
        edit_panel.SetSizer(edit_box)

        grid_items = []

        def make_entry(name, default=''):
            grid_items.append((wx.StaticText(edit_panel, -1, name), 0, 0))
            id = wx.NewId()
            entry = wx.TextCtrl(edit_panel, id, default)  #, size=(150, -1))
            grid_items.append((entry, 1, wx.RIGHT | wx.EXPAND))
            return entry

        def set_attributes(*args):
            try:
                if hasattr(plot[0], 'iplot_errorbar'):
                    loc = {}
                    try:
                        expression, initial = expr_entry.GetValue().split('@')
                        symbols, points = ifit.read_min_mean_max_file(
                            plot[0].filename)
                        fit=ifit.IFit(expression,points,symbols,\
                               condition=cond_entry.GetValue())
                        variables = ifit.restricted_eval(
                            'dict(%s)' % initial, loc)
                        variables, least_squares, hessian = fit.fit(
                            **variables)
                        fit.scatter_points = 0
                        if scatter_entry.GetValue():
                            fit.scatter_points = int(scatter_entry.GetValue())
                        if fit.scatter_points:
                            fit.iterative_fit(default_output_prefix \
                               + '_scatter.csv', **variables)
                        for key, value in variables.items():
                            log_msg('%s = %g' % (key, value))
                        log_msg('least_squares=%s' % least_squares)
                        log_msg('hessian=%s' % str(hessian))
                        bound_min, bound_max = \
                           plot[0].get_xaxis().get_data_interval().get_bounds()
                        if bound_min == bound_max:
                            return
                        new_ydata = []
                        new_xdata = numpy.arange(bound_min, bound_max, \
                               (bound_max - bound_min) / 200.0, numpy.float)
                        # str() to convert from unicode
                        #extrapolate_variable = str(extrap_entry.GetValue())
                        #if fit.scatter_points:
                        #    extrap = lambda f, c: fit.extrapolate_with_errors(**c)
                        #else:
                        #    extrap = lambda f, c: fit.extrapolate(**c)
                        #for item in new_xdata:
                        #    coordinates = {extrapolate_variable:item}
                        #    #coordinates=ifit.restricted_eval('dict(%s)' % item,loc)
                        #    e = extrap(fit, coordinates)
                        #    new_ydata.append(e)
                        #    print 'extrapolation %s -> %s' % (item,str(e))
                        #### replaced by
                        for item in new_xdata:
                            new_ydata.append(fit.f(**{IPlot.indices[0]: item}))
                        plot[0] = gen_plot(figure, plot_args)
                        if fit.scatter_points:
                            low, mid, high = [], [], []
                            for h, m, l in new_ydata:
                                low.append(l)
                                mid.append(m)
                                high.append(h)
                            plot[0].plot(new_xdata, low, color='#ff5555')
                            plot[0].plot(new_xdata, mid, color='#ff0000')
                            plot[0].plot(new_xdata, high, color='#bb0000')
                        else:
                            plot[0].plot(new_xdata, new_ydata, color='r')
                    except Exception, e:
                        log_msg(e)
                        log_msg('NO FIT')
                plot[0].set_xlabel(xlabel_entry.GetValue())
                plot[0].set_ylabel(ylabel_entry.GetValue())
                plot[0].set_title(title_entry.GetValue())
                plot[0].set_axis_bgcolor(background_entry.GetValue())
                figure.set_facecolor(background_entry.GetValue())
                canvas.draw()
            except Exception, e:
                traceback.print_tb(sys.exc_info()[2])
                dlg = wx.MessageDialog(None, 'Error setting preferences:\t' + \
                        str(e), style=wx.ICON_ERROR | wx.OK)
                dlg.ShowModal()
Пример #12
0
class MainFrame(Frame):
    def __init__(self, x, y, style, parent=None):
        self.fig = None
        Frame.__init__(self, parent, 'Plot', 'H', size=(750, 750))
        self.x = x
        self.y = y
        self.style = style
        self.Plot()

    def Body(self):

        self.CreateMenu()
        self.CenterOnScreen()

        self.fig = Figure(figsize=(7, 5), dpi=100)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.figmgr = FigureManager(self.canvas, 1, self)

        self.axes = [self.fig.add_subplot(111)]

    def CreateMenu(self):

        menubar = MenuBar()

        menu = Menu(self)
        menu.Append("&Run", self.Run, "Run", hotkey="Ctrl+R")
        menu.Append("Export Figure...", self.Export, "Export the Screen")
        menu.Append("&Quit", self.Quit, "Quit", hotkey="Ctrl+Q")

        menubar.Append(menu, "&File")
        self.running = False

        self.SetMenuBar(menubar)
        self.CreateStatusBar()

    def Export(self, event=None):
        export_fig(self)

    def Run(self, event=None):

        if self.running:
            self.y = self.y_bak
            self.UpdatePlot()

        else:
            t = 0.0
            self.y_bak = self.y

            for t in linspace(0, 2 * pi * 4, 100):
                self.y = y * cos(t)
                self.UpdatePlot()

        self.running = not self.running

    def UpdatePlot(self):
        self.h.set_ydata(self.y)
        self.canvas.draw()
        self.canvas.gui_repaint()
        wx.Yield()

    def Plot(self):
        self.axes[0].clear()
        self.h, = self.axes[0].plot(self.x, self.y, self.style, linewidth=3)

        self.canvas.draw()
        self.canvas.gui_repaint()

    def Quit(self, event=None):
        self.Close()
Пример #13
0
class PlotFigure(wx.Window):
#============================================================================
    def __init__(self,parent,size=wx.DefaultSize, filename=None, options=None):

        wx.Window.__init__( self, parent, id=-1, style=wx.NO_BORDER)
        self.fig = Figure((21,21),60)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.choice=PlotChoice(self)
        self.choice.mode="Standard"
        self.toolbar.Realize()
        self.parent=parent
        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))
        
        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        self.Fit()

        self.filename=filename
        if DEBUG :
            DEBUG_MSG("plot :"+filename)
        self.n=0
        self.ni=0
        self.vl=0
        self.vl1=0
        self.sw=0
        self.sw1=0
        self.flag_sum=False
        
        try:          
            [dirname,shortfilename]=os.path.split(filename)
            [basename,extension]=os.path.splitext(shortfilename)

            self.title=basename
            self.filename=dirname+"\\"+basename+".spe"            

            if not options:
                self.options={'units': 'ppm',
                              'titles': 'no',
                              'yoffset': '0.001',
                              'yaxis': 'yes'}
            self.grid=False
        except:
            pass

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an 
        # unmanaged toolbar in your frame
         
        return self.toolbar
    
    def read_spectra(self):
        #frequency=(i+1)*sw/n-sw/2.
        #ppm=frequency*1.e6/abs(vl)
        DEBUG_MSG("read_spectra : "+self.filename)
        
        try: #Handling filename error (Correction of a bug for NEw in file menu)
            f=open(self.filename,"rb")
        except:
            return False
        
        try: # Handling opening erros
            #first the header
            line=f.readline()    # PULSAR string
            DEBUG_MSG(rtn(line))
            line=f.readline()    # NP string
            DEBUG_MSG(rtn(line))
            items=line.split('=')
            n=int(items[1])     
            line=f.readline()    # SW string
            DEBUG_MSG(rtn(line))
            items=line.split('=')
            sw=float(items[1])
            line=f.readline()    # VL
            DEBUG_MSG(rtn(line))
            items=line.split('=')
            vl=float(items[1])
            line=f.readline()    # NI or LB string?
            DEBUG_MSG(rtn(line))
            items=line.split('=')
            ni=1 #by default
            if string.strip(items[0])=="NI":     
                ni=int(items[1])
                line=f.readline()    #SW1
                DEBUG_MSG(rtn(line))
                items=line.split('=')
                sw1=float(items[1])
                line=f.readline()    #VL1
                DEBUG_MSG(rtn(line))
                items=line.split('=')
                vl1=float(items[1])
                line=f.readline()    #SUM
                DEBUG_MSG(rtn(line))
                items=line.split('=')
                flag_sum=eval(string.upper(items[1]))
                line=f.readline()    # LB string
                DEBUG_MSG(rtn(line))
                items=line.split('=')     
            #now we have to read LB
            self.lb=[]
            self.lb.append(float(items[1]))
            #and GB
            line=f.readline()
            DEBUG_MSG(rtn(line))
            items=line.split('=')
            self.gb=[]
            self.gb.append(float(items[1]))
            #and CONCENTRATION
            line=f.readline() 
            DEBUG_MSG(rtn(line))
            items=line.split('=')
            self.concentration=[]
            self.concentration.append(float(items[1]))
            if ni>1:
                for j in range(ni-1):
                    line=f.readline() #LB
                    DEBUG_MSG(rtn(line))
                    items=line.split('=')
                    self.lb.append(float(items[1]))
                    line=f.readline() #GB
                    DEBUG_MSG(rtn(line))
                    items=line.split('=')
                    self.gb.append(float(items[1]))
                    line=f.readline() #concentration
                    DEBUG_MSG(rtn(line))
                    items=line.split('=')
                    self.concentration.append(float(items[1])) 

            self.ydata = []
            self.spec = []
            
            line=f.readline() # read TYPE
            DEBUG_MSG(rtn(line))

            line=f.readline()  # read YDATA or XDATA
            DEBUG_MSG(rtn(line))

        except: # There was an error
            WRITE_STRING("***ERROR***: Badly formatted header")
            f.close()
            return false

        if string.find(line,"YDATA")>-1: # check if there is a YDATA directive
            try:     
                self.label=string.join(string.split(line)[1:],' ')
                print self.label
                print ni
                for j in range(ni):
                    line=f.readline()
                    if not isinstance(line,str):
                        self.ydata.append(float(line))
                    else:
                        self.ydata.append(line)
            except:
                WRITE_ERROR("bad YDATA labels")
                f.close()
                return false

            line=f.readline()
            DEBUG_MSG(rtn(line)) # read XDATA

        try:
            for j in range(ni):
                DEBUG_MSG("\treading spectrum"+str(j+1))
                xy = []
                DEBUG_MSG("n %13i"%n)
                for i in range(n):
                    line=f.readline()
                    items=line.split(' ')
                    x=float(items[0])
                    y=float(items[1])
                    xy.append(complex(x,y)*self.concentration[j])
                DEBUG_MSG("end reading "+str(j+1))
                self.spec.append(array(xy))

            line=f.readline()       
            DEBUG_MSG(rtn(line))
            if string.find(line,"END")>-1:
                DEBUG_MSG("reading file success!")
        except:
            WRITE_STRING("***ERROR***: problem when reading X,Y data in the *.spe file!")
            f.close()
            return false
            
        self.frequency, self.ppm = [], []
        for i in range(n):
            self.frequency.append((i+1)*sw/n-sw/2.)
            self.ppm.append(((i+1)*sw/n-sw/2.)*1.e6/abs(vl))

        #save some data as class properties
        self.n=n
        self.ni=ni
        self.vl=vl
        self.sw=sw
        if ni > 1:
            self.vl1=vl1
            self.sw1=sw1
            self.flag_sum=flag_sum
            
        #perform the fft and broadening
        addlb(ni, self.spec, self.sw, self.lb, self.gb, self.concentration)

        #sum of the spectra
        if self.flag_sum:
            p=[]
            for i in range (n):
                sum=complex(0.,0.)
                for j in range(ni):
                    sum=sum+self.spec[j][i]
                p.append(sum)      
            self.spec.append(array(p))
            self.ni=ni+1    
        return True
    
    #------------------------------------------------    
    def plot_data(self,mode=None, offset=None):
    #------------------------------------------------
        """ PLOT_SPECTRA:
        Plot one or more 1D spectra on the same figure
        """

        if not mode or mode=='reset':
            try:
                if not self.read_spectra(): return False
            except:
                return False
            
            self.maxi=0
            for j in range(self.ni):
                mxi=max(map(abs,self.spec[j]))
                self.maxi=max(mxi,self.maxi)
                self.offset=0
                
            if self.ni<6:
                mode='standard'
            else:
                mode='popt'

        else:
            mode= string.lower(mode)

##        if mode == 'reset' :
##            try:
##                if not self.read_spectra(): return False
##            except:
##                return False
##                
##            self.maxi=0
##            for j in range(self.ni):
##                mxi=max(map(abs,self.spec[j]))
##                self.maxi=max(mxi,self.maxi)
##            self.offset=0

        mx=self.ni+1
        self.dlg = wx.ProgressDialog("Spectrum plotting",
                       "...wait...",
                       maximum = mx+1,
                       parent=self,
                        # style = wx.PD_CAN_ABORT
                        #| wx.PD_APP_MODAL
                        #| wx.PD_ELAPSED_TIME
                        #| wx.PD_ESTIMATED_TIME
                        #| wx.PD_REMAINING_TIME
                           )

        keepGoing = True
        count = 0
        self.fig.clear()
        self.plotdata = self.fig.add_subplot(111)
        if offset :
            self.offset=offset
        else:
            self.offset=0

        #------------------
        if mode == "popt":

            if self.ni == 1:
                mode=="standard"
            else:
                self.fig.clear()
                self.plotdat=None
                self.plotdata = self.fig.add_subplot(111)
                xticks=[]
                xtickslabel=[]
                spacing=10*(round(log10(self.ni))-1)
                DEBUG_MSG("%5i %5i"%(self.ni, spacing))
                if spacing<2: spacing=2
                for i in range(self.ni):
                    X=[float(self.n-j-1+i*self.n)/self.n for j in range(self.n)]
                    if self.ydata:
                        if i%spacing==0:
                            xticks.append(float(self.n/2+i*self.n)/self.n)
                            if not isinstance(self.ydata[i],str):
                                xtickslabel.append(string.strip(str('%10.3f'%float(self.ydata[i]))))
                            else:
                                xtickslabel.append(string.strip(str('%s'%self.ydata[i])))
                            
                    Y=[k.real for k in self.spec[i]]
                    self.plotdata.plot(X, array(Y))
                    count += 1
                    keepGoing = self.dlg.Update(count)

                self.plotdata.set_xlabel('Index')   
                if self.ydata:
                    self.plotdata.set_xticks(xticks)   
                    self.plotdata.set_xticklabels(xtickslabel)
                    self.plotdata.set_xlabel(self.label)
                    
                self.plotdata.set_ylabel('Intensity (a.u.)\n\n')                   
                self.plotdata.set_title("POPT display, "+self.title)
                self.plotdata.grid(self.grid)
            
        #------------------
        if mode == "popt 2d":
            if self.ni == 1:
                mode=="standard"
            else:                
                self.fig.clear()
                self.plotdata = self.fig.add_subplot(111)

                count += 1
                keepGoing = self.dlg.Update(count)

                X=[]
                Y=[]
                Z=[]
                X=self.ppm
                Y=range(self.ni)
                yticks=[]
                ytickslabel=[]
                spacing=10*(round(log10(self.ni))-1)
                if spacing<2: spacing=2
                maxi=0.
                mini=0.
                for i in range(self.ni):
                    Zt=[k.real for k in self.spec[i]]
                    mxi=max(map(abs,Zt))
                    mni=min(map(abs,Zt))
                    maxi=max(maxi,mxi)
                    mini=min(mini,mni)
                    Z.append(array(Zt))
                    if self.ydata:
                        if i%spacing==0:
                            yticks.append(i)
                            ytickslabel.append(string.strip(str('%10.3f'%self.ydata[i])))
                amp=(maxi-mini)
                levels=arange(mini-amp*.05,maxi+amp*.05,amp/self.ni)
                print mini,maxi
                cmap=pylab.cm.get_cmap('jet', len(levels)-1)
                
                cset = self.plotdata.contourf(X, Y, Z, levels, cmap=cmap,)

                #cset2 = self.plotdata.contour(X, Y, Z, cset.levels,
                #        colors = 'k',
                #        hold='on')
                self.plotdata.set_xlim(self.ppm[len(self.ppm)-1],self.ppm[0])
                self.plotdata.set_xlabel('Chemical shift (ppm)')
                self.plotdata.set_ylabel('Index\n')
                if self.ydata:
                    self.plotdata.set_yticks(yticks)   
                    self.plotdata.set_yticklabels(ytickslabel)
                    self.plotdata.set_ylabel(self.label+'\n')

                self.plotdata.set_title("POPT 2D display, "+self.title)
    ##                clabels=[mini,0.,maxi]
    ##                self.fig.colorbar(cset,clabels=clabels)
    ##                #self.plotdata.grid(self.grid)


        if mode == 'reset' or mode=="standard" :
            #print string.lower(self.options['units'])
            if string.lower(self.options['units'])=="hz":
                for i in range(self.ni):
                    spec=[]
                    shift=(i+1)*self.offset*self.maxi           
                    spec=[shift + x.real for x in self.spec[i]]
                    self.plotdata.plot(self.frequency, array(spec))
                    count += 1
                    keepGoing = self.dlg.Update(count)
                self.plotdata.set_xlim(self.frequency[len(self.frequency)-1],self.frequency[0])
                self.plotdata.set_xlabel('Frequency (Hz)')
            else:
                for i in range(self.ni):
                    shift=(i+1)*self.offset*self.maxi           
                    spec=[shift + x.real for x in self.spec[i]]
                    self.plotdata.plot(self.ppm, array(spec))
                    count += 1
                    keepGoing = self.dlg.Update(count)
                self.plotdata.set_xlim(self.ppm[len(self.ppm)-1],self.ppm[0])
                self.plotdata.set_xlabel('Chemical shift (ppm)')
            if string.lower(self.options['yaxis'])!="no": 
                self.plotdata.set_ylabel('Intensity (a.u.)\n')
            else:    
                self.plotdata.set_yticks([])   
                self.plotdata.set_yticklabels([])         
            self.plotdata.set_title(self.title)
            self.plotdata.grid(self.grid)

       #update everything and exit
        self.canvas.draw()
        self.toolbar.update()

        self.dlg.Destroy()
        return True
Пример #14
0
class MainFrame(Frame):

    def __init__(self,parent=None,title='',direction='H',
                    size=(800,800),lfname=None):
        self.fig=None
        
        # turn off security warning on tmpnam.  why is it here?
        warnings.filterwarnings('ignore')    
        fname=os.tempnam()
        warnings.resetwarnings()
        
        
        self.base_dir=os.path.dirname(__file__)
        if not self.base_dir:
            self.base_dir='.'
            
        self.tmpfile=fname+"_plasticity.dat"
        self.modified=False
        self.running=False
        self.stopping=False
        self.quitting=False
        self.plot_first=False
        
        self.params=default_params()
        
        for p in self.params['pattern_input']:
            p['filename']=self.base_dir+"/"+p['filename']
        
        
        if lfname:
            if not self.__load_sim__(lfname):
                self.plot_first=True


        Frame.__init__(self,parent,title,direction,size)
    
    def Body(self):
        
        self.CreateMenu()
        self.CenterOnScreen()
        
        self.ResetTitle()
        
        fname=self.base_dir+"/images/plasticity_small_icon.ico"
        self.SetIcon(fname)
        
        self.fig = Figure(figsize=(7,5),dpi=100)
        self.axes = [self.fig.add_subplot(221),
                    self.fig.add_subplot(222),
                    self.fig.add_subplot(223),
                    self.fig.add_subplot(224)]
                    
        self.canvas = FigureCanvas(self, -1, self.fig)
        
        if self.plot_first:
            sim=zpickle.load(self.tmpfile)
            self.Plot(sim)

    def Stopping(self):
        return self.stopping
    
    def Yield(self):
        wx.Yield()
    
    def ResetTitle(self):
        
        (root,sfname)=os.path.split(self.params['save_sim_file'])
        if self.modified:
            s=' (*)'
        else:
            s=''
            
        title='Plasticity: %s%s' % (sfname,s)
        self.SetTitle(title)

        
    def Plot(self,sim):
        
        if not sim['params']['display']:
            return

        if sim['params']['display_module']:
            try:
                module=__import__(sim['params']['display_module'],fromlist=['UserPlot'])
            except ImportError:
                sim['params']['display']=False
                dlg = MessageDialog(self, 
                        "Error","Error in Import: %s.  Turning display off" % sim['params']['display_module'],
                        icon='error')
                dlg.ShowModal()
                dlg.Destroy()
                return
            
            try:
                module.UserPlot(self,sim)
                return
            except ValueError:
                sim['params']['display']=False
                dlg = MessageDialog(self, 
                        "Error","Error in display.  Turning display off",
                        icon='error')
                dlg.ShowModal()
                dlg.Destroy()
                return
        
        try:
        
            im=weights2image(sim['params'],sim['weights'])
            
            self.axes[0].hold(False)
            self.axes[0].set_axis_bgcolor('k')
            self.axes[0].pcolor(im,cmap=gray)
            self.axes[0].set_aspect('equal')
            
            num_moments=sim['moments_mat'].shape[0]
    
            self.axes[1].hold(False)
            for i in range(num_moments):
                self.axes[1].plot(sim['moments_mat'][i,0,:],'-o')
                self.axes[1].hold(True)
            
    
            self.axes[2].hold(False)
            response_mat=sim['response_mat']
            response_var_list=sim['response_var_list']
            styles=['b-o','g-o']
            for i,r in enumerate(response_var_list[-1]):
                x=r[1]
                y=r[2]
            
                self.axes[2].plot(x,y,styles[i])
                self.axes[2].hold(True)
            
                
            self.axes[3].hold(False)
            styles=['b-o','g-o']
            for i,r in enumerate(response_mat):
                self.axes[3].plot(r,styles[i])
                self.axes[3].hold(True)
            
            
                
            self.canvas.draw()
            
        except ValueError:
            sim['params']['display']=False
            dlg = MessageDialog(self, 
                    "Error","Error in display.  Turning display off",
                    icon='error')
            dlg.ShowModal()
            dlg.Destroy()
            
            
    
    def Run_Pause(self,event):

        if not self.running:
#            pylab.close()
            
            self.params['tmpfile']=self.tmpfile
            if os.path.exists(self.tmpfile):
                self.params['continue']=1
            self.modified=True
            self.ResetTitle()
            self.running=True

##            d={}
##            d['params']=self.params
##            zpickle.save(d,'plasticity_tmpparams.dat')
##            cmd='./run_sim.py --paramfile plasticity_tmpparams.dat --from_gui 1'
##            os.system(cmd)
            self.stopping=False
            run_sim(self.params,self)

            self.params['load_sim_file']=self.tmpfile
            self.running=False
            if self.quitting:
                self.Quit()
        
        else:
            self.stopping=True
    
            
    def __load_sim__(self,lfname):
        
        sim=zpickle.load(lfname)

        params=sim['params']
        
        params['save_sim_file']=self.params['save_sim_file']
        params['load_sim_file']=''
        params['continue']=False
        
        try:
            params['initial_weights']=sim['weights']
            params['initial_moments']=sim['moments']
        except KeyError:
            self.params=params
            return 1

        params['load_sim_file']=self.tmpfile
        params['continue']=True
        sim['params']=params
        self.params=params
        
        zpickle.save(sim,self.tmpfile)
        
        return 0

    def Reset_Simulation(self,event=None):
        if not os.path.exists(self.tmpfile):
            return

        
        self.canvas.Show(False)
        if self.modified:
            (root,sfname)=os.path.split(self.params['save_sim_file'])
            dlg=MessageDialog(self, 
                          text="Do you want to save the changes you made to %s?" % sfname,
                          title="Reset", ok=0, yes_no=1,cancel=1)
            result=dlg.ShowModal()
            dlg.Destroy()
            
            if result == 'cancel':
                self.canvas.Show(True)
                return
            elif result == 'yes':
                filename=self.Save_Simulation()
                if not filename: # cancelled the save
                    self.canvas.Show(True)
                    return
        
        
        
        self.params['continue']=False
        self.params['load_sim_file']=''
        

        for a in self.axes:
            
            a.cla()

        self.canvas.draw()    
        self.canvas.Show(True)
        
        
        
        
    def Restart(self,event=None):
        
        if not os.path.exists(self.tmpfile):
            return
        
        self.canvas.Show(False)
        if self.modified:
            (root,sfname)=os.path.split(self.params['save_sim_file'])
            dlg=MessageDialog(self, 
                          text="Do you want to save the changes you made to %s?" % sfname,
                          title="Restart", ok=0, yes_no=1,cancel=1)
            result=dlg.ShowModal()
            dlg.Destroy()
            
            if result == 'cancel':
                self.canvas.Show(True)
                return
            elif result == 'yes':
                filename=self.Save_Simulation()
                if not filename: # cancelled the save
                    self.canvas.Show(True)
                    return
        
        
        
        
        self.__load_sim__(self.tmpfile)
        self.params['continue']=False
        self.canvas.Show(True)
        
        
    def Load_Simulation(self,event=None):

        self.canvas.Show(False)
        if self.modified:
            (root,sfname)=os.path.split(self.params['save_sim_file'])
            dlg=MessageDialog(self, 
                          text="Do you want to save the changes you made to %s?" % sfname,
                          title="Load Simulation", ok=0, yes_no=1,cancel=1)
            result=dlg.ShowModal()
            dlg.Destroy()
            
            if result == 'cancel':
                pass
            elif result == 'yes':
                self.Save_Simulation()
                
        lfname=''    
        dlg = FileDialog(self, "Load Simulation",default_dir=os.getcwd()+"/sims",
                        wildcard='DAT Files|*.dat|All Files|*.*')
        result = dlg.ShowModal()
        if result == 'ok':
            lfname = dlg.GetPaths()[0]
        dlg.Destroy()

        if not lfname:
            self.canvas.Show(True)
            return
        
        self.__load_sim__(lfname)
            
        sim=zpickle.load(self.tmpfile)
        self.Plot(sim)
        self.canvas.Show(True)
            
    def Save_Simulation(self,event=None):
        
        if not self.modified:
            return
        
        sfname=self.params['save_sim_file']
        def_sfname=default_params()['save_sim_file']
        if sfname==def_sfname:
            filename=self.Save_Simulation_As()
            
            
        else:
            filename=sfname
            d=zpickle.load(self.tmpfile)
            d['params']=self.params
            zpickle.save(d,sfname)
            
            self.modified=False
            
            self.ResetTitle()

        return filename
    
    def Save_Simulation_As(self,event=None):
        
        self.canvas.Show(False)
        dlg = FileDialog(self, "Save Simulation As...",default_dir=os.getcwd()+"/sims/",
                        wildcard='DAT Files|*.dat|All Files|*.*',save=1)
        result = dlg.ShowModal()
        if result == 'ok':
            filename = dlg.GetPaths()[0]
        else:
            filename=None
            
        dlg.Destroy()

            
        if filename:
            d=zpickle.load(self.tmpfile)
            self.params['save_sim_file']=filename
            d['params']=self.params
            zpickle.save(d,filename)
            
            self.modified=False
            
            self.ResetTitle()
        
        self.canvas.Show(True)
            
        return filename
    
    def Set_Simulation_Parameters(self,event):
        self.canvas.Show(False)
        set_simulation_parameters(self.params,self)
        self.canvas.Show(True)
        
    def Set_Input_Parameters(self,event):
        self.canvas.Show(False)
        set_input_parameters(self.params,self)
        self.canvas.Show(True)
        
    def Set_Output_Parameters(self,event):
        self.canvas.Show(False)
        set_output_parameters(self.params,self)
        self.canvas.Show(True)
        
    def Set_Weight_Parameters(self,event):
        self.canvas.Show(False)
        set_weight_parameters(self.params,self)
        self.canvas.Show(True)

    def Save_Parameters_As(self,event):
        save_parameters_as(self.params,self)
        
    def Set_Parameter_Structure(self,event):
        set_parameter_structure(self.params,self)

    def Load_Parameters(self,event):
        p=load_parameters(None,self)
        if p:
            self.params=p
        
    def CreateMenu(self):
    
        
        menubar = MenuBar()

        menu = Menu(self)
        menu.Append("L&oad State", self.Load_Simulation, "Load a Complete Simulation",hotkey="Ctrl+O")
        menu.Append("Load &Parameters", self.Load_Parameters, "Load Simulation Parameters")
        menu.AppendSeparator()
        menu.Append("Save Parameters As...", self.Save_Parameters_As, "Save Simulation Parameters")
        menu.Append("Save State As...", self.Save_Simulation_As, "Save a Complete Simulation")
        menu.Append("Save State", self.Save_Simulation, "Save a Complete Simulation",hotkey="Ctrl+S")
        menu.AppendSeparator()
        menu.Append("&Run/Pause", self.Run_Pause, "Run a Simulation",hotkey="Ctrl+P")
        menu.Append("Restart from Current State", self.Restart)
        menu.Append("Reset Simulation", self.Reset_Simulation,hotkey="Ctrl+R")
        menu.AppendSeparator()
        menu.Append("Export Figure...", self.Export, "Export the Screen")
        menu.Append("&Quit", self.Quit, "Quit",hotkey="Ctrl+Q")

        menubar.Append(menu, "&File")

        
        menu = Menu(self)
        menu.Append("&Simulation Parameters", self.Set_Simulation_Parameters)
        menu.Append("&Input Parameters",  self.Set_Input_Parameters)
        menu.Append("&Output Neuron Parameters", self.Set_Output_Parameters)
        menu.Append("&Weight Parameters", self.Set_Weight_Parameters)
        menu.AppendSeparator()
        menu.Append("&Display", self.Display)
        menu.Append("Make &New Input Files", self.Nop)
        menu.Append("Parameter Structure", self.Set_Parameter_Structure)
    
        menubar.Append(menu, "&Edit")

        menu=Menu(self)
        menu.Append("&Help", self.Nop)
        menu.Append("&About", self.About)
        menubar.Append(menu, "&Help")
        
        self.SetMenuBar(menubar)
        self.CreateStatusBar()

        
    def Display(self,event=None):

        self.canvas.Show(False)
        dlg = FileDialog(self, "Choose Display Module",default_dir=os.getcwd()+"/",
                        wildcard='Python Plot Files|plot*.py|All Files|*.*')
        result = dlg.ShowModal()
        dlg.Destroy()

        if result == 'ok':
            lfname = dlg.GetPaths()[0]
            modulename=os.path.splitext(os.path.split(lfname)[-1])[0]

            self.params['display_module']=modulename
            
            if os.path.exists(self.tmpfile):
                sim=zpickle.load(self.tmpfile)
                self.Plot(sim)
                
            
        self.canvas.Show(True)
            
        
        
    def About(self,event):

        win=AboutWindow()
        win.Show()
        

    def Nop(self,event):
        self.canvas.Show(False)
        dlg = MessageDialog(self, "Error","Function Not Implemented",icon='error')
        dlg.ShowModal()
        dlg.Destroy()
        self.canvas.Show(True)

    def Export(self,event=None):
        export_fig(self)
    
    def Quit(self,event=None):
        
        if self.running:
            self.quitting=True
            self.stopping=True
            return
        
        self.canvas.Show(False)
        if self.modified:
            (root,sfname)=os.path.split(self.params['save_sim_file'])
            dlg=MessageDialog(self, 
                          text="Do you want to save the changes you made to %s?" % sfname,
                          title="Quit", ok=0, yes_no=1,cancel=1)
            result=dlg.ShowModal()
            dlg.Destroy()
            
            if result == 'cancel':
                self.canvas.Show(True)
                return
            elif result == 'yes':
                self.Save_Simulation()

        
        self.Close()
        if os.path.exists(self.tmpfile):
            os.remove(self.tmpfile)
Пример #15
0
class PlotFrame(Frame):

    def __init__(self,parent=None,title='',direction='H',
                    size=(800,800)):
        self.fig=None

        Frame.__init__(self,parent,title,direction,size)


    def Body(self):
        
        self.CenterOnScreen()
        self.params=default_params()
        self.ResetTitle()
        
        self.fig = Figure(figsize=(7,5),dpi=100)
        self.axes = [self.fig.add_subplot(221),
                    self.fig.add_subplot(222),
                    self.fig.add_subplot(223),
                    self.fig.add_subplot(224)]
                    
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.CreateStatusBar()
        
        self.Show()

    def ResetTitle(self):
        
        (root,sfname)=os.path.split(self.params['save_sim_file'])
        s=''
            
        title='Plasticity: %s%s' % (sfname,s)
        self.SetTitle(title)

        
    def Plot(self,sim):
        
        sim['params']['display']=True

        if 'display_module' in sim['params']:
            if sim['params']['display_module']:
                try:
                    module=__import__(sim['params']['display_module'],fromlist=['UserPlot'])
                except ImportError:
                    sim['params']['display']=False
                    dlg = MessageDialog(self, 
                            "Error","Error in Import: %s.  Turning display off" % sim['params']['display_module'],
                            icon='error')
                    dlg.ShowModal()
                    dlg.Destroy()
                    return
                
                try:
                    module.UserPlot(self,sim)
                    return
                except ValueError:
                    sim['params']['display']=False
                    dlg = MessageDialog(self, 
                            "Error","Error in display.  Turning display off",
                            icon='error')
                    dlg.ShowModal()
                    dlg.Destroy()
                    return
        
        try:
        
            im=weights2image(sim['params'],sim['weights'])
            
            self.axes[0].hold(False)
            self.axes[0].set_axis_bgcolor('k')
            self.axes[0].pcolor(im,cmap=gray)
            self.axes[0].set_aspect('equal')
            
            num_moments=sim['moments_mat'].shape[0]
    
            self.axes[1].hold(False)
            for i in range(num_moments):
                self.axes[1].plot(sim['moments_mat'][i,0,:],'-o')
                self.axes[1].hold(True)
            
    
            self.axes[2].hold(False)
            response_mat=sim['response_mat']
            response_var_list=sim['response_var_list']
            styles=['b-o','g-o']
            for i,r in enumerate(response_var_list[-1]):
                x=r[1]
                y=r[2]
            
                self.axes[2].plot(x,y,styles[i])
                self.axes[2].hold(True)
            
                
            self.axes[3].hold(False)
            styles=['b-o','g-o']
            for i,r in enumerate(response_mat):
                self.axes[3].plot(r,styles[i])
                self.axes[3].hold(True)
            
            
                
            self.canvas.draw()
            
        except ValueError:
            sim['params']['display']=False
            dlg = MessageDialog(self, 
                    "Error","Error in display.  Turning display off",
                    icon='error')
            dlg.ShowModal()
            dlg.Destroy()
Пример #16
0
class MainFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,(0,0),(975,500))
        
        
        
        TopPanel = wx.Panel(self, -1)
        gauge1 = wx.Panel(TopPanel,-1)
        gauge2 = wx.Panel(TopPanel,-1)
        graph1 = wx.Panel(TopPanel,-1)
        
        #Set Panel Background Colors
        graph1.SetBackgroundColour("black")
        gauge1.SetBackgroundColour("black")
        gauge2.SetBackgroundColour("black")
        TopPanel.SetBackgroundColour("black")
        
        
        
        
        #Instantiate the Two Thermometers One for the Kiln One for ambient
        
		
		
        
        self.ambient=Thermometer(gauge1,-1,'amb_F',0,0,os.path.join('images','ambient_F.png'))
        self.kiln=Thermometer(gauge2,-1,'kiln_F_H',0,0,os.path.join('images','kiln_FH.png'))
        
        self.ambient.update_gauge(17)
        self.kiln.update_gauge(450)
        
        #Set up the Graph Panel
        self.fig = Figure((10,5),75)
        self.canvas = FigureCanvasWx(graph1,-1,self.fig)
       
        
        
        #Create the sizer
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(gauge1,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 30)
        hbox.Add(graph1,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 20)
        hbox.Add(gauge2,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 30)
        TopPanel.SetSizer(hbox)
        
        
       
       
        #Create Output Boxes
        #Displays Highest Recorded Reading
        self.HighReadingLabel = wx.StaticText(TopPanel, -1,'High Reading',(25,400))
        self.HighReadingLabel.SetForegroundColour('white')
        self.HighReading = wx.TextCtrl(TopPanel, -1,"",(25,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        #Displays Current Sample Number
        self.SampleNumLabel = wx.StaticText(TopPanel, -1,'Sample#',(125,400))
        self.SampleNumLabel.SetForegroundColour('white')
        self.SampleNum = wx.TextCtrl(TopPanel, -1,"",(125,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        
        
        
        
        
        
        
        
        
        self.Centre()
        self.Show(True)
        self.AutoSave = 'FALSE'
        
        
        self.debug = 'FALSE'
        #Unique Sensor IDs
        self.id1 = '30ED284B1000008F'
        self.id2 = '3063294B100000BB'
        self.current_sensor = self.id1
        #Starting Temperatures for the gauges
        self.ambient_F = 70
        self.kiln_F = 1000
        #Initialize the plot data arrays
        self.ambient_temp = []
        self.kiln_temp = []
        self.date_human = []
        self.date = []
        self.count = 0
        self.sample_count = 0
        self.x = []
        
        
        
        
        
        
        
        
        #Make Sure Filename is cleared
        self.filename = None
        
        #number of samples before updating graph
        self.sample_max = 5
        
        #Setup the Plotting Figure and Canvas Load Blank Graph
        self.load_graph()

        
        
        #Setup the Clock
        self.SensorTimer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER,self.OnTick,self.SensorTimer)
        
        

        #Menu Items
        ################################################
        self.menubar = wx.MenuBar()
        self.FileMenu = wx.Menu()
        self.ConfigMenu = wx.Menu()
        self.HelpMenu = wx.Menu()
        
        self.FileMenu.Append(100, '&Load', 'Load a saved Graph')
        self.FileMenu.Append(101, '&Save', 'Save the current Graph')
        self.FileMenu.Append(108, '&Save As...', 'Save the current Graph')
        self.FileMenu.Append(105, '&Start Logging', 'Start logging process')
        self.FileMenu.Append(106, '&Stop Logging', 'Stop logging process')
        self.FileMenu.Append(107, '&Clear Graph', 'Reset the Graph Panel')
        self.FileMenu.AppendSeparator()
        self.FileMenu.Append(102, '&Quit', 'Quit')
        
        self.ConfigMenu.Append(104, '&Serial Port', 'Serial Port')
        self.ConfigMenu.AppendSeparator()
        self.ConfigMenu.AppendCheckItem(110,'&AutoSave','Toggle AutoSave')
        self.ConfigMenu.AppendCheckItem(120,'&Debug','Toggle Debug')
        
        
        self.HelpMenu.Append(103,'&About', 'About')
        
        self.menubar.Append(self.FileMenu, '&File')
        self.menubar.Append(self.ConfigMenu, '&Config')
        self.menubar.Append(self.HelpMenu, '&Help')
        self.SetMenuBar(self.menubar)
        self.CreateStatusBar()
        
        #Menu Bindings Go here
        self.Bind(wx.EVT_MENU, self.OnLoad, id=100)
        self.Bind(wx.EVT_MENU, self.OnSave, id=101)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, id=108)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=103)
        self.Bind(wx.EVT_MENU, self.OnSerial, id=104)
        self.Bind(wx.EVT_MENU, self.OnLog, id=105)
        self.Bind(wx.EVT_MENU, self.OnStop, id=106)
        self.Bind(wx.EVT_MENU, self.OnClear, id=107)
        self.Bind(wx.EVT_MENU, self.OnAutoSave, id=110)
        self.Bind(wx.EVT_MENU, self.OnDebug, id=120)
        ################################################### 
        
        """
        #Button Items
        ###############################################
     

        self.save_bitmap = wx.Image(os.path.join("images",'save.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.save_button = wx.BitmapButton(self, 200, bitmap=self.save_bitmap,pos=(250, 10), size = (self.save_bitmap.GetWidth(), self.save_bitmap.GetHeight()))
        
        self.load_bitmap = wx.Image(os.path.join("images",'load.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.load_button = wx.BitmapButton(self, 201, bitmap=self.load_bitmap,pos=(350, 10), size = (self.load_bitmap.GetWidth()+5, self.load_bitmap.GetHeight()+5))
        
        self.log_bitmap = wx.Image(os.path.join("images",'log.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.log_button = wx.BitmapButton(self, 202, bitmap=self.log_bitmap,pos=(450, 10), size = (self.log_bitmap.GetWidth()+5, self.log_bitmap.GetHeight()+5))

        
        wx.EVT_BUTTON(self, 200, self.OnSave)
        wx.EVT_BUTTON(self, 201, self.OnLoad)
        wx.EVT_BUTTON(self, 202, self.OnLog)      
        ###############################################
        """
    
    
     
    def OnTick(self,event):
        #Redraw the the thermometer backgrounds
        self.ambient.OnPaint(self)
        self.kiln.OnPaint(self)
        
        #Get Celcius From First Thermo
        self.celsius = get_celsius(self.current_sensor)
        self.celsius_reverse = reverse_poly(self.celsius)
        self.ambient_F=(((self.celsius*9.0)/5.0)+32)
        time.sleep(1)
        #for i in range(1, 10):
        #    time.sleep(.1)
        
        #Get uV from first Thermo
        self.uv = get_uv(self.current_sensor)
        self.uv = self.uv + self.celsius_reverse
        self.temp_uv = convert_uv(self.uv)
        self.kiln_F = (((self.temp_uv*9.0)/5.0)+32)
        
        #Make sure thermo measurement is not less then ambient
        if (self.kiln_F < self.ambient_F):
            self.kiln_F = self.ambient_F
        
        
        
        """
        #------------------------------------------------
        #Rolling Average Filter
        #------------------------------------------------
        if len(kiln_temp) > 20:
            sensor_average = 0
            #print kiln_temp[len(kiln_temp)-10:]
            #moving_part = [len(kiln_temp)-10:]
            for sample in kiln_temp[len(kiln_temp)-20:]:    
                sensor_average = sensor_average + sample
            sensor_average = sensor_average / 20
            sensor_average = round(sensor_average,2)
            print "Ambient===>",self.ambient_F,"kiln Temp===>",self.kiln_F,"average is ==>", sensor_average
            self.kiln_F = sensor_average
        """
        
        #Update the thermometer displays
        self.ambient.update_gauge(self.ambient_F)
        if (self.kiln_F > 500):
            self.kiln.update_gauge(self.kiln_F)
            #self.kiln.update_gauge(1700)         
    
        #Update the Lists and Graph
        self.kiln_temp.append(self.kiln_F)
        self.ambient_temp.append(self.ambient_F)
    
        self.date_human.append(strftime("%a, %d %b %Y %H:%M:%S"))
        self.date.append(date2num(datetime.now()))
  
        self.x.append(self.count)
        self.count = self.count + 1
        print "Ambient===>",self.ambient_F,"kiln Temp===>",self.kiln_F,"Samples==>",self.count
        
        self.sample_count = self.sample_count + 1
        if (self.sample_count >= self.sample_max):
            self.draw_graph()
            self.sample_count = 0
        if (self.count%100 == 0) & (self.AutoSave == 'True'):
            if (self.debug == 'True'):
                print "I gots 100 samples, now ehm gonna save em"
            self.OnSave(None)
        
        
    
    def load_graph(self):
        #Set some plot attributes
        #add_subplot makes an Axes instance and puts it in the Figure instance
        #self.subplot is this Axes instance, as I had guessed.  
        #So, you can apply any Axes method to it.
        
        
        self.subplot = self.fig.add_subplot(111)
        self.subplot.set_title(r"Kiln Temperature")
        
        
    def draw_graph(self):
        if (self.debug == 'True'):
            print "updating the graph ;)"
        
        self.subplot.clear()
        self.subplot = self.fig.add_subplot(111)
        #self.subplot.set_title(r"Kiln Temperature")
        #self.subplot.xaxis.set_major_locator( DayLocator() )
        self.subplot.xaxis.set_minor_locator( HourLocator(12))
        #self.subplot.xaxis.set_major_locator( HourLocator(1))
        #self.subplot.xaxis.set_major_locator( MinuteLocator(30))
        #self.subplot.xaxis.set_major_locator( HourLocator(1))
        
        #Turn off Scientific Notation on Y Axis
        self.subplot.yaxis.set_major_formatter(ScalarFormatter(False))
        self.subplot.xaxis.set_major_formatter(DateFormatter('%H:%M'))
        self.fig.autofmt_xdate()
        self.subplot.grid(True)
        self.subplot.plot(self.date, self.kiln_temp, 'r-', linewidth = 1)
        self.canvas.draw()
    
    ##########################################################################
    ####################MENU Function Start Here##############################
    ##########################################################################
    def OnDebug(self, event):
        if (self.ConfigMenu.IsChecked(120)):
            self.debug = 'True'
            self.SetStatusText("Turning on Debug")
        else:
            self.debug = 'False'
            self.SetStatusText("Turning Off Debug")
                
    def OnAutoSave(self, event):
        if (self.debug == 'True'):
            print "Somebody clicked on Autosave"
            print self.ConfigMenu.IsChecked(110);
        if (self.ConfigMenu.IsChecked(110)):
            self.AutoSave = 'True'
            self.SetStatusText("Auto Save is on... Saving every 100 samples")
        else:
            self.AutoSave = 'False'
            self.SetStatusText("Auto Save is now off")
    
    def OnSerial(self, event):    
        for i in range(256):
            try:
                s = serial.Serial(i)
                print s.portstr
                s.close()
            except serial.SerialException:
                self.SetStatusText("Problem with the serial ports")
                
    def OnClear(self,event):
        self.SetStatusText("Clearing the current graph...")
        self.date = []
        self.kiln_temp = []
        self.HighReading.Clear()
        self.SampleNum.Clear()
        self.draw_graph()
    
    def OnStop(self,event):
        self.SetStatusText("Now stops the logging...")
        self.SensorTimer.Stop()

    def OnLog(self, event):
        self.SetStatusText("Now starts the logging...")
        #Open the serial port connection
        ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=5)
        #Startup the Timer for Sensor Readings
        self.SensorTimer.Start(3000)
   
 
    def OnAbout(self, event):
        self.SetStatusText("All about ...PyroLogger...")
        dlg = wx.MessageDialog(self, 'When you as the Pyro want to Log!  Revision .0000001 March 12, 2008', 'About Pyrologger', wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()
                   
    
    
    def OnSave(self,EVENT):
        if (self.filename == None):
            dialog = wx.FileDialog(self,"Save Graph Data...","","","Graph File (*.txt)|*.txt",wx.SAVE)
            if (dialog.ShowModal() == wx.ID_CANCEL):
                return  # canceled, bail
            # ok they saved
            self.filename = dialog.GetPath();
            self.SetTitle("PyroLogger        "+self.filename)

        try:
            file = open(self.filename, 'w')
            list_count = 0
            file.write ("Log Date and Time ")
            file.write (strftime("%a, %d %b %Y %H:%M:%S"))
            file.write ("\n")
            file.write ("Ambient Kiln Date Date2Num")
            file.write ("\n")
            file.write ("\n")
            for reading in self.date:
                value_1 = "%.2f" % self.ambient_temp[list_count]
                value_2 = "%.2f" % self.kiln_temp[list_count]
                value_3 = self.date_human[list_count]
                value_4 = "%.11f" % self.date[list_count]
                value = (list_count,value_1,value_2,value_3,value_4)
                file_line = str(value)
                file.write (file_line)
                file.write ("\n")
                list_count = list_count + 1
            file.close
            self.SetStatusText("Saved current Graph...")
        except IOError:
            self.SetStatusText("Error writing to file!")
            
    def OnSaveAs(self,EVENT):
        
        dialog = wx.FileDialog(self,"Save Graph Data...","","","Graph File (*.txt)|*.txt",wx.SAVE)
        if (dialog.ShowModal() == wx.ID_CANCEL):
            return  # canceled, bail
        # ok they saved
        self.filename = dialog.GetPath();
        self.SetTitle("PyroLogger        "+self.filename)

        try:
            file = open(self.filename, 'w')
            list_count = 0
            file.write ("Log Date and Time ")
            file.write (strftime("%a, %d %b %Y %H:%M:%S"))
            file.write ("\n")
            file.write ("Ambient Kiln Date Date2Num")
            file.write ("\n")
            file.write ("\n")
            for reading in self.date:
                value_1 = "%.2f" % self.ambient_temp[list_count]
                value_2 = "%.2f" % self.kiln_temp[list_count]
                value_3 = self.date_human[list_count]
                value_4 = "%.11f" % self.date[list_count]
                value = (list_count,value_1,value_2,value_3,value_4)
                file_line = str(value)
                file.write (file_line)
                file.write ("\n")
                list_count = list_count + 1
            file.close
            self.SetStatusText("Saved current Graph...")
        except IOError:
            self.SetStatusText("Error writing to file!")
    
    
    def OnLoad(self,EVENT):
        self.SetStatusText("Loading Graph...")
        self.SensorTimer.Stop()
        self.filename = None
            
        dialog = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN)
        if (dialog.ShowModal() == wx.ID_CANCEL):
            return  # canceled, bail
        # ok they loaded
        self.filename = dialog.GetPath()
        self.SetTitle("PyroLogger        "+self.filename)
        print "You Pressed Load"
        print "Slurping Raw Data... ummmmmm!!!"
        file = open(self.filename, 'r')
        skip = 0
        self.date = []
        self.kiln_temp = []
        
        for line in file.readlines():
            if (skip >= 3):
                #Split line up into its individual fields
                fields = line.split ('\', \'')
                self.kiln_temp.append(fields[1])
                paren = line.rfind(')')
                self.date.append(line[paren-19:paren-1])
            skip = skip + 1
        
        self.date = map(float, self.date)
        self.kiln_temp = map(float, self.kiln_temp)
        
        high = 0
        for reading in self.kiln_temp:
            if (reading > high):
                high = reading
                
        self.HighReading.Clear()
        self.HighReading.AppendText(str(high))
        
        self.SampleNum.Clear()
        self.SampleNum.AppendText(str(len(self.kiln_temp)))
        
        
        
        self.draw_graph()
Пример #17
0
class MainFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,(0,0),(975,500))
        
        
        
        self.TopPanel = wx.Panel(self, -1)
        gauge1 = wx.Panel(self.TopPanel,-1)
        gauge2 = wx.Panel(self.TopPanel,-1)
        graph1 = wx.Panel(self.TopPanel,-1)
        
        #Set Panel Background Colors
        graph1.SetBackgroundColour("black")
        gauge1.SetBackgroundColour("black")
        gauge2.SetBackgroundColour("black")
        self.TopPanel.SetBackgroundColour("black")
        
        
        
        
        #Instantiate the Two Thermometers One for the Kiln One for ambient
        #self.ambient=Thermometer(gauge1,-1,'amb_F',0,0,os.path.join("images",'ambient_F.png'))
        



        
        
        self.thermo_front=Thermometer(gauge1,-1,'kiln_F_H',0,0,os.path.join("images",'kiln_FH.png'))
        self.thermo_back=Thermometer(gauge2,-1,'kiln_F_H',0,0,os.path.join("images",'kiln_FH.png'))
        
        #self.ambient.update_gauge(17)
        self.thermo_front.update_gauge(450)
        self.thermo_back.update_gauge(450)
        
        #Set up the Graph Panel
        self.fig = Figure((10,5),75)
        self.canvas = FigureCanvasWx(graph1,-1,self.fig)
       
        
        
        #Create the sizer
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(gauge1,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 30)
        hbox.Add(graph1,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 20)
        hbox.Add(gauge2,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 30)
        self.TopPanel.SetSizer(hbox)
        
        
        self.OutputBoxes()   

        


        #Set Some Environment Variables
        self.Centre()
        self.Show(True)
        
        self.AutoSave = 'FALSE'
        self.debug = 'FALSE'
        
        self.FrontHigh = 0
        self.BackHigh= 0
        
        #Unique Sensor IDs
        self.id1 = '30ED284B1000008F'
        self.id2 = '3063294B100000BB'
        
        
        
        
        self.front_sensor = self.id1
        self.back_sensor = self.id2
        
        #Starting Temperatures for the gauges
        self.ambient = 70
        self.kiln_front = 1000
        self.kiln_back = 1000
        
        #Initialize the plot data arrays
        self.ambient_array= []
        self.kiln_front_array = []
        self.kiln_back_array = []
        self.date_human = []
        self.date = []
        self.count = 0
        self.sample_count = 0
        self.x = []
        
        
        #Make Sure Filename is cleared
        self.filename = None
        
        #number of samples before updating graph
        self.sample_max = 5
        
        #Setup the Plotting Figure and Canvas Load Blank Graph
        self.load_graph()

        
        
        #Setup the Clock
        self.SensorTimer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER,self.OnTick,self.SensorTimer)
        
        

        #Menu Items
        ################################################
        self.menubar = wx.MenuBar()
        self.FileMenu = wx.Menu()
        self.ConfigMenu = wx.Menu()
        self.SerialMenu = wx.Menu()
        self.HelpMenu = wx.Menu()
        
        self.FileMenu.Append(100, '&Load', 'Load a saved Graph')
        self.FileMenu.Append(101, '&Save', 'Save the current Graph')
        self.FileMenu.Append(108, '&Save As...', 'Save the current Graph')
        self.FileMenu.Append(105, '&Start Logging', 'Start logging process')
        self.FileMenu.Append(106, '&Stop Logging', 'Stop logging process')
        self.FileMenu.Append(107, '&Clear Graph', 'Reset the Graph Panel')
        self.FileMenu.AppendSeparator()
        self.FileMenu.Append(102, '&Quit', 'Quit')
        
    
        #Build the Configuration Menu
        # Build the Serial SubMenu
        # Get list of files in /dev
        cd = os.getcwd()
        os.chdir("/dev")
        dirdev = os.getcwd()
        fileList = os.listdir(dirdev)

        self.validPorts = list() 
        validPortCount = 0

        # Find the files that start with ttyUSB, USB connection
        for file in fileList:
          if file.startswith("ttyUSB"):
            try:
              sp = serial.Serial(file) 
              validPortCount += 1
              self.validPorts.append(sp.getPort()) 
            except serial.SerialException:
              pass

        # Find the files that start with ttyS, 9 pin serial connection
        for file in fileList:
          if file.startswith("ttyS"):
            try:
              sp = serial.Serial(file) 
              validPortCount += 1
              self.validPorts.append(sp.getPort()) 
            except serial.SerialException:
              pass

        
        IdNumber=500
        for port in self.validPorts:
            self.SerialMenu.AppendRadioItem(IdNumber,port)
            self.Bind(wx.EVT_MENU, self.OnSerial, id=IdNumber)
            IdNumber = IdNumber + 1
        
        self.ConfigMenu.AppendMenu(104, "&Serial", self.SerialMenu)
        self.ConfigMenu.AppendCheckItem(110,'&AutoSave','Toggle AutoSave')
        self.ConfigMenu.AppendSeparator()
        self.ConfigMenu.AppendCheckItem(120,'&Debug','Toggle Debug')
            
        
        
        self.HelpMenu.Append(103,'&About', 'About')
        
        self.menubar.Append(self.FileMenu, '&File')
        self.menubar.Append(self.ConfigMenu, '&Config')
        self.menubar.Append(self.HelpMenu, '&Help')
        self.SetMenuBar(self.menubar)
        self.CreateStatusBar()
        
        
        
        #Menu Bindings Go here
        self.Bind(wx.EVT_MENU, self.OnLoad, id=100)
        self.Bind(wx.EVT_MENU, self.OnSave, id=101)
        self.Bind(wx.EVT_MENU, self.OnQuit, id=102)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, id=108)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=103)
        self.Bind(wx.EVT_MENU, self.OnSerial, id=104)
        self.Bind(wx.EVT_MENU, self.OnLog, id=105)
        self.Bind(wx.EVT_MENU, self.OnStop, id=106)
        self.Bind(wx.EVT_MENU, self.OnClear, id=107)
        self.Bind(wx.EVT_MENU, self.OnAutoSave, id=110)
        self.Bind(wx.EVT_MENU, self.OnDebug, id=120)
        ################################################### 
        
        """Commented Out Buttons
        self.save_bitmap = wx.Image(os.path.join("images",'save.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.save_button = wx.BitmapButton(self, 200, bitmap=self.save_bitmap,pos=(250, 10), size = (self.save_bitmap.GetWidth(), self.save_bitmap.GetHeight()))
        
        self.load_bitmap = wx.Image(os.path.join("images",'load.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.load_button = wx.BitmapButton(self, 201, bitmap=self.load_bitmap,pos=(350, 10), size = (self.load_bitmap.GetWidth()+5, self.load_bitmap.GetHeight()+5))
        
        self.log_bitmap = wx.Image(os.path.join("images",'log.png'), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.log_button = wx.BitmapButton(self, 202, bitmap=self.log_bitmap,pos=(450, 10), size = (self.log_bitmap.GetWidth()+5, self.log_bitmap.GetHeight()+5))

        
        wx.EVT_BUTTON(self, 200, self.OnSave)
        wx.EVT_BUTTON(self, 201, self.OnLoad)
        wx.EVT_BUTTON(self, 202, self.OnLog)      
        ###############################################
        """
    
    
     
    def OnTick(self,event):
        #Redraw the the thermometer backgrounds
        #self.ambient.OnPaint(self)
        self.thermo_front.OnPaint(self)
        self.thermo_back.OnPaint(self)
       
        
        #Get Celcius From Front Thermo
        self.celsius = self.get_celsius(self.front_sensor)
        self.celsius_reverse = self.reverse_poly(self.celsius)
        self.ambient =(((self.celsius*9.0)/5.0)+32)
        #print ("Front Ambient ==> ", self.ambient)
        time.sleep(1)
        
        
        #Get uV from Front Thermo
        self.uv = self.get_uv(self.front_sensor)
        self.uv = self.uv + self.celsius_reverse
        self.uv = self.uv * 1000
        
        if (self.uv > 20.644):
            self.temp_uv = self.convert_uv_high(self.uv)
        else:
			self.temp_uv = self.convert_uv_low(self.uv)
		      
        self.kiln_front = (((self.temp_uv*9.0)/5.0)+32)
        
        #Make sure thermo measurement is not less then ambient
        #If it is less set the thermo to the ambient
        if (self.kiln_front < self.ambient):
            self.kiln_front = self.ambient
            
        time.sleep(1)
        
        #Get Celcius From Back Thermo
        self.celsius = self.get_celsius(self.back_sensor)
        self.celsius_reverse = self.reverse_poly(self.celsius)
        self.ambient =(((self.celsius*9.0)/5.0)+32)
        #print ("Back Ambient ==> ", self.ambient)
        time.sleep(1)
        
        
        #Get uV from back Thermo
        self.uv = self.get_uv(self.back_sensor)
        self.uv = self.uv + self.celsius_reverse
        self.uv = self.uv * 1000
        
        if (self.uv > 20.644):
            self.temp_uv = self.convert_uv_high(self.uv)
            
        else:
			self.temp_uv = self.convert_uv_low(self.uv)
			
        
        
        self.kiln_back = (((self.temp_uv*9.0)/5.0)+32)
        
        #Make sure thermo measurement is not less then ambient
        #If it is less set the thermo to the ambient
        if (self.kiln_back < self.ambient):
            self.kiln_back = self.ambient
        time.sleep(1)
        
        
        #Update the Front High Value Holder
        if self.kiln_front > self.FrontHigh:
            self.FrontHigh = self.kiln_front
        self.FrontHigh = round(self.FrontHigh,1)
        self.FrontHighReading.Clear()
        self.FrontHighReading.AppendText(str(self.FrontHigh))
        
        #Update the Back High Value Holder
        if self.kiln_back > self.BackHigh:
            self.BackHigh = self.kiln_back
        self.BackHigh = round(self.BackHigh,1)
        self.BackHighReading.Clear()
        self.BackHighReading.AppendText(str(self.BackHigh))
        
        self.BackReading.Clear()
        self.BackReading.AppendText(str(round(self.kiln_back,1)))
        
        self.FrontReading.Clear()
        self.FrontReading.AppendText(str(round(self.kiln_front,1)))
        
        self.elapsed = time.time()-self.t1
        self.ElapsedReading.Clear()
        self.ElapsedReading.AppendText(time.strftime("day %j - %H hrs. %M mins. %S secs.", time.gmtime(self.elapsed)))
        
        
    
        
        
        
        """Rolling Average Filter Commented Out
        if len(kiln_temp) > 20:
            sensor_average = 0
            #print kiln_temp[len(kiln_temp)-10:]
            #moving_part = [len(kiln_temp)-10:]
            for sample in kiln_temp[len(kiln_temp)-20:]:    
                sensor_average = sensor_average + sample
            sensor_average = sensor_average / 20
            sensor_average = round(sensor_average,2)
            print ("Ambient===>",self.ambient,"kiln Temp===>",self.kiln_F,"average is ==>", sensor_average)
            self.kiln_F = sensor_average
        """
        
        
        
        #Update the thermometer displays
        
        if (self.kiln_front > 500):
            self.thermo_front.update_gauge(self.kiln_front)
            
        if (self.kiln_back > 500):
            self.thermo_back.update_gauge(self.kiln_back)
        
    
        #Update the Lists and Graph
        self.kiln_front_array.append(self.kiln_front)
        self.kiln_back_array.append(self.kiln_back)
        self.ambient_array.append(self.ambient)
    
        self.date_human.append(strftime("%a, %d %b %Y %H:%M:%S"))
        self.date.append(date2num(datetime.now()))
  
        self.x.append(self.count)
        self.count = self.count + 1
        self.SampleNum.Clear()
        self.SampleNum.AppendText(str(self.count))
        
        
        """Attempts to just plot part of the line
        Turn This code on if you want to only plot to a certain depth
        self.depth is a variable that represents the number of readings to 
        show on the graph at one time.  After this number is exceeded the graph scrolls"""
        
        self.depth = 720
        if self.count > self.depth:
            self.graph_front=self.kiln_front_array[(len(self.kiln_front_array)-self.depth):len(self.kiln_front_array)]
            self.graph_back=self.kiln_back_array[(len(self.kiln_back_array)-self.depth):len(self.kiln_back_array)]
            self.graph_date=self.date[(len(self.date)-self.depth):len(self.date)]
        else:
            self.graph_front=self.kiln_front_array
            self.graph_back=self.kiln_back_array
            self.graph_date=self.date
            
            
        print ("front=>", round(self.kiln_front,1), "     back=>", round(self.kiln_back,1), "     ambient=>", round(self.ambient,1), "     Samples==>",self.count)
        
        #print "Ambient===>",self.ambient,"kiln front===>",self.kiln_front, "kiln back===>",self.kiln_back,"Samples==>",self.count
        
        self.sample_count = self.sample_count + 1
        if (self.sample_count >= self.sample_max):
            self.draw_graph()
            self.sample_count = 0
        if (self.count%100 == 0) & (self.AutoSave == 'True'):
            if (self.debug == 'True'):
                print ("I gots 100 samples, now ehm gonna save em")
            self.OnSave(None)
        
        
    
    def load_graph(self):
        #Set some plot attributes
        #add_subplot makes an Axes instance and puts it in the Figure instance
        #self.subplot is this Axes instance, as I had guessed.  
        #So, you can apply any Axes method to it.
        
        
        self.subplot = self.fig.add_subplot(111)
        self.subplot.set_title(r"Kiln Temperature")
        
        
    def draw_graph(self):
        if (self.debug == 'True'):
            print ("updating the graph ;")
        
        self.subplot.clear()
        self.subplot = self.fig.add_subplot(111)
        self.subplot.xaxis.set_minor_locator( HourLocator(12))
        
        """
        self.subplot.set_title(r"Kiln Temperature")
        self.subplot.xaxis.set_major_locator( DayLocator() )
        self.subplot.xaxis.set_major_locator( HourLocator(1))
        self.subplot.xaxis.set_major_locator( MinuteLocator(30))
        self.subplot.xaxis.set_major_locator( HourLocator(1))
        """
        
        #Turn off Scientific Notation on Y Axis
        self.subplot.yaxis.set_major_formatter(ScalarFormatter(False))
        self.subplot.xaxis.set_major_formatter(DateFormatter('%H:%M'))
        self.fig.autofmt_xdate()
        self.subplot.grid(True)
        
        self.subplot.plot(self.graph_date, self.graph_front, 'r-', linewidth = 1)
        self.subplot.plot(self.graph_date, self.graph_back, 'b-', linewidth = 1)
        
        #self.subplot.plot(self.date, self.kiln_front_array, 'r-', linewidth = 1)
        #self.subplot.plot(self.date, self.kiln_back_array, 'b-', linewidth = 1)
        self.canvas.draw()
    
    ##########################################################################
    ####################MENU Function Start Here##############################
    ##########################################################################
    def OnDebug(self, event):
        if (self.ConfigMenu.IsChecked(120)):
            self.debug = 'True'
            self.SetStatusText("Turning on Debug")
        else:
            self.debug = 'False'
            self.SetStatusText("Turning Off Debug")
                
    def OnAutoSave(self, event):
        if (self.debug == 'True'):
            print ("Somebody clicked on Autosave")
            print (self.ConfigMenu.IsChecked(110))
        if (self.ConfigMenu.IsChecked(110)):
            self.AutoSave = 'True'
            self.SetStatusText("Auto Save is on... Saving every 100 samples")
        else:
            self.AutoSave = 'False'
            self.SetStatusText("Auto Save is now off")
    
    def OnSerial(self, event): 
        if (self.debug == 'True'):
            print ("You are trying to change a port")
        IdNumber = 500
        for port in self.validPorts:
            if self.ConfigMenu.IsChecked(IdNumber):
                self.SerialSelect = port
                self.SetStatusText("Serial Port Now Set to " + self.SerialSelect)
                if (self.debug == 'True'):
                    print (port,"Is Checked")
            IdNumber = IdNumber + 1
                
    def OnClear(self,event):
        """clear the lists"""
        
        self.SetStatusText("Clearing the current graph...")
        self.date = []
        self.kiln_front_array = []
        self.kiln_back_array = []
        
        self.graph_front = self.kiln_front_array
        self.graph_back = self.kiln_back_array
        self.graph_date = self.date
        
        
       
        """clear the boxes"""
        self.SampleNum.Clear()
        self.FrontReading.Clear()
        self.BackReading.Clear()
        self.FrontHighReading.Clear()
        self.BackHighReading.Clear()
        self.ElapsedReading.Clear()
        
        """Clear the graph Window"""
        self.draw_graph()
    
    def OnStop(self,event):
        self.SetStatusText("Now stops the logging...")
        self.SensorTimer.Stop()
    
    def OnQuit(self,event):
        self.SetStatusText("Now we quit buh bye...")
        self.Close()

    def OnLog(self, event):
        #Open the serial port connection
        try: 
            self.ser = serial.Serial(self.SerialSelect, 9600, timeout=5)
            self.SetStatusText("Now starts the logging...")
            self.t1 = time.time()
            self.SensorTimer.Start(30000)
        except:
            self.SetStatusText("Invalid Serial Port Selected")

    def OnAbout(self, event):
        self.SetStatusText("All about ...PyroLogger...")
        dlg = wx.MessageDialog(self, 'When you as the Pyro want to Log!  Last updated October 2012', 'About Pyrologger', wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()
                   
    
    
    def OnSave(self,EVENT):
        if (self.filename == None):
            dialog = wx.FileDialog(self,"Save Graph Data...","","","Graph File (*.txt)|*.txt",wx.SAVE)
            if (dialog.ShowModal() == wx.ID_CANCEL):
                return  # canceled, bail
            # ok they saved
            self.filename = dialog.GetPath();
            self.SetTitle("PyroLogger        "+self.filename)

        try:
            file = open(self.filename, 'w')
            list_count = 0
            file.write ("Log Date and Time ")
            file.write (strftime("%a, %d %b %Y %H:%M:%S"))
            file.write ("\n")
            file.write ("Fields:Ambient KilnFront KilnBack Date Date2Num")
            file.write ("\n")
            file.write ("\n")
            for reading in self.date:
                value_1 = "%.1f" % self.ambient_array[list_count]
                value_2 = "%.1f" % self.kiln_front_array[list_count]
                value_3 = "%.1f" % self.kiln_back_array[list_count]
                value_4 = self.date_human[list_count]
                value_5 = "%.11f" % self.date[list_count]
                value = (list_count,value_1,value_2,value_3,value_4,value_5)
                file_line = str(value)
                file.write (file_line)
                file.write ("\n")
                list_count = list_count + 1
            file.close
            self.SetStatusText("Saved current Graph...")
        except IOError:
            self.SetStatusText("Error writing to file!")
            
    def OnSaveAs(self,EVENT):
        
        dialog = wx.FileDialog(self,"Save Graph Data...","","","Graph File (*.txt)|*.txt",wx.SAVE)
        if (dialog.ShowModal() == wx.ID_CANCEL):
            return  # canceled, bail
        # ok they saved
        self.filename = dialog.GetPath();
        self.SetTitle("PyroLogger        "+self.filename)

        try:
            file = open(self.filename, 'w')
            list_count = 0
            file.write ("Log Date and Time ")
            file.write (strftime("%a, %d %b %Y %H:%M:%S"))
            file.write ("\n")
            file.write ("Fields:Ambient KilnFront KilnBack Date Date2Num")
            file.write ("\n")
            file.write ("\n")
            for reading in self.date:
                value_1 = "%.1f" % self.ambient_array[list_count]
                value_2 = "%.1f" % self.kiln_front_array[list_count]
                value_3 = "%.1f" % self.kiln_back_array[list_count]
                value_4 = self.date_human[list_count]
                value_5 = "%.11f" % self.date[list_count]
                value = (list_count,value_1,value_2,value_3,value_4,value_5)
                file_line = str(value)
                file.write (file_line)
                file.write ("\n")
                list_count = list_count + 1
            file.close
            self.SetStatusText("Saved current Graph...")
        except IOError:
            self.SetStatusText("Error writing to file!")
    
    
    def OnLoad(self,EVENT):
        self.SetStatusText("Loading Graph...")
        self.SensorTimer.Stop()
        self.filename = None
            
        dialog = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN)
        if (dialog.ShowModal() == wx.ID_CANCEL):
            return  # canceled, bail
        # ok they loaded
        self.filename = dialog.GetPath()
        self.SetTitle("PyroLogger        "+self.filename)
        print ("You Pressed Load")
        print ("Slurping Raw Data... ummmmmm!!!")
        file = open(self.filename, 'r')
        skip = 0
        self.date = []
        self.kiln_front_array = []
        self.kiln_back_array = []
        
        for line in file.readlines():
            if (skip >= 3):
                #Split line up into its individual fields
                fields = line.split ('\', \'')
                self.kiln_front_array.append(fields[1])
                self.kiln_back_array.append(fields[2])
                paren = line.rfind(')')
                self.date.append(line[paren-19:paren-1])
            skip = skip + 1
        
        self.date = map(float, self.date)
        self.kiln_front_array = map(float, self.kiln_front_array)
        self.kiln_back_array = map(float, self.kiln_back_array)
        
        self.graph_front = self.kiln_front_array
        self.graph_back = self.kiln_back_array
        self.graph_date = self.date

        self.draw_graph()

    def get_celsius(self,address):
        self.ser.flushInput()
        self.ser.write("\r")
        self.ser.write("C")
        self.ser.write(address)
        self.ser.write("\r")
        #line = ser.read(5)
        line = self.ser.readline()
        self.ser.flushInput()
        return float(line)

    def get_uv(self,address):
        self.ser.flushInput()
        self.ser.write("\r")
        self.ser.write("K")
        self.ser.write(address)
        self.ser.write("\r")
        #line = ser.read(9)
        line = self.ser.readline()
        self.ser.flushInput()
        return float(line)
    """
    #This is older code and didn't give good values for ambient at higher temps use new code below
    def reverse_poly(self,x):
        #Takes in Temp in deg C and gives back Uv's, used to adjust for ambiant temperature
        coeffecients = [-1.76E1, 3.8921E1, 1.8559E-2, -9.9458E-5, 3.18409E-7, -5.607284E-10, 5.607506E-13, -3.20207E-16, 9.71511E-20, -1.21047E-23]

        a0 = 1.18597600000E2
        a1 = -0.118343200000E-3
        a2 = 0.126968600000E3

        e = 2.71828182

        result2 = 0.0
        added = 0.0
        power = 0

        exponent_value = x - a2
        exponent_value = exponent_value * exponent_value
        exponent_value = a1 * exponent_value
        added = pow(e,exponent_value)
        added = added * a0

        for c in coeffecients:
            result2 = (result2 + c * pow(x,power))
            power = power + 1
        result2 = result2 + added
        result2 = result2 / 1000000
        return (result2)
    """
    def reverse_poly(self,x):
        #Takes in Temp in deg C and gives back Uv's, used to adjust for ambiant temperature supposed to be good from 0-1372 deg C
        coeffecients = [-1.7600413686E-2, 3.8921204975E-2, 1.8558770032E-5, -9.9457592874E-8, 3.1840945719E-10, -5.6072844889E-13, 5.6075059059E-16, -3.2020720003E-19, 9.7151147152E-23, -1.2104721275E-26]
        
        result2 = 0.0
        #added = 0.0
        power = 0


        for c in coeffecients:
            result2 = (result2 + c * pow(x,power))
            power = power + 1
        #result2 = result2 + added
        #result2 = result2 / 1000000
        result2 = result2 / 1000
        return (result2)
 
 

    def convert_uv_low(self,uv):
        """The coefficients for Temperature range 0 deg C to 500 deg C
        Voltage range 0 mV to 20.644 mV
        Error range .04 deg C to -.05 deg C are:
			C0 = 0
			C1 = 2.508355 * 10^1
			C2 = 7.860106 * 10^-2
			C3 = -2.503131 *10^-1
			C4 = 8.315270 * 10^-2
			C5 = -1.228034 * 10^-2
			C6 = 9.804036 * 10^-4
			C7 = -4.413030 * 10^-5
			C8 = 1.057734 * 10^-6
			C9 = -1.052755 * 10^-8
		"""
		
        #coefficients = [0.226584602, 24152.10900, 67233.4248, 2210340.682, -860963914.9, 4.83506e10, -1.18452e12, 1.38690e13, -6.33708e13]
        coefficients = [0, 2.508355E1, 7.860106E-2, -2.503131E-1, 8.315270E-2, -1.228034E-2, 9.804036E-4, -4.413030E-5, 1.057734E-6, -1.052755E-8]
       
        result1 = 0.0
        power = 0
        
        for c in coefficients:
            result1 = result1 + c * pow(uv,power)
            power = power + 1
        result1 = round(result1,2)
        return result1
        
        
    def convert_uv_high(self,uv):
        """The coefficients for Temperature range 500 deg C to 1372 deg C
        Voltage range 20.644 mV to 54.886 mV
        Error range .06 deg C to -.05 deg C are:
            C0 = -1.318058 * 10^2
            C1 = 4.830222 * 10^1
            C2 = -1.646031
            C3 = 5.464731 * 10^-2
            C4 = -9.650715 * 10^-4
            C5 = 8.802193 * 10^-6
            C6 = -3.110810 * 10^-8
            C7 = 0
            C8 = 0
            C9 = 0
		"""
        
        coefficients = [-1.318058E2, 4.830222E1, -1.646031, 5.464731E-2, -9.650715E-4, 8.802193E-6, -3.110810E-8, 0, 0, 0]
       
        result1 = 0.0
        power = 0
        for c in coefficients:
            result1 = result1 + c * pow(uv,power)
            power = power + 1
        result1 = round(result1,2)
        return result1

    def OutputBoxes(self):
        """Create Output Boxes"""
        
        self.SampleNumLabel = wx.StaticText(self.TopPanel, -1,'Reading',(25,400))
        self.SampleNumLabel.SetForegroundColour('white')
        self.SampleNum = wx.TextCtrl(self.TopPanel, -1,"",(25,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        self.FrontReadingLabel = wx.StaticText(self.TopPanel, -1,'Front Temp',(125,400))
        self.FrontReadingLabel.SetForegroundColour('white')
        self.FrontReading = wx.TextCtrl(self.TopPanel, -1,"",(125,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        self.BackReadingLabel = wx.StaticText(self.TopPanel, -1,'Back Temp',(225,400))
        self.BackReadingLabel.SetForegroundColour('white')
        self.BackReading = wx.TextCtrl(self.TopPanel, -1,"",(225,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        self.FrontHighReadingLabel = wx.StaticText(self.TopPanel, -1,'Front High',(325,400))
        self.FrontHighReadingLabel.SetForegroundColour('white')
        self.FrontHighReading = wx.TextCtrl(self.TopPanel, -1,"",(325,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        self.BackHighReadingLabel = wx.StaticText(self.TopPanel, -1,'Back High',(425,400))
        self.BackHighReadingLabel.SetForegroundColour('white')
        self.BackHighReading = wx.TextCtrl(self.TopPanel, -1,"",(425,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        self.ElapsedReadingLabel = wx.StaticText(self.TopPanel, -1,'Elapsed Time',(525,400))
        self.ElapsedReadingLabel.SetForegroundColour('white')
        self.ElapsedReading = wx.TextCtrl(self.TopPanel, -1,"",(525,415),size=(300, 26),style=wx.TE_READONLY|wx.TE_CENTER)
Пример #18
0
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,(0,0),(975,500))
        
        
        
        self.TopPanel = wx.Panel(self, -1)
        gauge1 = wx.Panel(self.TopPanel,-1)
        gauge2 = wx.Panel(self.TopPanel,-1)
        graph1 = wx.Panel(self.TopPanel,-1)
        
        #Set Panel Background Colors
        graph1.SetBackgroundColour("black")
        gauge1.SetBackgroundColour("black")
        gauge2.SetBackgroundColour("black")
        self.TopPanel.SetBackgroundColour("black")
        
        
        
        
        #Instantiate the Two Thermometers One for the Kiln One for ambient
        #self.ambient=Thermometer(gauge1,-1,'amb_F',0,0,os.path.join("images",'ambient_F.png'))
        



        
        
        self.thermo_front=Thermometer(gauge1,-1,'kiln_F_H',0,0,os.path.join("images",'kiln_FH.png'))
        self.thermo_back=Thermometer(gauge2,-1,'kiln_F_H',0,0,os.path.join("images",'kiln_FH.png'))
        
        #self.ambient.update_gauge(17)
        self.thermo_front.update_gauge(450)
        self.thermo_back.update_gauge(450)
        
        #Set up the Graph Panel
        self.fig = Figure((10,5),75)
        self.canvas = FigureCanvasWx(graph1,-1,self.fig)
       
        
        
        #Create the sizer
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(gauge1,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 30)
        hbox.Add(graph1,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 20)
        hbox.Add(gauge2,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 30)
        self.TopPanel.SetSizer(hbox)
        
        
        self.OutputBoxes()   

        


        #Set Some Environment Variables
        self.Centre()
        self.Show(True)
        
        self.AutoSave = 'FALSE'
        self.debug = 'FALSE'
        
        self.FrontHigh = 0
        self.BackHigh= 0
        
        #Unique Sensor IDs
        self.id1 = '30ED284B1000008F'
        self.id2 = '3063294B100000BB'
        
        
        
        
        self.front_sensor = self.id1
        self.back_sensor = self.id2
        
        #Starting Temperatures for the gauges
        self.ambient = 70
        self.kiln_front = 1000
        self.kiln_back = 1000
        
        #Initialize the plot data arrays
        self.ambient_array= []
        self.kiln_front_array = []
        self.kiln_back_array = []
        self.date_human = []
        self.date = []
        self.count = 0
        self.sample_count = 0
        self.x = []
        
        
        #Make Sure Filename is cleared
        self.filename = None
        
        #number of samples before updating graph
        self.sample_max = 5
        
        #Setup the Plotting Figure and Canvas Load Blank Graph
        self.load_graph()

        
        
        #Setup the Clock
        self.SensorTimer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER,self.OnTick,self.SensorTimer)
        
        

        #Menu Items
        ################################################
        self.menubar = wx.MenuBar()
        self.FileMenu = wx.Menu()
        self.ConfigMenu = wx.Menu()
        self.SerialMenu = wx.Menu()
        self.HelpMenu = wx.Menu()
        
        self.FileMenu.Append(100, '&Load', 'Load a saved Graph')
        self.FileMenu.Append(101, '&Save', 'Save the current Graph')
        self.FileMenu.Append(108, '&Save As...', 'Save the current Graph')
        self.FileMenu.Append(105, '&Start Logging', 'Start logging process')
        self.FileMenu.Append(106, '&Stop Logging', 'Stop logging process')
        self.FileMenu.Append(107, '&Clear Graph', 'Reset the Graph Panel')
        self.FileMenu.AppendSeparator()
        self.FileMenu.Append(102, '&Quit', 'Quit')
        
    
        #Build the Configuration Menu
        # Build the Serial SubMenu
        # Get list of files in /dev
        cd = os.getcwd()
        os.chdir("/dev")
        dirdev = os.getcwd()
        fileList = os.listdir(dirdev)

        self.validPorts = list() 
        validPortCount = 0

        # Find the files that start with ttyUSB, USB connection
        for file in fileList:
          if file.startswith("ttyUSB"):
            try:
              sp = serial.Serial(file) 
              validPortCount += 1
              self.validPorts.append(sp.getPort()) 
            except serial.SerialException:
              pass

        # Find the files that start with ttyS, 9 pin serial connection
        for file in fileList:
          if file.startswith("ttyS"):
            try:
              sp = serial.Serial(file) 
              validPortCount += 1
              self.validPorts.append(sp.getPort()) 
            except serial.SerialException:
              pass

        
        IdNumber=500
        for port in self.validPorts:
            self.SerialMenu.AppendRadioItem(IdNumber,port)
            self.Bind(wx.EVT_MENU, self.OnSerial, id=IdNumber)
            IdNumber = IdNumber + 1
        
        self.ConfigMenu.AppendMenu(104, "&Serial", self.SerialMenu)
        self.ConfigMenu.AppendCheckItem(110,'&AutoSave','Toggle AutoSave')
        self.ConfigMenu.AppendSeparator()
        self.ConfigMenu.AppendCheckItem(120,'&Debug','Toggle Debug')
            
        
        
        self.HelpMenu.Append(103,'&About', 'About')
        
        self.menubar.Append(self.FileMenu, '&File')
        self.menubar.Append(self.ConfigMenu, '&Config')
        self.menubar.Append(self.HelpMenu, '&Help')
        self.SetMenuBar(self.menubar)
        self.CreateStatusBar()
        
        
        
        #Menu Bindings Go here
        self.Bind(wx.EVT_MENU, self.OnLoad, id=100)
        self.Bind(wx.EVT_MENU, self.OnSave, id=101)
        self.Bind(wx.EVT_MENU, self.OnQuit, id=102)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, id=108)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=103)
        self.Bind(wx.EVT_MENU, self.OnSerial, id=104)
        self.Bind(wx.EVT_MENU, self.OnLog, id=105)
        self.Bind(wx.EVT_MENU, self.OnStop, id=106)
        self.Bind(wx.EVT_MENU, self.OnClear, id=107)
        self.Bind(wx.EVT_MENU, self.OnAutoSave, id=110)
        self.Bind(wx.EVT_MENU, self.OnDebug, id=120)
        ################################################### 
        
        """Commented Out Buttons
Пример #19
0
class PlotFrame(Frame):
    def __init__(self, parent=None, title='', direction='H', size=(800, 800)):
        self.fig = None

        Frame.__init__(self, parent, title, direction, size)

    def Body(self):

        self.CenterOnScreen()
        self.params = default_params()
        self.ResetTitle()

        self.fig = Figure(figsize=(7, 5), dpi=100)
        self.axes = [
            self.fig.add_subplot(221),
            self.fig.add_subplot(222),
            self.fig.add_subplot(223),
            self.fig.add_subplot(224)
        ]

        self.canvas = FigureCanvas(self, -1, self.fig)
        self.CreateStatusBar()

        self.Show()

    def ResetTitle(self):

        (root, sfname) = os.path.split(self.params['save_sim_file'])
        s = ''

        title = 'Plasticity: %s%s' % (sfname, s)
        self.SetTitle(title)

    def Plot(self, sim):

        sim['params']['display'] = True

        if 'display_module' in sim['params']:
            if sim['params']['display_module']:
                try:
                    module = __import__(sim['params']['display_module'],
                                        fromlist=['UserPlot'])
                except ImportError:
                    sim['params']['display'] = False
                    dlg = MessageDialog(
                        self,
                        "Error",
                        "Error in Import: %s.  Turning display off" %
                        sim['params']['display_module'],
                        icon='error')
                    dlg.ShowModal()
                    dlg.Destroy()
                    return

                try:
                    module.UserPlot(self, sim)
                    return
                except ValueError:
                    sim['params']['display'] = False
                    dlg = MessageDialog(
                        self,
                        "Error",
                        "Error in display.  Turning display off",
                        icon='error')
                    dlg.ShowModal()
                    dlg.Destroy()
                    return

        try:

            im = weights2image(sim['params'], sim['weights'])

            self.axes[0].hold(False)
            self.axes[0].set_axis_bgcolor('k')
            self.axes[0].pcolor(im, cmap=gray, edgecolors='k')
            self.axes[0].set_aspect('equal')

            num_moments = sim['moments_mat'].shape[0]

            self.axes[1].hold(False)
            for i in range(num_moments):
                self.axes[1].plot(sim['moments_mat'][i, 0, :], '-o')
                self.axes[1].hold(True)

            self.axes[2].hold(False)
            response_mat = sim['response_mat']
            response_var_list = sim['response_var_list']
            styles = ['b-o', 'g-o']
            for i, r in enumerate(response_var_list[-1]):
                x = r[1]
                y = r[2]

                self.axes[2].plot(x, y, styles[i])
                self.axes[2].hold(True)

            self.axes[3].hold(False)
            styles = ['b-o', 'g-o']
            for i, r in enumerate(response_mat):
                self.axes[3].plot(r, styles[i])
                self.axes[3].hold(True)

            self.canvas.draw()

        except ValueError:
            sim['params']['display'] = False
            dlg = MessageDialog(self,
                                "Error",
                                "Error in display.  Turning display off",
                                icon='error')
            dlg.ShowModal()
            dlg.Destroy()
Пример #20
0
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title,(0,0),(975,500))
        
        
        
        TopPanel = wx.Panel(self, -1)
        gauge1 = wx.Panel(TopPanel,-1)
        gauge2 = wx.Panel(TopPanel,-1)
        graph1 = wx.Panel(TopPanel,-1)
        
        #Set Panel Background Colors
        graph1.SetBackgroundColour("black")
        gauge1.SetBackgroundColour("black")
        gauge2.SetBackgroundColour("black")
        TopPanel.SetBackgroundColour("black")
        
        
        
        
        #Instantiate the Two Thermometers One for the Kiln One for ambient
        
		
		
        
        self.ambient=Thermometer(gauge1,-1,'amb_F',0,0,os.path.join('images','ambient_F.png'))
        self.kiln=Thermometer(gauge2,-1,'kiln_F_H',0,0,os.path.join('images','kiln_FH.png'))
        
        self.ambient.update_gauge(17)
        self.kiln.update_gauge(450)
        
        #Set up the Graph Panel
        self.fig = Figure((10,5),75)
        self.canvas = FigureCanvasWx(graph1,-1,self.fig)
       
        
        
        #Create the sizer
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(gauge1,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 30)
        hbox.Add(graph1,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 20)
        hbox.Add(gauge2,0,wx.ALIGN_CENTER_HORIZONTAL | wx.TOP , 30)
        TopPanel.SetSizer(hbox)
        
        
       
       
        #Create Output Boxes
        #Displays Highest Recorded Reading
        self.HighReadingLabel = wx.StaticText(TopPanel, -1,'High Reading',(25,400))
        self.HighReadingLabel.SetForegroundColour('white')
        self.HighReading = wx.TextCtrl(TopPanel, -1,"",(25,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        #Displays Current Sample Number
        self.SampleNumLabel = wx.StaticText(TopPanel, -1,'Sample#',(125,400))
        self.SampleNumLabel.SetForegroundColour('white')
        self.SampleNum = wx.TextCtrl(TopPanel, -1,"",(125,415),style=wx.TE_READONLY|wx.TE_CENTER)
        
        
        
        
        
        
        
        
        
        
        self.Centre()
        self.Show(True)
        self.AutoSave = 'FALSE'
        
        
        self.debug = 'FALSE'
        #Unique Sensor IDs
        self.id1 = '30ED284B1000008F'
        self.id2 = '3063294B100000BB'
        self.current_sensor = self.id1
        #Starting Temperatures for the gauges
        self.ambient_F = 70
        self.kiln_F = 1000
        #Initialize the plot data arrays
        self.ambient_temp = []
        self.kiln_temp = []
        self.date_human = []
        self.date = []
        self.count = 0
        self.sample_count = 0
        self.x = []
        
        
        
        
        
        
        
        
        #Make Sure Filename is cleared
        self.filename = None
        
        #number of samples before updating graph
        self.sample_max = 5
        
        #Setup the Plotting Figure and Canvas Load Blank Graph
        self.load_graph()

        
        
        #Setup the Clock
        self.SensorTimer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER,self.OnTick,self.SensorTimer)
        
        

        #Menu Items
        ################################################
        self.menubar = wx.MenuBar()
        self.FileMenu = wx.Menu()
        self.ConfigMenu = wx.Menu()
        self.HelpMenu = wx.Menu()
        
        self.FileMenu.Append(100, '&Load', 'Load a saved Graph')
        self.FileMenu.Append(101, '&Save', 'Save the current Graph')
        self.FileMenu.Append(108, '&Save As...', 'Save the current Graph')
        self.FileMenu.Append(105, '&Start Logging', 'Start logging process')
        self.FileMenu.Append(106, '&Stop Logging', 'Stop logging process')
        self.FileMenu.Append(107, '&Clear Graph', 'Reset the Graph Panel')
        self.FileMenu.AppendSeparator()
        self.FileMenu.Append(102, '&Quit', 'Quit')
        
        self.ConfigMenu.Append(104, '&Serial Port', 'Serial Port')
        self.ConfigMenu.AppendSeparator()
        self.ConfigMenu.AppendCheckItem(110,'&AutoSave','Toggle AutoSave')
        self.ConfigMenu.AppendCheckItem(120,'&Debug','Toggle Debug')
        
        
        self.HelpMenu.Append(103,'&About', 'About')
        
        self.menubar.Append(self.FileMenu, '&File')
        self.menubar.Append(self.ConfigMenu, '&Config')
        self.menubar.Append(self.HelpMenu, '&Help')
        self.SetMenuBar(self.menubar)
        self.CreateStatusBar()
        
        #Menu Bindings Go here
        self.Bind(wx.EVT_MENU, self.OnLoad, id=100)
        self.Bind(wx.EVT_MENU, self.OnSave, id=101)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, id=108)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=103)
        self.Bind(wx.EVT_MENU, self.OnSerial, id=104)
        self.Bind(wx.EVT_MENU, self.OnLog, id=105)
        self.Bind(wx.EVT_MENU, self.OnStop, id=106)
        self.Bind(wx.EVT_MENU, self.OnClear, id=107)
        self.Bind(wx.EVT_MENU, self.OnAutoSave, id=110)
        self.Bind(wx.EVT_MENU, self.OnDebug, id=120)
        ################################################### 
        
        """
Пример #21
0
class MainFrame(Frame):

    def __init__(self,x,y,style,parent=None):
        self.fig=None
        Frame.__init__(self,parent,'Plot','H',size=(750,750))
        self.x=x
        self.y=y
        self.style=style
        self.Plot()
        
    def Body(self):
    
        self.CreateMenu()
        self.CenterOnScreen()
        
        self.fig = Figure(figsize=(7,5),dpi=100)
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.figmgr = FigureManager(self.canvas, 1, self)

        self.axes = [self.fig.add_subplot(111)]
        
    def CreateMenu(self):
    
        menubar = MenuBar()

        menu = Menu(self)
        menu.Append("&Run", self.Run, "Run",hotkey="Ctrl+R")
        menu.Append("Export Figure...", self.Export, "Export the Screen")
        menu.Append("&Quit", self.Quit, "Quit",hotkey="Ctrl+Q")

        menubar.Append(menu, "&File")
        self.running=False
        
        self.SetMenuBar(menubar)
        self.CreateStatusBar()

    def Export(self,event=None):
        export_fig(self)
        
    
    def Run(self,event=None):
    
        if self.running:
            self.y=self.y_bak
            self.UpdatePlot()

        else:        
            t=0.0
            self.y_bak=self.y
            
            for t in linspace(0,2*pi*4,100):
                self.y=y*cos(t)
                self.UpdatePlot()

        self.running=not self.running
        
    def UpdatePlot(self):
        self.h.set_ydata(self.y)
        self.canvas.draw()
        self.canvas.gui_repaint()
        wx.Yield()
        
    def Plot(self):
        self.axes[0].clear()
        self.h,=self.axes[0].plot(self.x,self.y,self.style,linewidth=3)
        
        self.canvas.draw()
        self.canvas.gui_repaint()


    def Quit(self,event=None):
        self.Close()