def __init__(self, *args, **kwargs): super(Wnd, self).__init__(*args, **kwargs) self.t = None self.osc = None self.input_cbox = None self.output_cbox = None left = VContainer() right = VContainer() self.slider = QtWidgets.QSlider(Qt.Horizontal) self.slider.setMinimum(20) self.slider.setMaximum(500) left.addWidget(self.slider) self.slider.valueChanged.connect(self.change_freq) self.addWidget(left) self.addWidget(right) devices = HContainer() devices.addWidget(self.inputCBox()) devices.addWidget(self.outputCBox()) left.addWidget(devices) spf = wave.open("wav.wav", "r") signal = spf.readframes(-1) signal = np.frombuffer(signal, "int16") self.signal = signal self.graphWidget = MyPlot() left.addWidget(self.graphWidget) self.fft = Spec() # self.fft.setYRange(0, 100000, padding=0) left.addWidget(self.fft) self.buttons = HContainer() btn = QtWidgets.QPushButton() btn.setText('Record') self.buttons.addWidget(btn) btn.clicked.connect(self.get_device_num) btn = QtWidgets.QPushButton() btn.setText('Play') self.buttons.addWidget(btn) btn.clicked.connect(self.play_file) left.addWidget(self.buttons) self.logger = LogWrite() right.addWidget(self.logger)
def show_bias(self): if len(self.weights) is 1: mp = MyPlot() mp.set_labels('Step', 'Bias') mp.show_list(self.biases) else: print('Cannot show the bias! Call print_bias mehtod.')
def implement_rule(self): if LineParser.__function_create_start == None: if self.rule_in_line == 'CREATEVAR': LineParser.__variables.CreateVar((self.line.split(':')[1]).split('\n')[0]) MyPlot.UpdateGlobals(Variable.variables) elif self.rule_in_line == 'SETVAR': LineParser.__variables.SetVar(self.line.split(':')[1], (self.line.split(':')[2]).split('\n')[0]) MyPlot.UpdateGlobals(Variable.variables) elif self.rule_in_line == 'CALCULATE': LineParser.__variables.Calculate(self.line.split(':')[1], (self.line.split(':')[2]).split('\n')[0]) MyPlot.UpdateGlobals(Variable.variables) elif self.rule_in_line == 'CREATEPLOT': LineParser.__plots.CreatePlot((self.line.split(':')[1]).split('\n')[0]) elif self.rule_in_line == 'ADDTOPLOT': LineParser.__plots.AddToPlot(self.line.split(':')[1], self.line.split(':')[2], (self.line.split(':')[3]).split('\n')[0]) elif self.rule_in_line == 'SHOWPLOT': LineParser.__plots.ShowPlot((self.line.split(':')[1]).split('\n')[0]) elif self.rule_in_line == 'CREATEFCT': LineParser.__function_create_start = (self.line.split(':')[1]).split('\n')[0] LineParser.__functions.CreateFunction((self.line.split(':')[1]).split('\n')[0]) elif self.rule_in_line == 'CALL': LineParser.__functions.CallFunction((self.line.split(':')[1]).split('\n')[0]) else: pass else: if self.rule_in_line == 'CREATEVAR': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'SETVAR': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'CALCULATE': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'CREATEPLOT': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'ADDTOPLOT': LineParser.__functions = Function() LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'SHOWPLOT': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'ENDFCT': LineParser.__function_create_start = None
def show_weight(self): print('shape=', self.weights) if len(self.weights[0]) is 1: mp = MyPlot() mp.set_labels('Step', 'Weight') mp.show_list(self.weights) else: print('Cannot show the weight! Call print_weight method.')
#----- a neuron w = tf.Variable(tf.random_normal([2, 1])) b = tf.Variable(tf.random_normal([1])) hypo = tf.matmul(x, w) + b #----- cost = tf.reduce_mean((hypo - y) * (hypo - y)) train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) costs = [] for i in range(2001): sess.run(train) if i % 50 == 0: print('hypo:', sess.run(hypo), '|', sess.run(w), sess.run(b), sess.run(cost)) costs.append(sess.run(cost)) hypo2 = tf.matmul([[4., 4]], w) + b print(sess.run(hypo2)) p = MyPlot() p.show_list(costs)
def show_error(self): mp = MyPlot() mp.set_labels('Step', 'Error') mp.show_list(self.costs)
class LineParser(object): __rules = [ 'CREATEVAR', 'SETVAR', 'CALCULATE', 'CREATEPLOT', 'ADDTOPLOT', 'SHOWPLOT', 'CREATEFCT', 'ENDFCT', 'CALL'] __function_create_start = None __variables = Variable() __plots = MyPlot() __functions = Function() def __init__(self, line): self.line = line self.error = 0 self.rule_in_line = '' def update_globals(self, globals): pass def get_rule(self): for __rule in LineParser.__rules: __location = -1 __matching_rules = 0 while __matching_rules <=2: #search multiple identical rules in the same line __location = self.line.find(__rule, __location + 1) if __location == -1: break else: __matching_rules += 1 if __matching_rules == 1: self.rule_in_line = __rule self.error += 1 else: self.error += 1 def implement_rule(self): if LineParser.__function_create_start == None: if self.rule_in_line == 'CREATEVAR': LineParser.__variables.CreateVar((self.line.split(':')[1]).split('\n')[0]) MyPlot.UpdateGlobals(Variable.variables) elif self.rule_in_line == 'SETVAR': LineParser.__variables.SetVar(self.line.split(':')[1], (self.line.split(':')[2]).split('\n')[0]) MyPlot.UpdateGlobals(Variable.variables) elif self.rule_in_line == 'CALCULATE': LineParser.__variables.Calculate(self.line.split(':')[1], (self.line.split(':')[2]).split('\n')[0]) MyPlot.UpdateGlobals(Variable.variables) elif self.rule_in_line == 'CREATEPLOT': LineParser.__plots.CreatePlot((self.line.split(':')[1]).split('\n')[0]) elif self.rule_in_line == 'ADDTOPLOT': LineParser.__plots.AddToPlot(self.line.split(':')[1], self.line.split(':')[2], (self.line.split(':')[3]).split('\n')[0]) elif self.rule_in_line == 'SHOWPLOT': LineParser.__plots.ShowPlot((self.line.split(':')[1]).split('\n')[0]) elif self.rule_in_line == 'CREATEFCT': LineParser.__function_create_start = (self.line.split(':')[1]).split('\n')[0] LineParser.__functions.CreateFunction((self.line.split(':')[1]).split('\n')[0]) elif self.rule_in_line == 'CALL': LineParser.__functions.CallFunction((self.line.split(':')[1]).split('\n')[0]) else: pass else: if self.rule_in_line == 'CREATEVAR': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'SETVAR': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'CALCULATE': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'CREATEPLOT': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'ADDTOPLOT': LineParser.__functions = Function() LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'SHOWPLOT': LineParser.__functions.AddToFunction(LineParser.__function_create_start, self.line) elif self.rule_in_line == 'ENDFCT': LineParser.__function_create_start = None
def callback(self, state): self.addPoint(state.PosAct) # A worker class for the ros node # To be deprecated soon class WorkerListener(Thread): def __init__(self): Thread.__init__(self) def run(self): rospy.ready(NAME, anonymous=True) rospy.spin() channel = MyChannel() channel2 = MyChannelAct() rospy.TopicSub('ARM_L_PAN_state', RotaryJointState, channel.callback) rospy.TopicSub('ARM_L_PAN_state', RotaryJointState, channel2.callback) app = wx.PySimpleApp(0) worker=WorkerListener() worker.start() frame = wx.Frame(None, -1,"") panel = MyPlot(frame) panel.addChannel(channel) panel.addChannel(channel2) frame.Show() print '>>>>>>>>>>>>>>' app.MainLoop() print '>>>>>>>>>>>>>>' #rospy.spin()
def make_plot(data, properties, titles, **kwargs): """ main function to generate a 1D plot * each dataset is represented by a numpy array consisting of data points in the format ``[x, y, dx, dy1, dy2]``, dy1 = statistical error, dy2 = systematic uncertainty * for symbol numbers to use in labels see http://bit.ly/1erBgIk * lines format: `'<x/y>=<value>': '<gnuplot options>'`, horizontal = (along) x, vertical = (along) y * labels format: `'label text': [x, y, abs. placement true/false]` * arrows format: `[<x0>, <y0>], [<x1>, <y1>], '<gnuplot props>'` :param data: datasets :type data: list :param properties: gnuplot property strings for each dataset (lc, lw, pt ...) :type properties: list :param titles: legend/key titles for each dataset :type titles: list :param name: basename of output files :type name: str :param title: image title :type title: str :param debug: flag to switch to debug/verbose mode :type debug: bool :param key: legend/key options to be applied on top of default_key :type key: list :param xlabel: label for x-axis :type xlabel: str :param ylabel: label for y-axis :type ylabel: str :param xr: x-axis range :type xr: list :param yr: y-axis range :type yr: list :param xreverse: reverse x-axis range :type xreverse: bool :param yreverse: reverse x-axis range :type yreverse: bool :param xlog: make x-axis logarithmic :type xlog: bool :param ylog: make y-axis logarithmic :type ylog: bool :param lines: vertical and horizontal lines :type lines: dict :param arrows: arrows :type arrows: list :param labels: labels :type labels: dict :param lmargin: defines left margin size (relative to screen) :type lmargin: float :param bmargin: defines bottom margin size :type bmargin: float :param rmargin: defines right margin size :type rmargin: float :param tmargin: defines top margin size :type tmargin: float :param arrow_offset: offset from data point for special error bars (see gp_panel) :type arrow_offset: float :param arrow_length: length of arrow from data point towards zero for special error bars (see gp_panel) :type arrow_length: float :param arrow_bar: width of vertical bar at end of special error bars (see gp_panel) :type arrow_bar: float :param gpcalls: execute arbitrary gnuplot set commands :type gpcalls: list :returns: MyPlot """ plt = MyPlot( name = kwargs.get('name', 'test'), title = kwargs.get('title', ''), debug = kwargs.get('debug', 0) ) plt.setErrorArrows(**kwargs) plt.setAxisLogs(**kwargs) plt.initData(data, properties, titles) plt.prepare_plot(**kwargs) plt._setter(kwargs.get('gpcalls', [])) plt.plot() return plt
def make_panel(dpt_dict, **kwargs): """make a panel plot * ``name/title/debug`` are global options used once to initialize the multiplot * ``x,yr/x,ylog/lines/labels/gpcalls`` are applied on each subplot * ``key/ylabel`` are only plotted in first subplot * ``xlabel`` is centered over entire panel * same for ``r,l,b,tmargin`` where ``r,lmargin`` will be reset, however, to allow for merged y-axes * input: OrderedDict w/ subplot titles as keys and lists of make_plot's ``data/properties/titles`` as values, see below * ``layout`` = '<cols>x<rows>', defaults to horizontal panel if omitted * ``key_subplot_id`` sets the desired subplot to put the key in :param dpt_dict: ``OrderedDict('subplot-title': [data, properties, titles], ...)`` :type dpt_dict: dict """ plt = MyPlot( name = kwargs.get('name', 'test'), title = kwargs.get('title', ''), debug = kwargs.get('debug', 0) ) nSubPlots = len(dpt_dict) plt.size = kwargs.get('size', default_size) height, width = [ float(ureg.parse_expression(s).to('cm').magnitude) for s in plt.size.split(',') ] text_inch = ureg.parse_expression('24point').to('cm').magnitude lm = kwargs.get('lmargin', 2.2*text_inch/width) bm = kwargs.get('bmargin', 1.8*text_inch/height) rm = kwargs.get('rmargin', 0.99) tm = kwargs.get('tmargin', 0.99) xlabel, ylabel = kwargs.get('xlabel',''), kwargs.get('ylabel','') plt._setter([ 'label 100 "%s" at screen %f,%f rotate center' % (ylabel, lm/2/2.2, (bm+tm)/2), 'label 101 "%s" at screen %f,%f center' % (xlabel, (lm+rm)/2, bm/2/1.8), ]) nx, ny = nSubPlots, 1 # horizontal panel by default layout = kwargs.get('layout') if layout is not None: nx, ny = map(int, layout.split('x')) w, h = (rm - lm) / nx, (tm - bm) / ny nDanglPlots = nSubPlots%nx # number of plots "dangling" in last row plt._setter([ 'terminal postscript eps enhanced color "Helvetica" 24 size %fcm,%fcm' % (width, height), 'output "%s"' % plt.epsname, 'multiplot layout %d,%d rowsfirst' % (ny, nx) ]) plt.setErrorArrows(**kwargs) xgap, ygap = 0.1 / width, 0.1 / height # both in cm key_subplot_id = kwargs.get('key_subplot_id', 0) if nDanglPlots > 0 and key_subplot_id > len(dpt_dict)-1: # allow for key in dangling panel cp_key = dpt_dict.keys()[0] xr = kwargs.get('xr') if xr is not None: xfake = xr[0] - 0.5 * (xr[1]-xr[0]) else: xfake = 1. dpt_dict.update({'': [ [ np.array([[xfake, 1, 0, 0, 0]]) for d in dpt_dict[cp_key][0] ], dpt_dict[cp_key][1], dpt_dict[cp_key][2] ]}) for subplot_title, dpt in dpt_dict.iteritems(): if plt.nLabels > 0: plt.gp('unset label') plt.setLabel('{/Helvetica-Bold %s}' % subplot_title, [0.1, 0.9]) plt.setAxisLogs(**kwargs) plt.initData(*dpt, subplot_title = subplot_title) plt.prepare_plot(margins=False, **kwargs) col, row = plt.nPanels % nx, plt.nPanels / nx sub_lm = lm + col * w + xgap/2. sub_rm = lm + (col + 1) * w - xgap/2. sub_tm = tm - row * h - ygap/2. sub_bm = tm - (row + 1) * h + ygap/2. plt.gp('unset xlabel') plt.gp('unset ylabel') if col > 0: plt.gp('set format y " "') if ( row < ny-1 and not nDanglPlots ) or ( row+1 == ny-1 and nDanglPlots and col+1 <= nDanglPlots ): plt.gp('set format x " "') if plt.nPanels > 0: plt.gp('set noarrow') if plt.nPanels != key_subplot_id: plt.gp('unset key') plt.nPanels += 1 plt._setter([ 'lmargin at screen %f' % sub_lm, 'rmargin at screen %f' % sub_rm, 'bmargin at screen %f' % sub_bm, 'tmargin at screen %f' % sub_tm ] + kwargs.get('gpcalls', [])) if nDanglPlots > 0 and plt.nPanels-1 == key_subplot_id: plt.gp('set format x " "') plt.gp('unset border') plt.gp('unset xtics') plt.gp('unset ytics') plt.gp('unset object') plt.plot(hardcopy = False) plt._hardcopy() plt.gp('unset multiplot; set output')
from myplot import MyPlot import sys data = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] print(data) print('Number of arguments:', len(sys.argv), 'arguments.') print('Argument List:', str(sys.argv)) #type_of_graph = int(input("What is the type of graph you want. \n Press 1 for histogram \n Press 2 for bar chart \n Press 3 for scatter plot. \n Press 4 for line plot \n Press 5 for histogram\n Press 6 for pie chart")) #{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'} type_of_graph = int(sys.argv[1]) myplt = MyPlot(type_of_graph, str(sys.argv[2]), data) myplt.plot_graph() #fig, axs = plt.subplots(2, 2, figsize=(5, 5)) #axs[0, 0].hist(data[0]) #axs[1, 0].scatter(data[0], data[1]) #axs[0, 1].plot(data[0], data[1]) #axs[1, 1].hist2d(data[0], data[1])
train = tf.train.GradientDescentOptimizer(learning_rate=0.2).minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) errors = [] for step in range(10001): sess.run(train) #계산그래프, 데이터 4개에 대하여 forward prop. 오류값을 구하고 충분히 작지 않으면 if step % 500 == 0: #print(step, sess.run(cost)) errors.append(sess.run(cost)) #----- testing(classification) predicted = tf.cast(hypo > 0.5, dtype=tf.float32) accuracy = tf.reduce_mean( tf.cast(tf.equal(predicted, y_data), dtype=tf.float32)) h = sess.run(hypo) print("\nHypo: ", h) p = sess.run(predicted) print("Predicted: ", p) a = sess.run(accuracy) print("Accuracy(%): ", a * 100) from myplot import MyPlot p = MyPlot() p.show_list(errors)
self.addPoint(state.PosAct) # A worker class for the ros node # To be deprecated soon class WorkerListener(Thread): def __init__(self): Thread.__init__(self) def run(self): rospy.ready(NAME, anonymous=True) rospy.spin() channel = MyChannel() channel2 = MyChannelAct() rospy.TopicSub('ARM_L_PAN_state', RotaryJointState, channel.callback) rospy.TopicSub('ARM_L_PAN_state', RotaryJointState, channel2.callback) app = wx.PySimpleApp(0) worker = WorkerListener() worker.start() frame = wx.Frame(None, -1, "") panel = MyPlot(frame) panel.addChannel(channel) panel.addChannel(channel2) frame.Show() print '>>>>>>>>>>>>>>' app.MainLoop() print '>>>>>>>>>>>>>>' #rospy.spin()
from myplot import MyPlot x_data = [1] y_data = [1] #----- a neuron w = tf.Variable(tf.random_normal([1])) b = tf.Variable(tf.random_normal([1])) hypo = w * x_data + b #----- cost = (hypo - y_data) ** 2 train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) costs = [] for i in range(1001): sess.run(train) if i % 50 == 0: print(sess.run(w), sess.run(b), sess.run(cost)) costs.append(sess.run(cost)) gildong = MyPlot() gildong.show_list(costs)