def main(input_file, output_directory): f1 = '/Users/Will/Documents/FDL/results/parsed_clima_initial.csv' f2 = '/Users/Will/Documents/FDL/results/parsed_clima_final.csv' print('Read clima into dataframe ...') # synthetic feature clima_dataframe = pd.read_csv(input_file) clima_dataframe['atm'] = clima_dataframe['P'] * 0.986923 print(clima_dataframe) print('Make plot...') pressure = Axis('P', 'Pressure', 'bar') atmospheres = Axis('atm', 'Pressure', 'atm') altitude = Axis('ALT', 'Altitude', 'km') temperature = Axis('T', 'Temperature', 'K') #plot_clima_profile(clima_dataframe, xaxis=pressure, yaxis=altitude, output_directory=output_directory) plot_clima_profile(clima_dataframe, xaxis=atmospheres, yaxis=altitude, output_directory=output_directory) plot_clima_profile(clima_dataframe, xaxis=temperature, yaxis=altitude, output_directory=output_directory)
def main(): dd = DataDecoder() level = LevelFilter() fil = LowPassFilter() serv = UdpServer() fig = plt.figure() dd.on_data.add(fil) fil.on_data.add(level) rows = 3 cols = 1 i = 1 for f in ('x', 'y', 'z'): ax = Axis(fig, [rows, cols, i], dt=1, maxt=100) dd.on_data.add(ax) line = PlotLine(f, color='b') dd.on_data.add(line) ax.add_line(line) linef = PlotLine(f, color='r') fil.on_data.add(linef) ax.add_line(linef) linef = PlotLine(f, color='g') level.on_data.add(linef) ax.add_line(linef) i = i + 1 pass dd_saver = DataSaver('dd') dd.on_data.add(dd_saver) fil_saver = DataSaver('fil') fil.on_data.add(fil_saver) lev_saver = DataSaver('lev') level.on_data.add(lev_saver) serv.on_read.add(dd) plt.ion() plt.plot() plt.draw() tk_win = fig.canvas._master tksupport.install(tk_win) def close_ev(): while True: print 'bye' fig.canvas.mpl_connect('close_event', close_ev) reactor.run() pass
def __init__(self, widget, plotbackground, height, width): """ Creates the graph object. You have to pack or grid it yourself. You can add bindings onto it however you want. """ # default axis size self.axisSize = 50 self.graphwidth = width - self.axisSize self.graphheight = height - self.axisSize self.ylogscale = 0 # can be changed with a call to yaxis_configure self.graphframe = Frame(widget) self.graph = Canvas(self.graphframe, bg=plotbackground, borderwidth=0, highlightthickness=0, height=self.graphheight, width=self.graphwidth, cursor='crosshair') self.graph.grid(row=0, column=1, sticky=N + W) # add the 2 axis # flip = 1 so positive numbers go up, not down self.yaxis = Axis(self.graphframe, lowestValue=None, highestValue=None, height=self.graphheight, width=self.axisSize, side="left", flip=1, logscale=self.ylogscale) self.yaxis.grid(row=0, column=0, sticky=N + W + E + S) self.xaxis = Axis(self.graphframe, lowestValue=None, highestValue=None, width=self.graphwidth, height=self.axisSize, side="bottom") self.xaxis.grid(row=1, column=1, sticky=N + W + E + S) # Make sure the main image will collapse before anything else self.graphframe.grid_rowconfigure(0, weight=1) self.graphframe.grid_columnconfigure(1, weight=1) # allow the graph to be resized self.graphframe.bind("<Configure>", self.resize)
def plot_fluxes(df): # find min/max of a set of c gases = ['CH4', 'CO', 'O2', 'H2', 'O', 'O3'] gases = ['CO', 'O2', 'H2O', 'H2'] gases = ['O2'] gases = ['CH4'] maximum = find_set_maximum(df, gases) minimum = find_set_minimum(df, gases) print(minimum, maximum) for g in gases: gas = Axis(g, 'Flux', 'molecules s$^{-1}$ cm$^{-2}$') plot_profile(df, gas, altitude) plt.legend() plt.xlim(xmin=minimum, xmax=maximum) plt.savefig('fluxes.pdf') plt.xscale('symlog') plt.savefig('fluxes_symlog.pdf') plt.xscale('log') plt.savefig('fluxes_log.pdf') # clear plot plt.clf()
def __init__(self,widget,plotbackground,height,width): """ Creates the graph object. You have to pack or grid it yourself. You can add bindings onto it however you want. """ # default axis size self.axisSize=50 self.graphwidth = width - self.axisSize self.graphheight = height - self.axisSize self.ylogscale = 0 # can be changed with a call to yaxis_configure self.graphframe = Frame(widget) self.graph=Canvas(self.graphframe,bg=plotbackground, borderwidth=0,highlightthickness=0, height=self.graphheight, width=self.graphwidth, cursor='crosshair') self.graph.grid(row=0,column=1,sticky=N+W) # add the 2 axis # flip = 1 so positive numbers go up, not down self.yaxis= Axis(self.graphframe, lowestValue = None, highestValue = None, height = self.graphheight, width = self.axisSize, side = "left", flip = 1,logscale=self.ylogscale) self.yaxis.grid(row=0,column=0,sticky=N+W+E+S) self.xaxis = Axis(self.graphframe, lowestValue = None, highestValue = None, width = self.graphwidth, height = self.axisSize, side = "bottom") self.xaxis.grid(row=1,column=1,sticky=N+W+E+S) # Make sure the main image will collapse before anything else self.graphframe.grid_rowconfigure(0,weight=1) self.graphframe.grid_columnconfigure(1,weight=1) # allow the graph to be resized self.graphframe.bind("<Configure>",self.resize)
def read(name, filein): tmp = filein[name] axlist = [] axes = [] for ax in tmp.dimensions: try: axes.append( Axis(ax, filein[ax][:], name=filein[ax].long_name, units=filein[ax].units)) except AttributeError: axes.append(Axis(ax, filein[ax][:], units=filein[ax].units)) except: raise axlist.append(ax) try: varout = Variable(name, data=tmp[:], name=tmp.long_name, units=tmp.units, axes=axes, axlist=axlist) except AttributeError: varout = Variable(name, data=tmp[:], units=tmp.units, axes=axes, axlist=axlist) except: raise return varout
def plot_mixing_ratios(df): gases = ['CH4', 'CO', 'O2', 'H2'] gases = ['CO', 'O2', 'H2O', 'H2'] gases = ['O2'] maximum = find_set_maximum(df, gases) minimum = find_set_minimum(df, gases) print(minimum, maximum) for g in gases: gas = Axis(g, 'Mixing ratio') plot_profile(df, gas, altitude) plt.legend() plt.xlim(xmin=minimum, xmax=maximum) plt.savefig('mixing_ratios.pdf') plt.xscale('log') plt.savefig('mixing_ratios_log.pdf') # clear plot plt.clf()
def __init__(self, min=0.0, max=1.0, start=0.0, end=1.0, majorticks=5, minorticks=20, majorlength=10, minorlength=5, y=0.0, labelformat='%d', id=u'', classes=(), baseid=u'', baseclasses=(), labelidprefix=u'', labelclasses=(), majoridprefix=u'', majorclasses=(), minoridprefix=u'', minorclasses=()): """ @param min: The minimum value of the axis @param max: The maximum value of the axis @param start: The starting coordinate of the axis @param end: The ending coordinate of the axis @param majorticks: The number of major tick marks @type majorticks: integer @param minorticks: The number of minor tick marks @type minorticks: integer @param majorlength: The length of the major tick marks @param minorlength: The length of the minor tick marks @param y: The y coordinate to draw the axis at @param labelformat: The format string to apply to the label text @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings @param baseid: The SVG document ID of the base line @type baseid: string @param baseclasses: Classnames to be applied to the base line @type baseclasses: string or sequence of strings @param labelidprefix: The prefix for each label ID @type labelidprefix: string @param labelclasses: Classnames to be applied to each label @type labelclasses: string or sequence of strings @param majoridprefix: The prefix for each major tick mark's ID @type majoridprefix: string @param majorclasses: Classnames to be applied to each major tick mark @type majorclasses: string or sequence of strings @param minoridprefix: The prefix for each minor tick mark's ID @type minoridprefix: string @param minorclasses: Classnames to be applied to each minor tick mark @type minorclasses: string or sequence of strings """ Axis.__init__(self, min=min, max=max, start=start, end=end, majorticks=majorticks, minorticks=minorticks, majorlength=majorlength, minorlength=minorlength, labelformat=labelformat, id=id, classes=classes, baseid=baseid, baseclasses=baseclasses, labelidprefix=labelidprefix, labelclasses=labelclasses, majoridprefix=majoridprefix, majorclasses=majorclasses, minoridprefix=minoridprefix, minorclasses=minorclasses) self.y = float(y) self.labelmargin = 2.0 self.labelsize = 12.0
class LinePlot: """ Plot creates a pretty rudimentary scatter plot which is good enough for my use. I am kind of ripping of the API to Pmw's Blt - http://heim.ifi.uio.no/~hpl/Pmw.Blt/doc/reference.html I was originally using Pmw's BLT but found it incompatible with mac. So this is a rewrite in pure tkinter which should run anywhere that Tk is installed. I am basically just using the Blt interface so I don't have to change any other code. When plotting data with a log y axis, this class will force the axis so that the smallest possible y value is 1 """ graphwidth = None graphheight = None axisSize = None # store all the lines that need to be plotted # The format for these lines should be a hash where # the key is the name of some line and the # value is a tuple holding the x and then y data # as 2 seperate lists and also the current ID of the line # (possibly equal to none). lines = {} # the only allowed marker is a rectangle # store the markers that should be put on this object. # the format for this is a hash where the key is the name # of some marker and the value is the ID of the object # as it is stored on the canvas. markers = {} inputXmin = None inputXmax = None inputYmin = None inputYmax = None usedXmin = None usedXmax = None usedYmin = None usedYmax = None def update(self): # remove everything from the graph for key in self.lines.keys(): record = self.lines[key] for id in record['ID']: self.graph.delete(id) record['ID'] = [] # if there is no line to plot AND no given axis if len(self.lines) == 0 and (self.inputXmin == None or self.inputXmax == None or self.inputYmin or self.inputYmax == 0): # configure the axis to have nothing in them self.xaxis.config(lowestValue=None,highestValue=None) self.yaxis.config(lowestValue=None,highestValue=None, logscale = self.ylogscale) # figure out what usedXmin and usedXmax should be if self.inputXmin == None or self.inputXmax == None: # auto scale x self.usedXmin = None self.usedXmax = None for key in self.lines.keys(): record = self.lines[key] for index in range(len(record['x'])): if self.usedXmin == None or record['x'][index] < self.usedXmin: self.usedXmin = record['x'][index] if self.usedXmax == None or record['x'][index] > self.usedXmax: self.usedXmax = record['x'][index] else: self.usedXmin = self.inputXmin self.usedXmax = self.inputXmax # figure out what usedYmin and usedYmax should be if self.inputYmin == None or self.inputYmax == None: # auto scale y self.usedYmin = None self.usedYmax = None for key in self.lines.keys(): record = self.lines[key] for index in range(len(record['y'])): if record['y'][index] > 0 or not self.ylogscale: if self.usedYmin == None or record['y'][index] < self.usedYmin: self.usedYmin = record['y'][index] if self.usedYmax == None or record['y'][index] > self.usedYmax: self.usedYmax = record['y'][index] else: self.usedYmin = self.inputYmin self.usedYmax = self.inputYmax # configure the axis self.xaxis.config(lowestValue=self.usedXmin,highestValue=self.usedXmax) self.yaxis.config(lowestValue=self.usedYmin,highestValue=self.usedYmax, logscale=self.ylogscale) for line in self.lines.keys(): record = self.lines[line] if len(record['x']) == 1: # draw just a point !!! # get the only line out x,y=self.invtransform(record['x'][0],record['y'][0]) line['ID'].append(self.graph.create_line( x,y,x,y,fill=record['color'],width=1)) else: record['ID'] = [] for index in range(len(record['x'])-1): x1,y1 = self.transform(record['x'][index],record['y'][index]) x2,y2 = self.transform(record['x'][index+1],record['y'][index+1]) record['ID'].append(self.graph.create_line( x1,y1,x2,y2,fill=record['color'],width=1)) def element_names(self): return self.lines.keys() def marker_create(self,type, name, dashes,coords=""): """ Put the marker outside of the frame, for now. """ if type != "line": raise Exception("The only type of marker that can be created is a line") self.markers[name] = self.graph.create_rectangle(-1,-1,-1,-1, dash=dashes,outline="black") def marker_configure(self,name,coords): (x0, y0, x1, y0, x1, y1, x0, y1, x0, y0) = coords # transform the real coordinates into canvas coordiantes # before adding them to the graph x0,y0 = self.transform(x0,y0) x1,y1 = self.transform(x1,y1) self.graph.coords(self.markers[name],x0,y0,x1,y1) def marker_delete(self,name): self.graph.delete(self.markers[name]) del self.markers[name] def inside(self,x,y): """ Check if the canvas coordinates (x,y) are inside the image. """ if x>0 and x<self.graphwidth and y>0 and y<self.graphheight: return 1 return 0 def transform(self,x,y): """ takes in real coodinates as they are plotted and returns the corresponding coordinates on the graph canvas. """ if self.usedXmin == None or self.usedXmax == None or \ self.usedYmin == None or self.usedYmax == None: if self.inputXmin == None or self.inputXmax == None or \ self.inputYmin == None or self.inputYmax == None: raise Exception("Cannot perform the inverse transform until a range for the plot is set.") xmin = self.inputXmin xmax = self.inputXmax ymin = self.inputYmin ymax = self.inputYmax else: xmin = self.usedXmin xmax = self.usedXmax ymin = self.usedYmin ymax = self.usedYmax transX = (x-xmin)*(self.graphwidth-1.0)/(xmax-xmin) if self.ylogscale: if y<=0: # anything less then 0 must be forced outside the image # This is kind of tricky, though, because a Tkinter canvas # has negative values on top of the canvas and very large # values below the canvas. That it why we are giving # our too small pixels very large values transY = 1000 else: transY = (self.graphheight-1.0)*(log10(y)-log10(ymin))/(log10(ymax)-log10(ymin)) # coordiantes are weird b/c they go down not up, so we have to invert them transY = self.graphheight-1.0-transY else: transY = (y-ymin)*(self.graphheight-1.0)/(ymax-ymin) # coordiantes are weird b/c they go down not up, so we have to invert them transY = self.graphheight-1-transY return transX,transY def invtransform(self,x,y): """ takes in coordinates on the graph canvas and convert them to real coordinates. """ if self.usedXmin == None or self.usedXmax == None or \ self.usedYmin == None or self.usedYmax == None: if self.inputXmin == None or self.inputXmax == None or \ self.inputYmin == None or self.inputYmax == None: raise Exception("Cannot perform the inverse transform until a range for the plot is set.") xmin = self.inputXmin xmax = self.inputXmax ymin = self.inputYmin ymax = self.inputYmax else: xmin = self.usedXmin xmax = self.usedXmax ymin = self.usedYmin ymax = self.usedYmax transX = self.usedXmin+x*(self.usedXmax-self.usedXmin)/(self.graphwidth-1.0) if self.ylogscale: transY = pow(10,((self.graphheight-1.0-y)/(self.graphheight-1.0))*(log10(self.usedYmax)-log10(self.usedYmin))+log10(self.usedYmin)) else: transY = self.usedYmin+(self.graphheight-1.0-y)*(self.usedYmax-self.usedYmin)/(self.graphheight-1.0) return transX,transY def xaxis_configure(self,title=None,min=None,max=None): """ If min == '' and max == '', then auto scale the graph """ if title != None: self.xaxis.config(title=title) # when min & max aren't passed in, then don't change the ranges if min != None and max != None: if min == '': if max != '': raise Exception("You can not fix part but not all of one of the ranges.") self.inputXmin = None self.inputXmax = None self.usedXmin = None self.usedXmax = None else: self.inputXmin = min self.inputXmax = max self.usedXmin = None self.usedXmax = None self.update() def yaxis_configure(self,title=None,min=None,max=None,logscale=None): """ If min == '' and max == '', then auto scale the graph """ if title != None: self.yaxis.config(title=title) # when min & max aren't passed in, then don't change the ranges if min != None and max != None: # if they are both set to '', reset the axis if min == '': if max != '': raise Exception("You can not fix part but not all of one of the ranges.") self.inputYmin = None self.inputYmax = None self.usedYmin = None self.usedYmax = None else: # otherwise, set it to new values self.inputYmin = min self.inputYmax = max self.usedYmin = None self.usedYmax = None if logscale != None: self.ylogscale = logscale self.update() def resize(self,event): """ Resize canvas if needed. """ # resize canvas properly if event.width <= self.axisSize or \ event.height <= self.axisSize: return self.graphwidth=event.width-self.axisSize self.graphheight=event.height-self.axisSize self.graph.config(height=self.graphheight, width=self.graphwidth) self.xaxis.config(width=self.graphwidth, height=self.axisSize) self.yaxis.config(width=self.axisSize, height=self.graphheight) self.update() def line_create(self,name,xdata=None,ydata=None,symbol='',color='red'): if symbol != '': raise Exception("Currently, no symbols can be used when drawing graphs.") if len(xdata) != len(ydata): raise Exception("The number of x and y values of the line to plot must be equal") if len(xdata) < 1: raise Exception("There must be at least one point to plot on the current line") if name in self.lines.keys(): raise Exception("Cannot add this line because another line with the same name already exists.") self.lines[name]={'x':xdata,'y':ydata,'color':color,'ID':[]} self.update() def element_delete(self,g): """ Deletes one of the lines by its name. """ if not g in self.lines.keys(): raise Exception("Cannot delete element that dose not exist.") # remove everything from the graph for id in self.lines[g]['ID']: self.graph.delete(id) del self.lines[g] self.update() def xaxis_cget(self,str): if str=="min": return self.inputXmin if str=="max": return self.inputXmax def yaxis_cget(self,str): if str=="min": return self.inputYmin if str=="max": return self.inputYmax def bind(self,**args): """ Bindings happen only on the graph with the data on it. I have no idea why I can't just call the function bind as: self.graph.bind(args) But what works, works... """ self.graph.bind(sequence=args['sequence'],func=args['func']) def unbind(self,**args): """ Bindings happen only on the graph with the data on it.""" self.graph.unbind(sequence=args['sequence']) def grid(self,**args): """ Allow the Frame that the plot gets put on to be gridded into the GUI. """ self.graphframe.grid(args) def pack(self,**args): """ Allow the Frame that the plot gets put on to be gridded into the GUI. """ self.graphframe.pack(args) def legend_configure(self,hide=1): """ This is just for compatability.""" if hide != 1: raise Exception("The legend in this program can only be hidden.") pass def __init__(self,widget,plotbackground,height,width): """ Creates the graph object. You have to pack or grid it yourself. You can add bindings onto it however you want. """ # default axis size self.axisSize=50 self.graphwidth = width - self.axisSize self.graphheight = height - self.axisSize self.ylogscale = 0 # can be changed with a call to yaxis_configure self.graphframe = Frame(widget) self.graph=Canvas(self.graphframe,bg=plotbackground, borderwidth=0,highlightthickness=0, height=self.graphheight, width=self.graphwidth, cursor='crosshair') self.graph.grid(row=0,column=1,sticky=N+W) # add the 2 axis # flip = 1 so positive numbers go up, not down self.yaxis= Axis(self.graphframe, lowestValue = None, highestValue = None, height = self.graphheight, width = self.axisSize, side = "left", flip = 1,logscale=self.ylogscale) self.yaxis.grid(row=0,column=0,sticky=N+W+E+S) self.xaxis = Axis(self.graphframe, lowestValue = None, highestValue = None, width = self.graphwidth, height = self.axisSize, side = "bottom") self.xaxis.grid(row=1,column=1,sticky=N+W+E+S) # Make sure the main image will collapse before anything else self.graphframe.grid_rowconfigure(0,weight=1) self.graphframe.grid_columnconfigure(1,weight=1) # allow the graph to be resized self.graphframe.bind("<Configure>",self.resize)
class LinePlot: """ Plot creates a pretty rudimentary scatter plot which is good enough for my use. I am kind of ripping of the API to Pmw's Blt - http://heim.ifi.uio.no/~hpl/Pmw.Blt/doc/reference.html. But this does not nearly have all the features Pmw:Blt has. I was originally using Pmw's BLT but found it incompatible with the mac. So this is a rewrite in pure Tkinter which should run anywhere that Tk is installed. I am basically just using the Blt interface so I don't have to change any other code. When plotting data with a log y axis, this class will force the axis so that the smallest possible y value is 1 """ graphwidth = None graphheight = None axisSize = None # store all the lines that need to be plotted # The format for these lines should be a hash where # the key is the name of some line and the # value is a tuple holding the x and then y data # as 2 seperate lists and also the current ID of the line # (possibly equal to none). lines = {} # the only allowed marker is a rectangle # store the markers that should be put on this object. # the format for this is a hash where the key is the name # of some marker and the value is the ID of the object # as it is stored on the canvas. markers = {} inputXmin = None inputXmax = None inputYmin = None inputYmax = None usedXmin = None usedXmax = None usedYmin = None usedYmax = None def update(self): # remove everything from the graph for key in self.lines.keys(): record = self.lines[key] for id in record['ID']: self.graph.delete(id) record['ID'] = [] # if there is no line to plot AND no given axis if len(self.lines) == 0 and (self.inputXmin == None or self.inputXmax == None or self.inputYmin or self.inputYmax == 0): # configure the axis to have nothing in them self.xaxis.config(lowestValue=None,highestValue=None) self.yaxis.config(lowestValue=None,highestValue=None, logscale = self.ylogscale) # figure out what usedXmin and usedXmax should be if self.inputXmin == None or self.inputXmax == None: # auto scale x self.usedXmin = None self.usedXmax = None for key in self.lines.keys(): record = self.lines[key] for index in range(len(record['x'])): if self.usedXmin == None or record['x'][index] < self.usedXmin: self.usedXmin = record['x'][index] if self.usedXmax == None or record['x'][index] > self.usedXmax: self.usedXmax = record['x'][index] else: self.usedXmin = self.inputXmin self.usedXmax = self.inputXmax # figure out what usedYmin and usedYmax should be if self.inputYmin == None or self.inputYmax == None: # auto scale y self.usedYmin = None self.usedYmax = None for key in self.lines.keys(): record = self.lines[key] for index in range(len(record['y'])): if record['y'][index] > 0 or not self.ylogscale: if self.usedYmin == None or record['y'][index] < self.usedYmin: self.usedYmin = record['y'][index] if self.usedYmax == None or record['y'][index] > self.usedYmax: self.usedYmax = record['y'][index] else: self.usedYmin = self.inputYmin self.usedYmax = self.inputYmax # configure the axis self.xaxis.config(lowestValue=self.usedXmin,highestValue=self.usedXmax) self.yaxis.config(lowestValue=self.usedYmin,highestValue=self.usedYmax, logscale=self.ylogscale) for line in self.lines.keys(): record = self.lines[line] if len(record['x']) == 1: # draw just a point !!! # get the only line out x,y=self.invtransform(record['x'][0],record['y'][0]) line['ID'].append(self.graph.create_line( x,y,x,y,fill=record['color'],width=1)) else: record['ID'] = [] for index in range(len(record['x'])-1): x1,y1 = self.transform(record['x'][index],record['y'][index]) x2,y2 = self.transform(record['x'][index+1],record['y'][index+1]) record['ID'].append(self.graph.create_line( x1,y1,x2,y2,fill=record['color'],width=1)) def element_names(self): return self.lines.keys() def marker_create(self,type, name, dashes,coords=""): """ Put the marker outside of the frame, for now. """ if type != "line": raise Exception("The only type of marker that \ can be created is a line") self.markers[name] = self.graph.create_rectangle(-1,-1,-1,-1, dash=dashes,outline="black") def marker_configure(self,name,coords): (x0, y0, x1, y0, x1, y1, x0, y1, x0, y0) = coords # transform the real coordinates into canvas coordiantes # before adding them to the graph x0,y0 = self.transform(x0,y0) x1,y1 = self.transform(x1,y1) self.graph.coords(self.markers[name],x0,y0,x1,y1) def marker_delete(self,name): self.graph.delete(self.markers[name]) del self.markers[name] def inside(self,x,y): """ Check if the canvas coordinates (x,y) are inside the image. """ if x>0 and x<self.graphwidth and y>0 and y<self.graphheight: return 1 return 0 def transform(self,x,y): """ takes in real coordinates as they are plotted and returns the corresponding coordinates on the graph canvas. """ if self.usedXmin == None or self.usedXmax == None or \ self.usedYmin == None or self.usedYmax == None: if self.inputXmin == None or self.inputXmax == None or \ self.inputYmin == None or self.inputYmax == None: raise Exception("Cannot perform the inverse \ transform until a range for the plot is set.") xmin = self.inputXmin xmax = self.inputXmax ymin = self.inputYmin ymax = self.inputYmax else: xmin = self.usedXmin xmax = self.usedXmax ymin = self.usedYmin ymax = self.usedYmax transX = (x-xmin)*(self.graphwidth-1.0)/(xmax-xmin) if self.ylogscale: if y<=0: # anything less then 0 must be forced outside the image # This is kind of tricky, though, because a Tkinter canvas # has negative values on top of the canvas and very large # values below the canvas. That it why we are giving # our too small pixels very large values transY = 1000 else: transY = (self.graphheight-1.0)*(log10(y)- \ log10(ymin))/(log10(ymax)-log10(ymin)) # coordinates are weird because they go down not up, # so we have to invert them transY = self.graphheight-1.0-transY else: transY = (y-ymin)*(self.graphheight-1.0)/(ymax-ymin) # coordinates are weird b/c they go down not up, so we # have to invert them transY = self.graphheight-1-transY return transX,transY def invtransform(self,x,y): """ takes in coordinates on the graph canvas and convert them to real coordinates. """ if self.usedXmin == None or self.usedXmax == None or \ self.usedYmin == None or self.usedYmax == None: if self.inputXmin == None or self.inputXmax == None or \ self.inputYmin == None or self.inputYmax == None: raise Exception("Cannot perform the inverse \ transform until a range for the plot is set.") xmin = self.inputXmin xmax = self.inputXmax ymin = self.inputYmin ymax = self.inputYmax else: xmin = self.usedXmin xmax = self.usedXmax ymin = self.usedYmin ymax = self.usedYmax transX = self.usedXmin+x*(self.usedXmax- \ self.usedXmin)/(self.graphwidth-1.0) if self.ylogscale: transY = pow(10,((self.graphheight-1.0-y)/ \ (self.graphheight-1.0))*(log10(self.usedYmax)- \ log10(self.usedYmin))+log10(self.usedYmin)) else: transY = self.usedYmin+(self.graphheight-1.0-y)* \ (self.usedYmax-self.usedYmin)/(self.graphheight-1.0) return transX,transY def xaxis_configure(self,title=None,min=None,max=None): """ If min == '' and max == '', then auto scale the graph """ if title != None: self.xaxis.config(title=title) # when min & max aren't passed in, then # don't change the ranges if min != None and max != None: if min == '': if max != '': raise Exception("You can not fix part \ but not all of one of the ranges.") self.inputXmin = None self.inputXmax = None self.usedXmin = None self.usedXmax = None else: self.inputXmin = min self.inputXmax = max self.usedXmin = None self.usedXmax = None self.update() def yaxis_configure(self,title=None,min=None, max=None,logscale=None): """ If min == '' and max == '', then auto scale the graph """ if title != None: self.yaxis.config(title=title) # when min & max aren't passed in, then # don't change the ranges if min != None and max != None: # if they are both set to '', reset # the axis if min == '': if max != '': raise Exception("You can not \ fix part but not all of one of the ranges.") self.inputYmin = None self.inputYmax = None self.usedYmin = None self.usedYmax = None else: # otherwise, set it to new values self.inputYmin = min self.inputYmax = max self.usedYmin = None self.usedYmax = None if logscale != None: self.ylogscale = logscale self.update() def resize(self,event): """ Resize canvas if needed. """ # resize canvas properly if event.width <= self.axisSize or \ event.height <= self.axisSize: return self.graphwidth=event.width-self.axisSize self.graphheight=event.height-self.axisSize self.graph.config(height=self.graphheight, width=self.graphwidth) self.xaxis.config(width=self.graphwidth, height=self.axisSize) self.yaxis.config(width=self.axisSize, height=self.graphheight) self.update() def line_create(self,name,xdata=None,ydata=None, symbol='',color='red'): if symbol != '': raise Exception("Currently, no symbols can \ be used when drawing graphs.") if len(xdata) != len(ydata): raise Exception("The number of x and y values \ of the line to plot must be equal") if len(xdata) < 1: raise Exception("There must be at least one \ point to plot on the current line") if name in self.lines.keys(): raise Exception("Cannot add this line because \ another line with the same name already exists.") self.lines[name]={'x':xdata,'y':ydata, 'color':color,'ID':[]} self.update() def element_delete(self,g): """ Deletes one of the lines by its name. """ if not g in self.lines.keys(): raise Exception("Cannot delete element that \ dose not exist.") # remove everything from the graph for id in self.lines[g]['ID']: self.graph.delete(id) del self.lines[g] self.update() def xaxis_cget(self,str): if str=="min": return self.inputXmin if str=="max": return self.inputXmax def yaxis_cget(self,str): if str=="min": return self.inputYmin if str=="max": return self.inputYmax def bind(self,**args): """ Bindings happen only on the graph with the data on it. I have no idea why I can't just call the function bind as: self.graph.bind(args) But what works, works... """ self.graph.bind(sequence=args['sequence'],func=args['func']) def unbind(self,**args): """ Bindings happen only on the graph with the data on it.""" self.graph.unbind(sequence=args['sequence']) def grid(self,**args): """ Allow the Frame that the plot gets put on to be gridded into the GUI. """ self.graphframe.grid(args) def pack(self,**args): """ Allow the Frame that the plot gets put on to be gridded into the GUI. """ self.graphframe.pack(args) def legend_configure(self,hide=1): """ This is just for compatibility.""" if hide != 1: raise Exception("The legend in this program can only be hidden.") pass def __init__(self,widget,plotbackground,height,width): """ Creates the graph object. You have to pack or grid it yourself. You can add bindings onto it however you want. """ # default axis size self.axisSize=50 self.graphwidth = width - self.axisSize self.graphheight = height - self.axisSize self.ylogscale = 0 # can be changed with a call to yaxis_configure self.graphframe = Frame(widget) self.graph=Canvas(self.graphframe,bg=plotbackground, borderwidth=0,highlightthickness=0, height=self.graphheight, width=self.graphwidth, cursor='crosshair') self.graph.grid(row=0,column=1,sticky=N+W) # add the 2 axis # flip = 1 so positive numbers go up, not down self.yaxis= Axis(self.graphframe, lowestValue = None, highestValue = None, height = self.graphheight, width = self.axisSize, side = "left", flip = 1,logscale=self.ylogscale) self.yaxis.grid(row=0,column=0,sticky=N+W+E+S) self.xaxis = Axis(self.graphframe, lowestValue = None, highestValue = None, width = self.graphwidth, height = self.axisSize, side = "bottom") self.xaxis.grid(row=1,column=1,sticky=N+W+E+S) # Make sure the main image will collapse before anything else self.graphframe.grid_rowconfigure(0,weight=1) self.graphframe.grid_columnconfigure(1,weight=1) # allow the graph to be resized self.graphframe.bind("<Configure>",self.resize)
print "\nWARNING: Not on Linux!\n" ON_PI = 0 LS = [LimitSwitch(11), LimitSwitch(12), LimitSwitch(13), LimitSwitch(15), LimitSwitch(35), LimitSwitch(37), LimitSwitch(38)] RLY = [Relay(18), Relay(22), Relay(7)] mh = [0, 0] if (ON_PI): mh = [ Adafruit_MotorHAT(0x60), Adafruit_MotorHAT(0x61) ] if (len(sys.argv) > 1): if sys.argv[1] == "--testMotor": testAxis = Axis() testAxis.attach(Motor(mh[0], 1, 0), None, None) testAxis.attach(Motor(mh[0], 2, 0), None, None) testAxis.attach(Motor(mh[1], 1, 0), None, None) testAxis.attach(Motor(mh[1], 2, 0), None, None) testAxis.homeAxis() raw_input("Press Enter to quit...") testAxis.stop() sys.exit() else: print "Unrecognized parameter" sys.exit(2) feeder = Feeder(Motor(mh[0], 2)) dropper = Dropper(RLY[0], LimitSwitch(16)) # Note, pin 16 is the Photocell, not a physical limit switch
#!/usr/bin/env python3 from Axis import Axis import pandas as pd import matplotlib.pyplot as plt import numpy as np pressure = Axis('P', 'Pressure', 'bar') altitude = Axis('Z', 'Altitude', 'km') temperature = Axis('T', 'Temperature', 'K') #_____________________________________________________________________________ def main(input_file): base_dir = '/Users/Will/Documents/FDL/results/docker_image' flux_path = base_dir + '/parsed_photochem_fluxes.csv' mix_path = base_dir + '/parsed_photochem_mixing_ratios.csv' flux_dataframe = pd.read_csv(flux_path) mix_dataframe = pd.read_csv(mix_path) # convert cm to km mix_dataframe['Z'] = mix_dataframe['Z'] / 1e5 flux_dataframe['Z'] = flux_dataframe['Z'] / 1e5 sum_fluxes(flux_dataframe, []) plot_mixing_ratios(mix_dataframe) plot_fluxes(flux_dataframe)
# threshold boundaries for HSV space skin segmentation lower = np.array([0, 0, 0], dtype="uint8") upper = np.array([255, 255, 255], dtype="uint8") # video recording fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('COS429.avi', fourcc, 20.0, (640, 480)) # Choose the segmentation algorithm option = int( raw_input( "What skin segmentation algorithm would you like to use?\n1) OTSU Thresholding \n2) HSV Skin Sample Segmentation\n" )) ax = Axis() curr_time = time.time() ct = 1 print "Press c to use current frame for calibration" while (True): # Capture frame-by-frameqq ret, BGR_frame = cap.read() BGR_frame = cv2.flip(BGR_frame, 1) #vertical flip # thresholding to find hand if option == 1: BGR_frame = pre.deNoise(BGR_frame) gray_frame = pre.im2Gray(BGR_frame) skinMask = pre.thresholdHand(gray_frame)
def main(): dd = DataDecoder() level = LevelFilter() fil = LowPassFilter() serv = UdpServer() fig = plt.figure() dd.on_data.add(fil) fil.on_data.add(level) rows = 3 cols = 1 i = 1 for f in ('x', 'y', 'z'): ax = Axis(fig, [rows, cols, i], dt = 1, maxt = 100) dd.on_data.add(ax) line = PlotLine(f,color='b') dd.on_data.add(line) ax.add_line(line) linef = PlotLine(f, color='r') fil.on_data.add(linef) ax.add_line(linef) linef = PlotLine(f, color='g') level.on_data.add(linef) ax.add_line(linef) i = i + 1 pass dd_saver = DataSaver('dd') dd.on_data.add(dd_saver) fil_saver = DataSaver('fil') fil.on_data.add(fil_saver) lev_saver = DataSaver('lev') level.on_data.add(lev_saver) serv.on_read.add(dd) plt.ion() plt.plot() plt.draw() tk_win = fig.canvas._master tksupport.install(tk_win) def close_ev(): while True: print 'bye' fig.canvas.mpl_connect('close_event', close_ev) reactor.run() pass