xx.append(line_y1[i]) line2.append(np.array(xx)) x_inner, y_outer = make_blobs(n_samples = n_point_per_cluster*2, n_features=2, centers=[[15.0, 13], [17, 8]], cluster_std=0.12, random_state=0) x_outer, y_inner = make_blobs(n_samples = n_point_per_cluster, n_features=2, centers=[[13, 8]], cluster_std=0.20, random_state=0) x_c2, y_c2 = make_blobs(n_samples = n_point_per_cluster, n_features=1, centers=[[13, 10]], cluster_std=4.0, random_state=0) #dataX = np.vstack((X, x1, x4, x5, x2, line1, line2, x_inner, x_outer, x_c2)) dataX = np.vstack((X, x4, x2, x_inner, x_outer, x_c2)) # # plot data file # # ============================================================================= plt.Figure(figsize=(30,30)) plt.plot(dataX[:,0], dataX[:,1], 'b,') plt.show() # # ============================================================================= file_name = open("dataSets_50K.txt",'w') for data in dataX: for i in range(len(data)): file_name.write(str(data[i]) +" ") file_name.write("\n") file_name.close()
def __init__(self, _name, _context, _master=None): self.name = _name self.master = _master self.context = _context self.nrl = self.context['nrl'] self.ut = self.context['ut'] self.cwp = self.context['cwd'] self.delimiter = self.context['delimiter'] self.modelConfigDir = self.context['modelconfigdir'] self.datasetDir = self.context['datasetdir'] self.experimentDir = self.context['experimentdir'] self.stateParser = None self.m = None self.d = None self.modelLoaded = False f_padx = self.context['f_padx'] f_pady = self.context['f_pady'] padx_ = self.context['padx'] pady_ = self.context['pady'] self.xLimMouse = [-65.0, 65.0] self.yLimMouse = [-65.0, 65.0] self.xLimPlot = [-55.0, 55.0] self.yLimPlot = [-55.0, 55.0] self.motionSaturation = 5 self.aplhaFgPlot = 1.0 self.aplhaBgPlot = 0.2 self.datasetColor = '#4affff' self.drawColor = 'brown' self.time_ms = self.ut.getCurrentTimeMS() #--- Initialization self.mouseIn = False self.drawHuman = False self.nActDof = 2 self.mc = 0.9 self.step = 0 self.samplingPeriod = 0 self.showERLog = False self.stateBufferSize = 0 # default values self.wInit = '1.0e-5' self.postdiction_epochs = 15 self.windowSize = 5 self.alpha = 0.3 self.beta1 = 0.1 self.beta2 = 0.95 self.nBuffdata = self.windowSize * self.nActDof self.expTimeSteps = 2000 self.runExperiment = False self.plotBuffSize = 50 # for visualization purposes self.topDownId = 0 self.ERStartTime = self.windowSize -1 # maps self.primSet = {} self.state_index = {} # containers self.robotBuffer = deque(maxlen=self.plotBuffSize) self.humanBuffer = deque(maxlen=self.plotBuffSize) self.posWinBuffer = deque(maxlen=self.windowSize) self.signal_list = [] self.opt_elbo_list = [] self.state_list = [] self.tgt_pos_list = [] self.cur_pos_list = [] self.hum_pos_list = [] self.hum_int_list = [] self.primCanvas = [] self.signalVar = tk.BooleanVar() self.sliderLabelVar = tk.StringVar() self.sliderLabelVar.set('{:.2f}'.format(self.mc)) self.WStext = 'Workspace' # === BLOCK 1: Parameter section self.f_t1_f1_controls = ttk.Frame(self.master) self.f_t1_f1_f1 = ttk.LabelFrame(self.f_t1_f1_controls, relief=tk.SUNKEN, text=" Selection ") self.l_t1_f1_f1_N = ttk.Label(self.f_t1_f1_f1, text="Model:") self.l_t1_f1_f1_D = ttk.Label(self.f_t1_f1_f1, text="Dataset:") self.l_t1_f1_f1_S = ttk.Label(self.f_t1_f1_f1, text="Signal:") self.l_t1_f1_f1_F = ttk.Label(self.f_t1_f1_f1, text="Format:") self.l_t1_f1_f1_Nv = ttk.Label(self.f_t1_f1_f1, text=" ") self.l_t1_f1_f1_Dv = ttk.Label(self.f_t1_f1_f1, text=" ") self.c_t1_f1_f1_S = ttk.Combobox(self.f_t1_f1_f1, values=['empty'], width= 20, state="readonly") self.c_t1_f1_f1_F = ttk.Combobox(self.f_t1_f1_f1, values=['Raw','Sum','Mean'], width= 20, state="readonly") self.l_t1_f1_f1_N.grid(row=0, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f1_D.grid(row=1, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f1_S.grid(row=2, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f1_F.grid(row=3, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f1_Nv.grid(row=0, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.l_t1_f1_f1_Dv.grid(row=1, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.c_t1_f1_f1_S.grid(row=2, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.c_t1_f1_f1_F.grid(row=3, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.c_t1_f1_f1_S.bind("<<ComboboxSelected>>", self.doComboSignal) self.c_t1_f1_f1_F.current(0) self.c_t1_f1_f1_F.bind("<<ComboboxSelected>>", self.doComboFormatSignal) self.f_t1_f1_f2 = ttk.LabelFrame(self.f_t1_f1_controls, relief=tk.SUNKEN, text=" ADAM ") self.l_t1_f1_f2_ADAM_A = ttk.Label(self.f_t1_f1_f2, text="\u03B1:") self.l_t1_f1_f2_ADAM_B1 = ttk.Label(self.f_t1_f1_f2, text="\u03B2\u2081:") self.l_t1_f1_f2_ADAM_B2 = ttk.Label(self.f_t1_f1_f2, text="\u03B2\u2082:") self.e_t1_f1_f2_ADAM_A = ttk.Entry(self.f_t1_f1_f2, width=10) self.e_t1_f1_f2_ADAM_B1 = ttk.Entry(self.f_t1_f1_f2, width=10) self.e_t1_f1_f2_ADAM_B2 = ttk.Entry(self.f_t1_f1_f2, width=10) self.e_t1_f1_f2_ADAM_A.bind("<KeyRelease>", self.entryKeyRelease) self.e_t1_f1_f2_ADAM_B1.bind("<KeyRelease>", self.entryKeyRelease) self.e_t1_f1_f2_ADAM_B2.bind("<KeyRelease>", self.entryKeyRelease) self.l_t1_f1_f2_ADAM_A.grid(row=0, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f2_ADAM_B1.grid(row=1, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f2_ADAM_B2.grid(row=2, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.e_t1_f1_f2_ADAM_A.grid(row=0, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.e_t1_f1_f2_ADAM_B1.grid(row=1, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.e_t1_f1_f2_ADAM_B2.grid(row=2, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.f_t1_f1_f3 = ttk.LabelFrame(self.f_t1_f1_controls, relief=tk.SUNKEN, text=" Postdiction ") self.l_t1_f1_f3_Epd = ttk.Label(self.f_t1_f1_f3, text="Enable:") self.l_t1_f1_f3_E = ttk.Label(self.f_t1_f1_f3, text="Epochs:") self.l_t1_f1_f3_Win = ttk.Label(self.f_t1_f1_f3, text="Window:") self.l_t1_f1_f3_W = ttk.Label(self.f_t1_f1_f3, text="w:") self.c_t1_f1_f3_Epd = ttk.Combobox(self.f_t1_f1_f3, values=['yes','no'], width= 10, state="readonly") self.e_t1_f1_f3_E = ttk.Entry(self.f_t1_f1_f3, width=10) self.e_t1_f1_f3_Win = ttk.Entry(self.f_t1_f1_f3, width=15) self.e_t1_f1_f3_W = ttk.Entry(self.f_t1_f1_f3, width=15) self.c_t1_f1_f3_Epd.bind("<<ComboboxSelected>>", self.doComboPostdiction) self.c_t1_f1_f3_Epd.set('yes') self.e_enabled = True self.interationMode = False self.e_t1_f1_f3_E.bind("<KeyRelease>", self.entryKeyRelease) self.e_t1_f1_f3_Win.bind("<KeyRelease>", self.entryKeyRelease) self.e_t1_f1_f3_W.bind("<KeyRelease>", self.entryKeyRelease) self.l_t1_f1_f3_Epd.grid(row=0, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f3_E.grid(row=1, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f3_Win.grid(row=2, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f3_W.grid(row=3, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.c_t1_f1_f3_Epd.grid(row=0, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.e_t1_f1_f3_E.grid(row=1, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.e_t1_f1_f3_Win.grid(row=2, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.e_t1_f1_f3_W.grid(row=3, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.f_t1_f1_f4 = ttk.LabelFrame(self.f_t1_f1_controls, relief=tk.SUNKEN, text=" Experiment ") self.l_t1_f1_f4_T = ttk.Label(self.f_t1_f1_f4, text="Time steps:") self.l_t1_f1_f4_P = ttk.Label(self.f_t1_f1_f4, text="Period in ms:") self.l_t1_f1_f4_Prim = ttk.Label(self.f_t1_f1_f4, text="Initial primitive:") self.l_t1_f1_f4_Mc = ttk.Label(self.f_t1_f1_f4, text="Motor compliance:") self.e_t1_f1_f4_T = ttk.Entry(self.f_t1_f1_f4, width=10) self.e_t1_f1_f4_P = ttk.Entry(self.f_t1_f1_f4, width=10) self.c_t1_f1_f4_Prim = ttk.Combobox(self.f_t1_f1_f4, values=['empty'], width= 10, state="readonly", postcommand=self.initComboPrimitive) self.f_t1_f1_f4_f1 = ttk.Frame(self.f_t1_f1_f4) self.l_t1_f1_f4_Mc_l = ttk.Label(self.f_t1_f1_f4_f1, textvariable=self.sliderLabelVar) self.s_t1_f1_f4_Mc = ttk.Scale(self.f_t1_f1_f4_f1, from_=0.0, to=1.0, orient=tk.HORIZONTAL,\ length=100, value = self.mc, command=self.doScaleMotorCompliance) self.s_t1_f1_f4_Mc.grid(row=0, column=0, padx=0, pady=pady_, sticky=tk.W) self.l_t1_f1_f4_Mc_l.grid(row=0, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.e_t1_f1_f4_T.bind("<KeyRelease>", self.entryKeyRelease) self.e_t1_f1_f4_P.bind("<KeyRelease>", self.entryKeyRelease) self.c_t1_f1_f4_Prim.bind("<<ComboboxSelected>>", self.doComboPrimitive) self.l_t1_f1_f4_T.grid(row=0, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f4_P.grid(row=1, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f4_Prim.grid(row=2, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.l_t1_f1_f4_Mc.grid(row=3, column=0, padx=padx_, pady=pady_, sticky=tk.E) self.e_t1_f1_f4_T.grid(row=0, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.e_t1_f1_f4_P.grid(row=1, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.c_t1_f1_f4_Prim.grid(row=2, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.f_t1_f1_f4_f1.grid(row=3, column=1, padx=padx_, pady=pady_, sticky=tk.W) self.f_t1_f1_f4_f2 = ttk.Frame(self.f_t1_f1_f4) self.b_t1_f1_f4_f2_Start = ttk.Button(self.f_t1_f1_f4_f2, text="Start", command=self.doStart) self.b_t1_f1_f4_f2_Pause = ttk.Button(self.f_t1_f1_f4_f2, text="Pause", command=self.doPause) self.b_t1_f1_f4_f2_Reset = ttk.Button(self.f_t1_f1_f4_f2, text="Reset", command=self.doReset) self.b_t1_f1_f4_f2_Save = ttk.Button(self.f_t1_f1_f4_f2, text="Save", command=self.doSave) self.b_t1_f1_f4_f2_Start.grid(row=0, column=0, padx=padx_, pady=pady_, sticky=tk.N) self.b_t1_f1_f4_f2_Pause.grid(row=0, column=1, padx=padx_, pady=pady_, sticky=tk.N) self.b_t1_f1_f4_f2_Reset.grid(row=0, column=2, padx=padx_, pady=pady_, sticky=tk.N) self.b_t1_f1_f4_f2_Save.grid(row=0, column=3, padx=padx_, pady=pady_, sticky=tk.N) self.f_t1_f1_f4_f2.grid(columnspan=2) self.f_t1_f1_f1.pack(side=tk.LEFT, expand=1, fill=tk.X, padx=padx_, pady=pady_, anchor=tk.N) self.f_t1_f1_f2.pack(side=tk.LEFT, expand=1, fill=tk.X, padx=padx_, pady=pady_, anchor=tk.N) self.f_t1_f1_f3.pack(side=tk.LEFT, expand=1, fill=tk.X, padx=padx_, pady=pady_, anchor=tk.N) self.f_t1_f1_f4.pack(side=tk.LEFT, expand=1, fill=tk.X, padx=padx_, pady=pady_, anchor=tk.N) # === BLOCK 2: Workspace self.f_t1_f2 = ttk.Frame(self.master, relief=tk.SUNKEN) cW = 5.5 cH = 5.5 self.fig = plt.Figure(constrained_layout=False,figsize=(cW, cH), dpi=100, facecolor=(0.1, 0.1, 0.1)) cHf1 = cH cHf2 = cHf1/20.0 cH = cHf1+cHf2 fWidths = [cW] fHeights = [cHf1, cHf2] spec = gridspec.GridSpec(ncols=1, nrows=2, width_ratios=fWidths, height_ratios=fHeights, figure=self.fig) self.ax = self.fig.add_subplot(spec[0, 0]) # reducing the number of ticks in the axis to 3 self.ax.xaxis.set_major_locator(plt.MaxNLocator(3)) self.ax.yaxis.set_major_locator(plt.MaxNLocator(3)) self.ax.axis('off') self.ax.axis('square') self.axSignal = self.fig.add_subplot(spec[1, 0]) self.ax.set_xlim(self.xLimMouse) self.ax.set_ylim(self.yLimMouse) self.drawPrim, = self.ax.plot(0, 0, self.drawColor) self.tCtrMsg = 'Press control to interact' self.drawControl = self.ax.text(15.0, 65.0, '', style='italic', color='teal', bbox={'facecolor': 'teal', 'alpha': 0.5, 'pad': 10}) self.drawWSTitle = self.ax.text(-55.0, 60.0, '', style='italic', color=self.datasetColor ) ## signal plot self.axSignal.axis('off') self.signalYmin = 0.0 self.signalYmax = 20.0 self.f_t1_f2_canvas = FigureCanvasTkAgg(self.fig, master=self.f_t1_f2) # A tk.DrawingArea. self.f_t1_f2_canvas.draw() self.f_t1_f2_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1, padx=f_padx) self.toolbar = NavigationToolbar2Tk(self.f_t1_f2_canvas, self.f_t1_f2) self.toolbar.update() self.mouseH = Mouse(self.drawPrim, self.xLimMouse, self.yLimMouse) self.fig.canvas.mpl_connect('key_press_event', self.keyPressed) self.fig.canvas.mpl_connect('key_release_event', self.keyReleased) self.messenger = Message() self.f_t1_f1_controls.pack(side=tk.TOP, expand=0, fill=tk.X, padx=f_padx, pady=10, anchor=tk.N) self.f_t1_f2.pack(side=tk.TOP, expand=1, fill=tk.BOTH, padx=f_padx, anchor=tk.N) # plot objects self.robotCanvas, = self.ax.plot(0.0, 0.0) self.robotEffCanvas, = self.ax.plot(0.0, 0.0, color='red', marker='o') self.humanCanvas, = self.ax.plot(0.0, 0.0) self.signalCanvas, = self.axSignal.plot(0.0, 0.0, color='orangered') self.signalTitle = self.ax.text(-55.0, -63.0, '', style='italic', color=self.datasetColor) self.cur_pos = np.array([0.0,0.0]) self.hum_pos = np.array([0.0,0.0]) # thread loop self.timer = self.fig.canvas.new_timer(interval=10, callbacks=[(self.doLoop, [], {})]) self.timer.start()
type_imp_fun) # optimize_results = optimize.differential_evolution(func=fct.make_Y, bounds = bounds, args = args, workers = 3) optimize_results = optimize.brute(func=fct.make_Y, ranges=bounds, args=args, Ns=5, full_output=True) # optimize_results = optimize.minimize(fun = fct.make_Y, x0 = init_parameter,method="Powell", args = args, bounds = bounds) # test = fct.make_Y(init_parameter, args) print(optimize_results) print(score_type) print(optimize_type) test_if_ranges_make_sense = True if test_if_ranges_make_sense: plt.Figure() x = np.arange(0, 120, 1) for L in [0.5]: for x_0 in [50]: for k in np.arange(1, 10, 2): plt.plot(fct.sigmoid(x, L, x_0, k)) plt.show() plt.Figure() x = np.arange(0, 240, 1) for L in np.arange(0.1, 1, 0.1): for x_0 in np.arange(1.0, 150, 20): for k in np.arange(1, 20, 2): plt.plot(fct.sigmoid(x, L, x_0, k)) plt.show() # imp_agr.plot_raster_eai_exposure(raster_res = 0.008333333333325754) #%% WICHTIG: WIESO IST haz_hail.intensity_thresh = 10?????????????
def plot_dataset_boxplot(self, dataset, cols): plt.Figure() dataset[cols].plot.box() plt.ylim([-30, 30]) self.save(plt) plt.show()
def __generate_overview_matrix(self): data = np.zeros((10, 10)) no_classification = 0 correct_classification = 0 sums = np.zeros((10, 1)) sums_correct = np.zeros((10, 1)) for i in range(len(self.overview_data)): if self.overview_data[i][0] >= 0 and self.overview_data[i][ 1] >= 0 and self.overview_data[i][ 0] < 10 and self.overview_data[i][ 1] < 10 and self.overview_data[i][ 2] >= self.minProb: # Rows = target, cols = actual data[self.overview_data[i][0]][self.overview_data[i][1]] += 1 if self.overview_data[i][0] == self.overview_data[i][1]: correct_classification += 1 sums_correct[self.overview_data[i][0]] += 1 sums[self.overview_data[i][0]] += 1 else: no_classification += 1 str_result = "Richtig klassifiziert (alle Daten): %s von %s (%s%%) \n Nicht klassifiziert: %s" \ % (correct_classification, len(self.overview_data), (correct_classification / len(self.overview_data)) * 100, no_classification) # Creating the figure figure = plt.Figure(figsize=(7, 7), dpi=100) graph = figure.add_subplot(111) major_ticks = np.arange(0, 10, 1) graph.set_xticks(major_ticks) graph.set_yticks(major_ticks) graph.set_xticklabels(major_ticks) graph.set_yticklabels(major_ticks) graph.set_xlabel("Predicted") graph.set_ylabel("Target") # Configure color cmap = plt.cm.RdYlGn mask = np.ma.masked_where(data == 0, data) cmap.set_bad(color="lightgrey") imgplot = graph.imshow(mask, cmap=cmap) # Add sums to the right side for i in range(10): str = "%s / %s" % (int( sums_correct[i][0]).__str__(), int(sums[i][0]).__str__()) graph.text(10, i, str) # Add text to the graph for i in range(10): for j in range(10): graph.text(-0.2 + i, 0.1 + j, int(data[j][i])) return figure, str_result
def eeg_like(file_name, folder=None): if folder is None: folder = "data/figures" os.makedirs(folder, exist_ok=True) bkp = backup.RunBackup.load(file_name=file_name) pst = bkp.positions prc = bkp.prices t_max = 250 # bkp.parameters.t_max t = np.arange(1, t_max) position_A = pst[1:t_max, 0] position_B = pst[1:t_max, 1] price_A = prc[1:t_max, 0] price_B = prc[1:t_max, 1] color_A = "orange" color_B = "blue" position_min = 0 position_max = bkp.parameters.n_positions - 1 price_min = 1 price_max = bkp.parameters.n_prices * bkp.parameters.unit_value fig = plt.Figure() # Position firm A ax = plt.subplot(4, 1, 1) ax.plot(t, position_A, color=color_A, alpha=1, linewidth=1.1) ax.plot(t, np.ones(len(t)) * 50, color='0.5', linewidth=0.5, linestyle='dashed', zorder=-10) # ax.plot(t, position_B, color="black", alpha=0.5, linewidth=1) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_xticks([]) ax.set_yticks([position_min, position_max]) ax.set_ylabel('Position A', labelpad=10) # Add title plt.title("Evolution of positions and prices ($r={}$)".format(bkp.field_of_view/2)) # Position firm B ax = plt.subplot(4, 1, 2) ax.plot(t, position_B, color=color_B, alpha=1, linewidth=1.1) ax.plot(t, np.ones(len(t)) * 50, color='0.5', linewidth=0.5, linestyle='dashed', zorder=-10) # ax.plot(t, position_A, color="black", alpha=0.5, linewidth=1) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_xticks([]) ax.set_yticks([position_min, position_max]) ax.set_ylabel('Position B', labelpad=10) # Price firm A ax = plt.subplot(4, 1, 3) ax.plot(t, price_A, color=color_A, alpha=1, linewidth=1.1, clip_on=False) # ax.plot(t, price_B, color="black", alpha=0.5, linewidth=1) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_xticks([]) ax.set_yticks([price_min, price_max]) ax.set_ylabel('Price A', labelpad=10) # , rotation=0) ax.set_ylim([price_min, price_max]) # Price firm B ax = plt.subplot(4, 1, 4) ax.plot(t, price_B, color=color_B, alpha=1, linewidth=1.1, clip_on=False) # ax.plot(t, price_A, color="black", alpha=0.5, linewidth=1) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_xticks([]) ax.set_yticks([price_min, price_max]) ax.set_ylabel('Price B', labelpad=10) # , rotation=0) ax.set_ylim([price_min, price_max]) ax.set_xlabel("Time", labelpad=10) plt.text(0.005, 0.005, file_name, transform=fig.transFigure, fontsize='x-small', color='0.5') plt.savefig("{}/{}_eeg_like.pdf".format(folder, file_name)) plt.show()
import numpy as np import matplotlib.pyplot as plt #%matplotlib inline from PIL import Image import cv2 b_img=np.zeros((512,512),np.int8) plt.Figure(figsize=(20,20)) def dc(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONDOWN: cv2.circle(img,(x,y),100,(0,255,0),-1) cv2.namedWindow(winname='my') cv2.setMouseCallback('my',dc) while True: plt.imshow('my',b_img) if cv2.waitKey(20) & 0xFF==27: break cv2.destroyAllWindows()
class chef(): __root = Tk() # default window width and height __thisWidth = 200 __thisHeight = 200 __thisMenuBar = Menu(__root, relief=FLAT) __thisFileMenu = Menu(__thisMenuBar, tearoff=0) __text = Text() __thisHelpMenu = Menu(__thisMenuBar, tearoff=0) __cls = Button() __checkFrame1 = Frame() __checkFrame2 = Frame() __tableFrame = Frame() __toolbarFrame = Frame() __fig = plt.Figure() __file = None def __init__(self, **kwargs): try: self.__thisWidth = kwargs['w'] except KeyError: pass try: self.__thisHeight = kwargs['h'] except KeyError: pass # Set the window text self.__root.title("MagOD Chef") # Center the window screenWidth = self.__root.winfo_screenwidth() screenHeight = self.__root.winfo_screenheight() # For left-allignment left = (screenWidth / 2) - (self.__thisWidth / 2) # For right-allignment right = (screenHeight / 2) - (self.__thisHeight / 2) # For top and bottom self.__root.geometry( '%dx%d+%d+%d' % (self.__thisWidth, self.__thisHeight, left, right)) self.__root.resizable(1, 1) self.__root.grid() # Add Frame self.__checkFrame1 = Frame(self.__root).grid(row=0, column=0, sticky='NEWS') self.__checkFrame2 = Frame(self.__root).grid(row=0, column=8, sticky='NEWS') self.__tableFrame = Frame(self.__root) self.__tableFrame.grid(column=1, row=10, columnspan=7, rowspan=6, sticky='NEWS') self.__toolbarFrame = Frame(self.__root) self.__toolbarFrame.grid(column=1, row=9, rowspan=1, columnspan=2, sticky='NW') extra = Frame(self.__root).grid(row=20, column=0, rowspan=2, columnspan=8, sticky='NW') # Add Graph self.__fig = plt.Figure(dpi=100, figsize=(5, 3)) self.__fig.subplots_adjust(left=0.10, right=0.9, bottom=0.15, top=0.93) self.__ax = self.__fig.add_subplot(1, 1, 1, frameon=True) self.__ax.set(xlim=[0, 2400], ylim=[-3, 3]) self.__ax.set_xlabel('Time(s)') self.__axe = self.__ax.twinx() self.__axe.set_ylabel('Led Intensity', color='crimson') self.__axe.set(ylim=[0, 255]) self.chart = FigureCanvasTkAgg(self.__fig, self.__root) self.chart.get_tk_widget().grid(column=1, row=0, rowspan=9, columnspan=7, sticky='NEWS') self.toolbar = NavigationToolbar2Tk(self.chart, self.__toolbarFrame) self.toolbar.update() # Add variables self.__Var1 = BooleanVar(self.__root) self.__Var2 = BooleanVar(self.__root) self.__Var3 = BooleanVar(self.__root) self.__Var4 = BooleanVar(self.__root) self.__Var5 = BooleanVar(self.__root) self.__Var6 = BooleanVar(self.__root) # Add CheckButtons (widget) self.checkBtn() # self._bx = None # self._by = None # self._bz = None # self._red = None # self._green = None # self._blue = None # Add Table (widget) self.table() # Add Text (widget) self.text() # To open a already existing file self.__thisFileMenu.add_command(label="Open", command=self.__openFile) self.__thisFileMenu.add_command(label="Save As", command=self.__saveFile) self.__thisFileMenu.add_separator() self.__thisFileMenu.add_command(label="Exit", command=self.__exit) self.__thisMenuBar.add_cascade(label=" File ", menu=self.__thisFileMenu, underline=0) # To create a feature of description self.__thisHelpMenu.add_command(label="About", command=self.__showAbout) self.__thisMenuBar.add_cascade(label=" Help ", menu=self.__thisHelpMenu, underline=0) self.__root.config(menu=self.__thisMenuBar) self.config() self.__upg = Button(self.__root, text="Update Graph", padx=15, pady=5, font=("Arial", 10, "bold"), bg="black", fg="white", command=self.__update) self.__upg.grid(column=5, row=9, columnspan=2, sticky='NW') mag = Label(extra, text='MagOD Chef', font=("Arial", 3, "bold")).grid(column=8, sticky='S') self.x = None self.y = None self.y1 = None self.y2 = None self.y3 = None self.y4 = None self.y5 = None self.y6 = None """Function to create the seperation lines to indicate different recipes""" def v_lines(self): for i in self.y: self.__ax.axvline(self.x[i - 1], linestyle='-.', color='silver') # vertical lines """Function to create the graph and set axes""" def graph(self): self.__ax.set_xlabel('Time(s)') self.__axe.set_ylabel('Led Intensity', color='crimson') self.__ax.step(self.x, self.y1, color='black', linestyle='-', label='B_x (mT)', where='pre') self.__ax.step(self.x, self.y2, color='tomato', linestyle='--', label='B_y (mT)', where='pre') self.__ax.step(self.x, self.y3, color='chocolate', linestyle=':', label='B_z (mT)', where='pre') self.__axe.step(self.x, self.y4, color='red', linestyle='-', label='RED', where='pre') self.__axe.step(self.x, self.y5, color='green', linestyle='--', label='GREEN', where='pre') self.__axe.step(self.x, self.y6, color='blue', linestyle=':', label='BLUE', where='pre') self.__ax.set(ylim=[-3, 3]) self.__axe.set(ylim=[0, 255]) self.v_lines() self.__ax.legend(loc='best') self.__axe.legend(loc='lower right') self.chart.draw() """Function when the B_x checkbutton is pressed/cleared""" def ch_bx(self): self.check() self.v_lines() if (self.__Var1.get()): self.pt1, = self.__ax.step(self.x, self.y1, color='black', label='B_x (mT)', where='pre') self.chart.draw() else: self.pt1.set_xdata([0]) self.pt1.set_ydata([0]) self.chart.draw() """Function when the B_y checkbutton is pressed/cleared""" def ch_by(self): self.check() self.v_lines() if (self.__Var2.get()): self.pt2, = self.__ax.step(self.x, self.y2, color='tomato', linestyle='--', label='B_y (mT)', where='pre') self.chart.draw() else: self.pt2.set_xdata([0]) self.pt2.set_ydata([0]) self.chart.draw() """Function when the B_z checkbutton is pressed/cleared""" def ch_bz(self): self.check() self.v_lines() if (self.__Var3.get()): self.pt3, = self.__ax.step(self.x, self.y3, color='chocolate', linestyle=':', label='B_z (mT)', where='pre') self.chart.draw() else: self.pt3.set_xdata([0]) self.pt3.set_ydata([0]) self.chart.draw() """Function when the red checkbutton is pressed/cleared""" def ch_red(self): self.check() self.v_lines() if (self.__Var4.get()): self.pt4, = self.__axe.step(self.x, self.y4, color='red', label='RED', where='pre') self.chart.draw() else: self.pt4.set_xdata([0]) self.pt4.set_ydata([0]) self.chart.draw() """Function when the green checkbutton is pressed/cleared""" def ch_green(self): self.check() self.v_lines() if (self.__Var5.get()): self.pt5, = self.__axe.step(self.x, self.y5, color='green', linestyle='--', label='GREEN', where='pre') self.chart.draw() else: self.pt5.set_xdata([0]) self.pt5.set_ydata([0]) self.chart.draw() """Function when the blue checkbutton is pressed/cleared""" def ch_blue(self): self.check() self.v_lines() if (self.__Var6.get()): self.pt6, = self.__axe.step(self.x, self.y6, color='blue', linestyle=':', label='BLUE', where='pre') self.chart.draw() else: self.pt6.set_xdata([0]) self.pt6.set_ydata([0]) self.chart.draw() """Function to create the axes when cleared""" def check(self): if ((self.__Var1.get() or self.__Var2.get() or self.__Var3.get() or self.__Var4.get() or self.__Var5.get() or self.__Var6.get()) and self.count): self.count = False self.__ax.cla() self.__axe.cla() self.__ax.set_xlabel('Time(s)') self.__axe.set_ylabel('Led Intensity', color='crimson') self.__ax.set(ylim=[-3, 3]) self.__axe.set(ylim=[0, 255]) """Function to create the checkbuttons and their placements""" def checkBtn(self): _bx = Checkbutton(self.__checkFrame1, text="Bx", padx=5, pady=5, variable=self.__Var1, fg="black", font=("Arial", 10, "bold"), command=self.ch_bx).grid(row=0, sticky='N') _by = Checkbutton(self.__checkFrame1, text="By", padx=5, pady=5, variable=self.__Var2, fg="tomato", font=("Arial", 10, "bold"), command=self.ch_by).grid(row=1, sticky='N') _bz = Checkbutton(self.__checkFrame1, text="Bz", padx=5, pady=5, variable=self.__Var3, fg="saddle brown", font=("Arial", 10, "bold"), command=self.ch_bz).grid(row=2, sticky='N') _red = Checkbutton(self.__checkFrame2, text=" RED ", padx=5, pady=5, variable=self.__Var4, fg="red", font=("Arial", 10, "bold"), command=self.ch_red) _red.grid(column=8, row=0, sticky='N') _green = Checkbutton(self.__checkFrame2, text="GREEN", padx=5, variable=self.__Var5, fg="green", font=("Arial", 10, "bold"), command=self.ch_green) _green.grid(column=8, row=1, sticky='N') _blue = Checkbutton(self.__checkFrame2, text=" BLUE ", padx=5, pady=5, variable=self.__Var6, fg="blue", font=("Arial", 10, "bold"), command=self.ch_blue) _blue.grid(column=8, row=2, sticky='N') """Function to the create the table""" def table(self): mod = TableModel(rows=30, columns=6) # to create a table of 30*6 self.__table = pt = TableCanvas(self.__tableFrame, model=mod) pt.show() """Function for the text widget and the clear button""" def text(self): self.__text = Text(self.__root, height=2, width=70, xscrollcommand=set(), yscrollcommand=set()) self.__text.grid(column=1, row=18, columnspan=4, sticky='NW') self.__cls = Button(self.__root, text="Clear", padx=15, pady=5, font=("Arial", 10, "bold"), bg="black", fg="white", command=self.__clr) self.__cls.grid(column=7, row=18, columnspan=2, sticky='NW') """Configuration of the window for minimize/maximize function""" def config(self): self.__root.grid_columnconfigure(3, weight=1) self.__root.grid_columnconfigure(5, weight=1) self.__root.grid_columnconfigure(7, weight=1) self.__root.grid_rowconfigure(10, weight=1) self.__root.grid_rowconfigure(13, weight=1) self.__root.grid_rowconfigure(15, weight=1) def __clr(self): self.__text.delete(1.0, END) self.clear_table() def __showAbout(self): showinfo("MagOD Chef", "Version 2.0") def __exit(self): self.__root.quit() self.__root.destroy() """Function for opening the csv file""" def __openFile(self): self.__file = askopenfilename(defaultextension=".csv", filetypes=[("CSV Files", "*.csv"), ("All Files", "*.*")]) fname = os.path.basename(self.__file) #print(self.__file) if self.__file == "": # no file to open self.__file = None else: # opening the file self.__root.title(os.path.basename(self.__file)) self.clear_table() self.__ax.cla() self.__axe.cla() self.count = True try: w = subprocess.Popen(['TestRecipes', '-o', fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) except AttributeError: w = subprocess.Popen(['./TestRecipes -o', fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, errors = w.communicate() self.__text.insert(END, output) self.__table.importCSV("temp.csv") model = self.__table.model model.deleteColumn(0) v0 = list( map( int, model.getColumnData(0, filters=[('Recipe Number', '', 'contains', '')]))) model.deleteColumns([0, 6, 6, 6]) self.__table.redraw() f = self.freq_count(v0) self.y = self.value_gen(f, 1) self.y1 = list( map( float, model.getColumnData(0, filters=[('B x', '', 'contains', '') ]))) self.y2 = list( map( float, model.getColumnData(1, filters=[('B y', '', 'contains', '') ]))) self.y3 = list( map( float, model.getColumnData(2, filters=[('B z', '', 'contains', '') ]))) v4 = list( map( int, model.getColumnData(3, filters=[('Led Time', '', 'contains', '')]))) v5 = model.getColumnData(4, filters=[('Led Color', '', 'contains', '') ]) v6 = list( map( int, model.getColumnData(5, filters=[('Led Intensity', '', 'contains', '')]))) self.y4, self.y5, self.y6 = self.led_val(v5, v6) self.x = self.value_gen(v4, 1000) # converting milli_s -> seconds self.graph_init() self.graph() """To start the graph from (0,0)""" def graph_init(self): self.y1.insert(0, 0) self.y2.insert(0, 0) self.y3.insert(0, 0) self.y4.insert(0, 0) self.y5.insert(0, 0) self.y6.insert(0, 0) self.x.insert(0, 0) """Update the graph when table is updated""" def toggle(self): self.__ax.cla() self.__axe.cla() self.count = True if (self.__Var1.get()): self.ch_bx() if (self.__Var2.get()): self.ch_by() if (self.__Var3.get()): self.ch_bz() if (self.__Var4.get()): self.ch_red() if (self.__Var5.get()): self.ch_green() if (self.__Var6.get()): self.ch_blue() """Function to update the list when elements in table are updated""" def __update(self): mod = self.__table.model self.y1 = list( map(float, mod.getColumnData(0, filters=[('B x', '', 'contains', '')]))) self.y2 = list( map(float, mod.getColumnData(1, filters=[('B y', '', 'contains', '')]))) self.y3 = list( map(float, mod.getColumnData(2, filters=[('B z', '', 'contains', '')]))) v4 = list( map( int, mod.getColumnData(3, filters=[('Led Time', '', 'contains', '')]))) v5 = mod.getColumnData(4, filters=[('Led Color', '', 'contains', '')]) v6 = list( map( int, mod.getColumnData(5, filters=[('Led Intensity', '', 'contains', '')]))) self.y4, self.y5, self.y6 = self.led_val(v5, v6) self.x = self.value_gen(v4, 1000) # converting milli_s -> seconds self.toggle() """Function to convert milli-seconds to seconds""" def value_gen(self, a, b): val = [0] * len(a) for i, j in enumerate(a): val[i] = val[i - 1] + int(j / b) return val """Function to clear the contents and redraw the table""" def clear_table(self): mod = self.__table.model r = list(i for i in range(mod.getRowCount())) c = list(i for i in range(mod.getColumnCount())) self.__table.multiplerowlist = r self.__table.multiplecollist = c self.__table.clearData() self.__table.redraw() """ Function to count the number of recipes. It returns the list to draw seperations on the graph""" def freq_count(self, vv): freq = {} for i in vv: freq[i] = vv.count(i) a = list(freq.values()) return a """Function to convert the LED Color to integers""" def led_val(self, val, _int): _green = [0] * len(val) _red = [0] * len(val) _blue = [0] * len(val) for i, j in enumerate(val): if (j == ' GREEN'): _green[i] = _int[i] elif (j == ' RED'): _red[i] = _int[i] elif (j == ' BLUE'): _blue[i] = _int[i] else: _green[i] = 0 _red[i] = 0 _blue[i] = 0 return _red, _green, _blue """Function to save file""" def __saveFile(self): if self.__sfile == None: # Save as new file self.__sfile = asksaveasfilename(initialfile='Untitled.csv', defaultextension=".csv", filetypes=[("CSV Files", "*.csv"), ("All Files", "*.*")]) if self.__sfile == "": self.__sfile = None else: # Try to save the file self.__table.exportTable(self.__sfile) # Change the window title self.__root.title(os.path.basename(self.__sfile)) def execute(self): # Run main application self.__root.mainloop()
def __init__(self, **kwargs): try: self.__thisWidth = kwargs['w'] except KeyError: pass try: self.__thisHeight = kwargs['h'] except KeyError: pass # Set the window text self.__root.title("MagOD Chef") # Center the window screenWidth = self.__root.winfo_screenwidth() screenHeight = self.__root.winfo_screenheight() # For left-allignment left = (screenWidth / 2) - (self.__thisWidth / 2) # For right-allignment right = (screenHeight / 2) - (self.__thisHeight / 2) # For top and bottom self.__root.geometry( '%dx%d+%d+%d' % (self.__thisWidth, self.__thisHeight, left, right)) self.__root.resizable(1, 1) self.__root.grid() # Add Frame self.__checkFrame1 = Frame(self.__root).grid(row=0, column=0, sticky='NEWS') self.__checkFrame2 = Frame(self.__root).grid(row=0, column=8, sticky='NEWS') self.__tableFrame = Frame(self.__root) self.__tableFrame.grid(column=1, row=10, columnspan=7, rowspan=6, sticky='NEWS') self.__toolbarFrame = Frame(self.__root) self.__toolbarFrame.grid(column=1, row=9, rowspan=1, columnspan=2, sticky='NW') extra = Frame(self.__root).grid(row=20, column=0, rowspan=2, columnspan=8, sticky='NW') # Add Graph self.__fig = plt.Figure(dpi=100, figsize=(5, 3)) self.__fig.subplots_adjust(left=0.10, right=0.9, bottom=0.15, top=0.93) self.__ax = self.__fig.add_subplot(1, 1, 1, frameon=True) self.__ax.set(xlim=[0, 2400], ylim=[-3, 3]) self.__ax.set_xlabel('Time(s)') self.__axe = self.__ax.twinx() self.__axe.set_ylabel('Led Intensity', color='crimson') self.__axe.set(ylim=[0, 255]) self.chart = FigureCanvasTkAgg(self.__fig, self.__root) self.chart.get_tk_widget().grid(column=1, row=0, rowspan=9, columnspan=7, sticky='NEWS') self.toolbar = NavigationToolbar2Tk(self.chart, self.__toolbarFrame) self.toolbar.update() # Add variables self.__Var1 = BooleanVar(self.__root) self.__Var2 = BooleanVar(self.__root) self.__Var3 = BooleanVar(self.__root) self.__Var4 = BooleanVar(self.__root) self.__Var5 = BooleanVar(self.__root) self.__Var6 = BooleanVar(self.__root) # Add CheckButtons (widget) self.checkBtn() # self._bx = None # self._by = None # self._bz = None # self._red = None # self._green = None # self._blue = None # Add Table (widget) self.table() # Add Text (widget) self.text() # To open a already existing file self.__thisFileMenu.add_command(label="Open", command=self.__openFile) self.__thisFileMenu.add_command(label="Save As", command=self.__saveFile) self.__thisFileMenu.add_separator() self.__thisFileMenu.add_command(label="Exit", command=self.__exit) self.__thisMenuBar.add_cascade(label=" File ", menu=self.__thisFileMenu, underline=0) # To create a feature of description self.__thisHelpMenu.add_command(label="About", command=self.__showAbout) self.__thisMenuBar.add_cascade(label=" Help ", menu=self.__thisHelpMenu, underline=0) self.__root.config(menu=self.__thisMenuBar) self.config() self.__upg = Button(self.__root, text="Update Graph", padx=15, pady=5, font=("Arial", 10, "bold"), bg="black", fg="white", command=self.__update) self.__upg.grid(column=5, row=9, columnspan=2, sticky='NW') mag = Label(extra, text='MagOD Chef', font=("Arial", 3, "bold")).grid(column=8, sticky='S') self.x = None self.y = None self.y1 = None self.y2 = None self.y3 = None self.y4 = None self.y5 = None self.y6 = None
25, 34, 22, 27, 33, 33, 31, 22, 35, 34, 67, 54, 57, 43, 50, 57, 59, 52, 65, 47, 49, 48, 35, 33, 44, 45, 38, 43, 51, 46 ], 'y': [ 79, 51, 53, 78, 59, 74, 73, 57, 69, 75, 51, 32, 40, 47, 53, 36, 35, 58, 59, 50, 25, 20, 14, 12, 20, 5, 29, 27, 8, 7 ] } df = DataFrame(Data, columns=['x', 'y']) kmeans = KMeans(n_clusters=3).fit(df) centroids = kmeans.cluster_centers_ root = tk.Tk() canvas1 = tk.Canvas(root, width=100, height=100) canvas1.pack() label1 = tk.Label(root, text=centroids, justify='center') canvas1.create_window(70, 50, window=label1) figure1 = plt.Figure(figsize=(5, 4), dpi=100) ax1 = figure1.add_subplot(111) ax1.scatter(df['x'], df['y'], c=kmeans.labels_.astype(float), s=50, alpha=0.5) ax1.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50) scatter1 = FigureCanvasTkAgg(figure1, root) scatter1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH) root.mainloop()
def values(): global New_Market_Cap #our 1st input variable New_Market_Cap = float(entry1.get()) global New_PB #our 2nd input variable New_PB = float(entry2.get()) Prediction_result = ('Predict Stock Price: ', regr.predict([[New_Market_Cap ,New_PB]])) label_Prediction = tk.Label(root, text= Prediction_result, bg='orange') canvas1.create_window(260, 280, window=label_Prediction) button1 = tk.Button (root, text='Predict Stock Price',command=values, bg='orange') # button to call the 'values' command above canvas1.create_window(270, 150, window=button1) #plot 1st scatter figure3 = plt.Figure(figsize=(5,4), dpi=100) ax3 = figure3.add_subplot(111) ax3.scatter(df['MARKETCAP'].astype(float),df['PRICE'].astype(float), color = 'r') scatter3 = FigureCanvasTkAgg(figure3, root) scatter3.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH) ax3.legend(['PRICE']) ax3.set_xlabel('MARKETCAP') ax3.set_title('MARKETCAP Vs. Stock Price') #plot 2nd scatter figure4 = plt.Figure(figsize=(5,4), dpi=100) ax4 = figure4.add_subplot(111) ax4.scatter(df['PB'].astype(float),df['PRICE'].astype(float), color = 'g') scatter4 = FigureCanvasTkAgg(figure4, root) scatter4.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
def oscillator_nw(position_vector, max_time=10.0, fitness_option=6, plot = False, log_dis = False, render = False, monitor_path=None, save_plot_path = None, env_name=None ): if log_dis: log.infov('[OSC]-------------------------------------------------------------') log.infov('[OSC] Run in multiprocessing({})'.format(os.getpid())) log.infov('[OSC] Running oscillator_2.oscillator_nw') log.info('[OSC] Printing chromosome') log.info('[OSC] {0}'.format(position_vector)) log.info('[OSC] Started monitoring thread') # Start the monitoring thread # Start the monitoring thread if env_name is None: env = gym.make('CellrobotBigSnakeEnv-v0') else: env = gym.make(env_name) CPG_node_num =16 # For plots - not needed now if plot: o1_list = list() o2_list = list() o3_list = list() o4_list = list() o5_list = list() o6_list = list() o7_list = list() o8_list = list() o9_list = list() end_pos_x_list = list() end_pos_y_list = list() end_pos_z_list = list() t_list = list() CPG_controller = CPG_network_2gb(CPG_node_num, position_vector) # Set monitor thread monitor_thread = RobotMonitorThread(env, render, monitor_path=monitor_path) # Set robot API robot_handle = CRbot(env, monitor_thread, sync_sleep_time=0.01, interpolation=False, fraction_max_speed=0.01, wait=False, ) # Note the current position start_pos_x = monitor_thread.x start_pos_y = monitor_thread.y start_pos_z = monitor_thread.z # Start the monitoring thread monitor_thread.start() # Set init angles # robot_handle.set_angles_slow(target_angles=initial_bias_angles, duration=2.0, step=0.01) # Sleep for 2 seconds to let any oscillations to die down #time.sleep(2.0) # Reset the timer of the monitor monitor_thread.reset_timer() # New variable for logging up time, since monitor thread is not accurate some times up_t = 0.0 dt =0.01 for t in np.arange(0.0, max_time, dt): # Increment the up time variable up_t = t output_list = CPG_controller.output(state=None) # Set the joint positions current_angles = {'cell0': output_list[1], 'cell1': output_list[2], 'cell2': output_list[3], 'cell3': output_list[4], 'cell4': output_list[5], 'cell5': output_list[6], 'cell6': output_list[7], 'cell7': output_list[8], 'cell8': output_list[9], 'cell9': output_list[10], 'cell10': output_list[11], 'cell11': output_list[12], 'cell12': output_list[13], 'cell13': output_list[14], 'cell14': output_list[15], 'cell15': output_list[16] } robot_handle.set_angles(current_angles) time.sleep(dt) # Check if the robot has fallen if monitor_thread.fallen: break # For plots - not needed now if plot: o1_list.append(output_list[1]) o2_list.append(output_list[2]) o3_list.append(output_list[3]) o4_list.append(output_list[4]) o5_list.append(output_list[5]) o6_list.append(output_list[6]) o7_list.append(output_list[7]) o8_list.append(output_list[8]) o9_list.append(output_list[9]) end_pos_x_list.append(monitor_thread.x) end_pos_y_list.append(monitor_thread.y) end_pos_z_list.append(monitor_thread.z) t_list.append(t) if log_dis: log.info('[OSC] Accurate up time: {0}'.format(up_t)) # Outside the loop, it means that either the robot has fallen or the max_time has elapsed # Find out the end position of the robot end_pos_x = monitor_thread.x end_pos_y = monitor_thread.y end_pos_z = monitor_thread.z # Find the average height avg_z = monitor_thread.avg_z # Find the up time # up_time = monitor_thread.up_time up_time = up_t # Calculate the fitness if up_time == 0.0: fitness = 0.0 if log_dis: log('[OSC] up_t==0 so fitness is set to 0.0') else: fitness = calc_fitness(start_x=start_pos_x, start_y=start_pos_y, start_z=start_pos_z, end_x=end_pos_x, end_y=end_pos_y, end_z=end_pos_z, avg_z=avg_z, up_time=up_time, fitness_option=fitness_option ) if log_dis: if not monitor_thread.fallen: log.info("[OSC] Robot has not fallen") else: log.info("[OSC] Robot has fallen") log.info('[OSC] Calculated fitness: {0}'.format(fitness)) # Different from original script # Fetch the values of the evaluation metrics fallen = monitor_thread.fallen up = up_time # Using a more accurate up time than monitor_thread.up_time, x_distance = end_pos_x - start_pos_x abs_y_deviation = end_pos_y avg_footstep_x = None var_torso_alpha = monitor_thread.obs[3] var_torso_beta = monitor_thread.obs[4] var_torso_gamma = monitor_thread.obs[5] # Stop the monitoring thread monitor_thread.stop() # Close the VREP connection robot_handle.cleanup() # For plots - not needed now if plot: ax1 = plt.subplot(611) plt.plot(t_list, o1_list, color='red', label='o_1') plt.plot(t_list, o2_list, color='green', ls='--', label='o_2') plt.plot(t_list, o3_list, color='green', label='o_3') plt.grid() plt.legend() ax2 = plt.subplot(612, sharex=ax1, sharey=ax1) plt.plot(t_list, o1_list, color='red', label='o_1') plt.plot(t_list, o4_list, color='blue', ls='--', label='o_4') plt.plot(t_list, o5_list, color='blue', label='o_5') plt.grid() plt.legend() ax3 = plt.subplot(613, sharex=ax1, sharey=ax1) plt.plot(t_list, o1_list, color='red', label='o_1') plt.plot(t_list, o6_list, color='black', ls='--', label='o_6') plt.plot(t_list, o7_list, color='black', label='o_7') plt.grid() plt.legend() ax4 = plt.subplot(614, sharex=ax1, sharey=ax1) plt.plot(t_list, o1_list, color='red', label='o_1') plt.plot(t_list, o8_list, color='cyan', ls='--', label='o_8') plt.plot(t_list, o9_list, color='cyan', label='o_9') plt.grid() plt.legend() if save_plot_path is not None: plt.savefig(save_plot_path+'/fig1.jpg') else: plt.show() plt.Figure(figsize=(15, 10)) ax1 = plt.subplot(311) plt.plot(t_list, end_pos_x_list, color='red', label='x') plt.grid() plt.legend() ax2 = plt.subplot(312, sharex=ax1, sharey=ax1) plt.plot(t_list, end_pos_y_list, color='red', label='y') plt.grid() plt.legend() ax3 = plt.subplot(313, sharex=ax1, sharey=ax1) plt.plot(t_list, end_pos_z_list, color='red', label='z') plt.grid() plt.legend() if save_plot_path is not None: plt.savefig(save_plot_path+'/fig1.jpg') else: plt.show() # Different from original script # Return the evaluation metrics return {'fitness': fitness, 'fallen': fallen, 'up': up, 'x_distance': x_distance, 'abs_y_deviation': abs_y_deviation, 'avg_footstep_x': avg_footstep_x, 'var_torso_alpha': var_torso_alpha, 'var_torso_beta': var_torso_beta, 'var_torso_gamma': var_torso_gamma} #return fitness # # # # # position_vector = np.zeros(33) # position_vector[0]=1 # for i in range(1,17): # position_vector[i] =0.3 # # print(position_vector) # # oscillator_nw(position_vector, plot=True,render=True, monitor_path=None, #'/home/drl/PycharmProjects/DeployedProjects/CR_CPG/tmp/tmp2.mp4' # save_plot_path=None) #'/home/drl/PycharmProjects/DeployedProjects/CR_CPG/tmp/tmp.mp4'
def plot_analytic_envelop_frequency(self): # get the left and right Analytic signal and envelop from hilbert_transform() left_analytic_signal, left_envelop, left_phase, left_instant_freq = self.left_hilbert_transform( ) right_analytic_signal, right_envelop, right_phase, right_instant_freq = self.right_hilbert_transform( ) # get the envelop filter from left_envelop_butterworth() and right_envelop_butterworth() left_envelop_filter = self.left_envelop_butterworth() right_envelop_filter = self.right_envelop_butterworth() left_instant_freq = left_instant_freq / 200000 right_instant_freq = right_instant_freq / 200000 left_freq_filter = self.left_frequency_butterworth() left_freq_filter = left_freq_filter / 200000 # divide the instant freq by 200kH right_freq_filter = self.right_frequency_butterworth() right_freq_filter = right_freq_filter / 200000 self.root4.title( 'Analytic Signal, Envelop, Instantaneous Frequency, Envelop Filter and Instant Frequency Filter' ) frame1 = Frame(self.root4) frame2 = Frame(self.root4) fig1 = plt.Figure(dpi=100) ax1 = fig1.add_subplot(111) ax1.plot(self.time, left_analytic_signal, label='signal') # left analytic signal ax1.plot(self.time, left_envelop, label='envelop') # left envelop ax1.plot(self.time[1:], left_instant_freq, label='Instantaneous frequency') ax1.plot(self.time, left_envelop_filter, label='envelop filter') ax1.plot(self.time[1:], left_freq_filter, label='frequency filter') ax1.set_xlabel('Times(sec)') ax1.set_ylabel('Amplitude(V)') ax1.grid() ax1.set_title( 'Left Signal,Envelop,Instantaneous freq,envelop and instant freq filter' ) canvas1 = FigureCanvasTkAgg(fig1, frame1) canvas1.draw() canvas1.get_tk_widget().pack(fill=BOTH, expand=True) tool1 = NavigationToolbar2Tk(canvas1, frame1) tool1.update() tool1.pack() fig1.legend() plt.tight_layout() fig2 = plt.Figure(dpi=100) ax2 = fig2.add_subplot(111) ax2.plot(self.time, right_analytic_signal, label='signal') # right analytic signal ax2.plot(self.time, right_envelop, label='envelop') # right envelop ax2.plot(self.time[1:], right_instant_freq, label='Instantaneous frequency') ax2.plot(self.time, right_envelop_filter, label='envelop filter ') ax2.plot(self.time[1:], right_freq_filter, label='frequency filter ') ax2.set_xlabel('Times(sec)') ax2.set_ylabel('Amplitude(V)') ax2.grid() ax2.set_title( 'Right Signal,Envelop,Instantaneous freq,envelop and instant freq filter' ) canvas2 = FigureCanvasTkAgg(fig2, frame2) canvas2.draw() canvas2.get_tk_widget().pack(fill=BOTH, expand=True) tool2 = NavigationToolbar2Tk(canvas2, frame2) tool2.update() tool2.pack() fig2.legend() plt.tight_layout() frame1.pack(side=LEFT) frame2.pack(side=RIGHT)
def __init__(self, file_data, initialslice=0, scan_dir=0, color_map='hot', font_size=18, font_weight='bold'): self.file_data = file_data # Create a matplotlib Figure to populate with cits image and colour bar. self.cits_window = plt.Figure() # Add a subplot to take the cits image self.cits_image = self.cits_window.add_subplot(111) # Extract the cits info from the data self.cits_info = extract_cits_info(file_data) self.x_extent = self.cits_info['xres'] * self.cits_info['xinc'] self.y_extent = self.cits_info['yres'] * self.cits_info['yinc'] self.v_start = self.cits_info['vstart'] self.v_inc = self.cits_info['vinc'] self.v_res = self.cits_info['vres'] self.v_end = self.v_start + (self.v_res * self.v_inc) self.v_range = np.arange(self.v_start, self.v_start + (self.v_res * self.v_inc), self.v_inc) self.v_len = len(self.v_range) # Extract the x,y,z data fom the file_data self.cits_data = extract_cits_data(file_data) # Produce the initial 2D CITS plot at the initial voltage self.cits_image_cbarCall = self.cits_image.imshow( self.cits_data[scan_dir][initialslice], origin='lower', extent=[0, self.x_extent, 0, self.y_extent], cmap=color_map, interpolation='none') self.cbar = self.cits_window.colorbar(self.cits_image_cbarCall) self.cits_image.set_xlabel(self.cits_info['unitxy'], fontsize=font_size, fontweight=font_weight) self.cits_image.set_ylabel(self.cits_info['unitxy'], fontsize=font_size, fontweight=font_weight) self.cits_image.set_title( str(np.round(self.v_range[initialslice], decimals=3)) + self.cits_info['unitv']) self.cbar.set_label(self.cits_info['unitv'], fontsize=font_size, fontweight=font_weight) # Construct a Tkinter window to place CITS plot and other components self.cits_viewer = Tkinter.Tk() self.cits_canvas = FigureCanvasTkAgg(self.cits_window, master=self.cits_viewer) self.cits_canvas.get_tk_widget().grid(column=0, row=1, columnspan=3) self.cid = self.cits_canvas.mpl_connect('button_press_event', self.mouse_click) # Label of the data filename self.data_label = Tkinter.Label(self.cits_viewer, text='None', bg='blue', fg='white') self.data_label.configure(text=self.cits_info['filename']) self.data_label.grid(column=0, row=0, columnspan=3, sticky='EW') # A slider (Tkinter.Scale) that controls the voltage slice currently shown self.cits_slider = Tkinter.Scale(master=self.cits_viewer, from_=0, to=self.v_len - 1, orient=Tkinter.HORIZONTAL, command=self.return_slider_val, length=250) self.cits_slider.grid(column=0, row=2, columnspan=3, sticky='S') # Button to extract a point spectra from the CITS data self.cits_pointspec_button = Tkinter.Button( master=self.cits_viewer, text=u'Extract Point Spectrum', command=self.extract_pointspectrum) self.cits_pointspec_button.grid(column=0, row=3, sticky='W') # Label showing currently selected pixel self.x_loc = 0 self.y_loc = 0 self.cits_pointspec_label = Tkinter.Label(self.cits_viewer, text='None', bg='white', fg='black') self.cits_pointspec_label.configure(text='x: ' + str(self.x_loc) + ' y: ' + str(self.y_loc)) self.cits_pointspec_label.grid(column=0, row=3, sticky='E') # Save currently displayed CITS energy slice self.cits_save_button = Tkinter.Button(master=self.cits_viewer, text=u'Save CITS', command=self.save_button) self.cits_save_button.grid(column=0, row=4, sticky='W') # Cleanly exit the CITS viewer self.cits_quit_button = Tkinter.Button(master=self.cits_viewer, text=u'Close CITS', command=self.quit_button) self.cits_quit_button.grid(column=2, row=4, sticky='E') # Define Window Geometry self.screen_w = self.cits_viewer.winfo_screenwidth() self.screen_h = self.cits_viewer.winfo_screenheight() self.cits_viewer.grid_columnconfigure(0, weight=1) self.cits_viewer.resizable(True, True) self.cits_viewer.geometry('%dx%d+%d+%d' % (0.41 * self.screen_w, 0.69 * self.screen_h, 0.05 * self.screen_w, 0.05 * self.screen_h)) self.cits_viewer.update_idletasks() self.cits_canvas.show() self.is_rectangle = 0 # Run cits_viewer Tk.mainloop(self.cits_viewer)
def __init__(self, frame): figure_fragment = plt.Figure(figsize=(3, 3), dpi=100) self._ax = figure_fragment.add_subplot(111) self._canvas = FigureCanvasTkAgg(figure_fragment, frame) self._canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH) self._data = None
def render(self, mode='human'): screen_width = 1000 screen_height = 450 clearance_x = 80 clearance_y = 10 zero_x = 0.25 * screen_width visible_track_length = 1000 scale_x = screen_width / visible_track_length if self.viewer is None: import matplotlib.pyplot as plt import seaborn as sns from gym_longicontrol.envs import rendering self.viewer = rendering.Viewer(width=screen_width, height=screen_height) rel_dir = os.path.join(os.path.dirname(__file__), 'assets/track/img') # start and finish line fname = os.path.join(rel_dir, 'start_finish_30x100.png') start = rendering.Image(fname, rel_anchor_y=0, batch=self.viewer.batch, group=self.viewer.background) start.position = (zero_x, clearance_y) self.viewer.components['start'] = start finish = rendering.Image(fname, rel_anchor_y=0, batch=self.viewer.batch, group=self.viewer.background) finish.position = (zero_x + scale_x * self.track_length, clearance_y) self.viewer.components['finish'] = finish self.viewer.components['signs'] = [] # speedometer fname = os.path.join(rel_dir, 'speedometer_232x190.png') speedometer = rendering.Image(fname, rel_anchor_y=0, batch=self.viewer.batch, group=self.viewer.background) speedometer.position = (screen_width - 110 - clearance_x, 220 + clearance_y) self.viewer.components['speedometer'] = speedometer fname = os.path.join(rel_dir, 'needle_6x60.png') needle = rendering.Image(fname, rel_anchor_y=0.99, batch=self.viewer.batch, group=self.viewer.foreground) needle.position = (screen_width - 110 - clearance_x, 308 + clearance_y) self.viewer.components['needle'] = needle fname = os.path.join(rel_dir, 'needle_6x30.png') needle_sl = rendering.Image(fname, rel_anchor_y=2.6, batch=self.viewer.batch, group=self.viewer.background) needle_sl.position = (screen_width - 110 - clearance_x, 308 + clearance_y) self.viewer.components['needle_sl'] = needle_sl # info label velocity0_label = rendering.Label(text='km/h', batch=self.viewer.batch, group=self.viewer.foreground, anchor_x='left', font_size=12, color=(255, 255, 255, 255)) velocity0_label.position = (screen_width - 110 - clearance_x, 267 + clearance_y) self.viewer.components['velocity0_label'] = velocity0_label energy0_label = rendering.Label(text='kWh', batch=self.viewer.batch, group=self.viewer.foreground, anchor_x='left', font_size=12, color=(255, 255, 255, 255)) energy0_label.position = (screen_width - 155 - clearance_x, 238 + clearance_y) self.viewer.components['energy0_label'] = energy0_label time0_label = rendering.Label(text='min', batch=self.viewer.batch, group=self.viewer.foreground, anchor_x='left', font_size=12, color=(255, 255, 255, 255)) time0_label.position = (screen_width - 49 - clearance_x, 238 + clearance_y) self.viewer.components['time0_label'] = time0_label velocity_label = rendering.Label(text=str(int(self.velocity * 3.6)), batch=self.viewer.batch, group=self.viewer.foreground, anchor_x='left', font_size=12, color=(255, 255, 255, 255)) velocity_label.position = (screen_width - 150 - clearance_x, 267 + clearance_y) self.viewer.components['velocity_label'] = velocity_label energy_label = rendering.Label(text=str( round(self.total_energy_kWh, 2)), batch=self.viewer.batch, group=self.viewer.foreground, anchor_x='left', font_size=12, color=(255, 255, 255, 255)) energy_label.position = (screen_width - 200 - clearance_x, 238 + clearance_y) self.viewer.components['energy_label'] = energy_label m, s = divmod(self.time, 60) time_label = rendering.Label(text=f'{m:02.0f}:{s:02.0f}', batch=self.viewer.batch, group=self.viewer.foreground, anchor_x='left', font_size=12, color=(255, 255, 255, 255)) time_label.position = (screen_width - 99 - clearance_x, 238 + clearance_y) self.viewer.components['time_label'] = time_label # info figures self.viewer.history['velocity'] = [] self.viewer.history['speed_limit'] = [] self.viewer.history['position'] = [] self.viewer.history['acceleration'] = [] sns.set_style('whitegrid') self.fig = plt.Figure((640 / 80, 200 / 80), dpi=80) info = rendering.Figure(self.fig, rel_anchor_x=0, rel_anchor_y=0, batch=self.viewer.batch, group=self.viewer.background) info.position = (clearance_x - 40, 225 + clearance_y) self.viewer.components['info'] = info # car fname = os.path.join(rel_dir, 'car_80x40.png') car = rendering.Image(fname, rel_anchor_x=1, batch=self.viewer.batch, group=self.viewer.foreground) car.position = (zero_x, 50 + clearance_y) self.viewer.components['car'] = car # speed limit signs if not self.viewer.components['signs']: from gym_longicontrol.envs import rendering rel_dir = os.path.join(os.path.dirname(__file__), 'assets/track/img') for sl, slp in zip(self.speed_limits[1:], self.speed_limit_positions[1:]): fname = os.path.join(rel_dir, f'sign_60x94_{str(int(sl * 3.6))}.png') sign = rendering.Image(fname, rel_anchor_y=0, batch=self.viewer.batch, group=self.viewer.background) sign.position = (zero_x + scale_x * (slp - self.position), 100 + clearance_y) self.viewer.components['signs'].append(sign) # updates for sl, slp, sign in zip(self.speed_limits[1:], self.speed_limit_positions[1:], self.viewer.components['signs']): distance = slp - self.position if distance >= self.sensor_range: sign.opacity = 64 else: sign.opacity = 255 if -zero_x - 50 <= scale_x * distance <= screen_width - zero_x + 50: sign.position = (zero_x + scale_x * distance, 100 + clearance_y) sign.visible = True else: sign.visible = False self.viewer.components['start'].position = (zero_x + scale_x * (0 - self.position), clearance_y) self.viewer.components['finish'].position = ( zero_x + scale_x * (self.track_length - self.position), clearance_y) # car turns red if speed limit is exceeded if self.velocity > self.current_speed_limit: self.viewer.components['car'].color = (128, 0, 0) else: self.viewer.components['car'].color = (255, 255, 255) # speedometer deg = 60.0 + self.current_speed_limit * 3.6 * 1.5 # 1km/h =^ 1.5° self.viewer.components['needle_sl'].rotation = deg deg = 60.0 + self.velocity * 3.6 * 1.5 # 1km/h =^ 1.5° self.viewer.components['needle'].rotation = deg self.viewer.components['velocity_label'].text = str( int(self.velocity * 3.6)) self.viewer.components['energy_label'].text = str( round(self.total_energy_kWh, 2)) m, s = divmod(self.time, 60) self.viewer.components['time_label'].text = f'{m:02.0f}:{s:02.0f}' # info figures self.viewer.history['velocity'].append(self.velocity * 3.6) self.viewer.history['speed_limit'].append(self.current_speed_limit * 3.6) self.viewer.history['position'].append(self.position) self.viewer.history['acceleration'].append(self.acceleration) self.viewer.components['info'].visible = False if self.viewer.plot_fig or mode == 'rgb_array': self.viewer.components['info'].visible = True self.fig.clf() ax = self.fig.add_subplot(121) ax.plot(self.viewer.history['position'], self.viewer.history['velocity'], lw=2, color='k') ax.plot(self.viewer.history['position'], self.viewer.history['speed_limit'], lw=1.5, ls='--', color='r') ax.set_xlabel('Position in m') ax.set_ylabel('Velocity in km/h') ax.set_xlim( (0.0, max(500, self.position + (500 - self.position) % 500))) ax.set_ylim((0.0, 130)) ax2 = self.fig.add_subplot(122) ax2.plot(self.viewer.history['position'], self.viewer.history['acceleration'], lw=2, color='k') ax2.set_xlabel('Position in m') ax2.set_ylabel('Acceleration in m/s²') ax2.set_xlim( (0.0, max(500, self.position + (500 - self.position) % 500))) ax2.set_ylim((-5.0, 5.0)) self.fig.tight_layout() self.viewer.components['info'].figure = self.fig return self.viewer.render(return_rgb_array=mode == 'rgb_array')
def eeg_like(backup, fig_name): os.makedirs(os.path.dirname(fig_name), exist_ok=True) pst = backup.positions prc = backup.prices t_max = backup.parameters.t_max t = np.arange(1, t_max) position_max = backup.parameters.n_positions - 1 position_A = pst[1:t_max, 0] / position_max position_B = pst[1:t_max, 1] / position_max price_A = prc[1:t_max, 0] price_B = prc[1:t_max, 1] color_A = "orange" color_B = "blue" price_min = backup.parameters.p_min price_max = backup.parameters.p_max fig = plt.Figure() # Position firm A ax = plt.subplot(4, 1, 1) ax.plot(t, position_A, color=color_A, alpha=1, linewidth=1.1) ax.plot(t, np.ones(len(t)) * 0.5, color='0.5', linewidth=0.5, linestyle='dashed', zorder=-10) # ax.plot(t, position_B, color="black", alpha=0.5, linewidth=1) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_xticks([]) ax.set_yticks([0, 1]) ax.set_ylabel('Position $a$', labelpad=16) # Add title plt.title("Evolution of positions and prices ($r={}$)".format( backup.parameters.r)) # Position firm B ax = plt.subplot(4, 1, 2) ax.plot(t, position_B, color=color_B, alpha=1, linewidth=1.1) ax.plot(t, np.ones(len(t)) * 0.5, color='0.5', linewidth=0.5, linestyle='dashed', zorder=-10) # ax.plot(t, position_A, color="black", alpha=0.5, linewidth=1) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_xticks([]) ax.set_yticks([0, 1]) ax.set_ylabel('Position $b$', labelpad=16) # Price firm A ax = plt.subplot(4, 1, 3) ax.plot(t, price_A, color=color_A, alpha=1, linewidth=1.1, clip_on=False) # ax.plot(t, price_B, color="black", alpha=0.5, linewidth=1) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_xticks([]) ax.set_yticks([price_min, price_max]) ax.set_ylabel('Price $a$', labelpad=10) # , rotation=0) ax.set_ylim([price_min, price_max]) # Price firm B ax = plt.subplot(4, 1, 4) ax.plot(t, price_B, color=color_B, alpha=1, linewidth=1.1, clip_on=False) # ax.plot(t, price_A, color="black", alpha=0.5, linewidth=1) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_xticks([]) ax.set_yticks([price_min, price_max]) ax.set_ylabel('Price $b$', labelpad=10) # , rotation=0) ax.set_ylim([price_min, price_max]) ax.set_xlabel("Time", labelpad=10) # Cut margins plt.tight_layout() # Save fig plt.savefig(fig_name) plt.close()
#(ori_h,ori_w)=img.shape print("annotation by ", first_doctor) anns_1 = extract_annotation(json_path_1) print("annotation by ", second_doctor) anns_2 = extract_annotation(json_path_2) im_1 = img.copy() im_2 = img.copy() #print("processing file", index, "of ", len(ann2.index)) if len(anns_1) > 0: im_1 = plot_image(im_1, anns_1, class_names) if len(anns_2) > 0: im_2 = plot_image(im_2, anns_2, class_names) # Create figure and axes figure = plt.Figure(figsize=(14.5, 7), dpi=300) ax1 = figure.add_subplot(121) ax2 = figure.add_subplot(122) # Display the image ax1.imshow(im_1) ax2.imshow(im_2) ax1.set_title(first_doctor + " Annotation") ax2.set_title(second_doctor + " Annotation") #plt.show(block = False) canvas = FigureCanvasTkAgg(figure, master=root) # A tk.DrawingArea. canvas.draw() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2Tk(canvas, root)
tabControl.add(tab2, text='Tab 2') tabControl.pack(expand=1, fill='both') #---------------variables to store info------------ count_sentence = tk.StringVar() count_words = tk.StringVar() word_most = tk.StringVar() word_least = tk.StringVar() path_of_file= tk.StringVar() path_of_file2= tk.StringVar() lines_with_keywords = tk.StringVar() main_file = tk.StringVar() keyword_file = tk.StringVar() fig = plt.Figure(figsize=(8,4), dpi=100) # ----------functions-------------------------------- # function to open and access file def open_file(is_keyword_file = False): file = filedialog.askopenfilename(initialdir="~") if (not is_keyword_file): main_file.set(file) path_of_file.set(file) else: keyword_file.set(file) path_of_file2.set(file) # refresh file to update info
Prediction_result = ('Predicted Stock Index Price: ', regr.predict( [[New_Interest_Rate, New_Unemployment_Rate]])) label_Prediction = tk.Label(root, text=Prediction_result, bg='orange') canvas1.create_window(120, 280, window=label_Prediction) button1 = tk.Button(root, text='Predict Stock Index Price', command=values, bg='orange') # button to call the 'values' command above canvas1.create_window(140, 150, window=button1) # plot 1st scatter figure3 = plt.Figure(figsize=(4, 3), dpi=100) ax3 = figure3.add_subplot(111) ax3.scatter(df['Interest_Rate'].astype(float), df['Stock_Index_Price'].astype(float), color='r') scatter3 = FigureCanvasTkAgg(figure3, root) scatter3.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH) ax3.legend() ax3.set_xlabel('Interest Rate') ax3.set_title('Interest Rate Vs. Stock Index Price') # plot 2nd scatter figure4 = plt.Figure(figsize=(4, 3), dpi=100) ax4 = figure4.add_subplot(111) ax4.scatter(df['Unemployment_Rate'].astype(float), df['Stock_Index_Price'].astype(float),
import os """Global Variables""" # Default port for USB devices PORT_NAME = '/dev/ttyUSB0' # Global variable for LIDAR sensor lidar = RPLidar(None, PORT_NAME) # Data queue used for passing data from the scan thread to the GUI thread data_queue = Queue(maxsize=10) # GUI Global variables lidar_program_running = True window = Tk() figure = plt.Figure(figsize=(30, 30), dpi=100) ax = figure.add_subplot(111, projection='polar') export = False save_menu = "" def scan(): # Function for generating lidar scan data global lidar_program_running # Create array of scan data scan_data = [0]*360 try: # Iterate through the scans produced by the LIDAR for single_scan in lidar.iter_scans():
} df2 = DataFrame(Data2, columns=['Year', 'Unemployment_Rate']) df2 = df2[['Year', 'Unemployment_Rate']].groupby('Year').sum() Data3 = { 'Interest_Rate': [5, 5.5, 6, 5.5, 5.25, 6.5, 7, 8, 7.5, 8.5], 'Stock_Index_Price': [1500, 1520, 1525, 1523, 1515, 1540, 1545, 1560, 1555, 1565] } df3 = DataFrame(Data3, columns=['Interest_Rate', 'Stock_Index_Price']) root = tk.Tk() figure1 = plt.Figure(figsize=(6, 5), dpi=100) ax1 = figure1.add_subplot(111) bar1 = FigureCanvasTkAgg(figure1, root) bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH) df1.plot(kind='bar', legend=True, ax=ax1) ax1.set_title('Country Vs. GDP Per Capita') figure2 = plt.Figure(figsize=(5, 4), dpi=100) ax2 = figure2.add_subplot(111) line2 = FigureCanvasTkAgg(figure2, root) line2.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH) df2.plot(kind='line', legend=True, ax=ax2, color='r', marker='o', fontsize=10) ax2.set_title('Year Vs. Unemployment Rate') figure3 = plt.Figure(figsize=(5, 4), dpi=100) ax3 = figure3.add_subplot(111)
def __init__(self, filename=None): # initialise some variables: self.ncfn = filename self.pc = None self.cfacs = None self.proj = None self.src_proj = None self.lon1=None self.lon2=None self.lat1=None self.lat2=None ############### ## GTK setup ## ############### # create new window self.win = Gtk.Window(Gtk.WindowType.TOPLEVEL) ###################### # setup window ###################### self.win.set_border_width(10) self.win.set_default_size(1200, 500) self.win.set_title('SMC Gridded Data Plotter') ###################### # add the GTK canvas: ###################### self.fig = plt.Figure(figsize=(4,3), dpi=100) self.canvas = FigureCanvas(self.fig) ################ # Add menu bar # ################ menu_bar = Gtk.MenuBar() file_menu = Gtk.Menu() open_item = Gtk.MenuItem("Open") exit_item = Gtk.MenuItem("Exit") file_menu.append(open_item) file_menu.append(exit_item) open_item.connect("activate", self.load_event) root_menu = Gtk.MenuItem("File") root_menu.set_submenu(file_menu); menu_bar.append(root_menu) ########### # Controls ########## # buttons: btnPlot = Gtk.Button('Update Plot') btnPrev = Gtk.Button('Prev Time') btnNext = Gtk.Button('Next Time') # Field combo box: store = Gtk.ListStore(str,str) self.cbox_field = Gtk.ComboBox.new_with_model_and_entry(store) cell = Gtk.CellRendererText() self.cbox_field.pack_start(cell, True) self.cbox_field.add_attribute(cell, 'text', 1) self.cbox_field.set_entry_text_column(1) store.append(['hs','sig wave heihgt']) # Times combo box: store = Gtk.ListStore(int,str) self.cbox_times = Gtk.ComboBox.new_with_model_and_entry(store) cell = Gtk.CellRendererText() self.cbox_times.pack_start(cell, True) self.cbox_times.add_attribute(cell, 'text', 1) self.cbox_times.set_entry_text_column(1) #for i in range(1,61): # store.append([i-1, 'T+%03d' % i]) # Domain combo box: store = Gtk.ListStore(str,float,float,float,float) self.cbox_domains = Gtk.ComboBox.new_with_model_and_entry(store) cell = Gtk.CellRendererText() self.cbox_domains.pack_start(cell, True) self.cbox_domains.add_attribute(cell, 'text', 0) store.append(['Full Domain (could be slow)', -999.9, -999.9, -999.9, -999.9]) store.append(['UK', 35.0, 70.0, -15.0, 10.0]) store.append(['South West UK', 49.4, 51.5, -6.7, -1.6]) store.append(['Mediterranean', 29.5, 46.5, -6.0, 36.5]) store.append(['North Atlantic', 20.0, 70.0, -90, 30]) store.append(['West Pacific', -70.0, 70.0, 120, 200]) store.append(['East Pacific', -70.0, 70.0, -160, -68]) store.append(['Arabian Gulf', 23.0, 30.5, 47.5, 59.5]) store.append(['Caspian Sea', 36.0, 47.5, 46.0, 55.5]) store.append(['Black Sea', 40.5, 47.1, 27.0, 42.0]) store.append(['Caribbean', 10.0, 27.5, -86.5, -58.5]) store.append(['South China Sea', -9.5, 24.0, 98.0, 128.0]) store.append(['Australasia', -48, 0.0, 105.0, 179.0]) store.append(['New Zealand', -50, -30, 160.0, 182.0]) self.cbox_domains.set_entry_text_column(0) self.cbox_domains.set_active(1) # Projections: store = Gtk.ListStore(object, str) self.cbox_proj = Gtk.ComboBox.new_with_model_and_entry(store) cell = Gtk.CellRendererText() self.cbox_proj.pack_start(cell, True) self.cbox_proj.add_attribute(cell, 'text', 1) self.cbox_proj.set_entry_text_column(1) store.append([ccrs.PlateCarree(), 'Plate Carree']) store.append([ccrs.RotatedPole(pole_latitude=37.5, pole_longitude=177.5),'Euro Rotated Pole']) store.append([ccrs.Robinson(), 'Robinson']) store.append([ccrs.Mercator(), 'Mercator']) store.append([ccrs.Geostationary(), 'Geostationary']) store.append([ccrs.PlateCarree(central_longitude=180), 'Plate Carree (central_longitude=180)']) self.cbox_proj.set_active(0) # coastlines: store = Gtk.ListStore(object, str) self.cbox_coast = Gtk.ComboBox.new_with_model_and_entry(store) cell = Gtk.CellRendererText() self.cbox_coast.pack_start(cell, True) self.cbox_coast.add_attribute(cell, 'text', 1) self.cbox_coast.set_entry_text_column(1) store.append([None, 'None']) store.append(['10m', 'High res (10m)']) store.append(['50m', 'Medium res (50m)']) store.append(['110m', 'Low res (110m)']) self.cbox_coast.set_active(3) self.coast = '110m' # lat/lon ranges: self.inLat1 = Gtk.Entry(); self.inLat2 = Gtk.Entry(); self.inLon1 = Gtk.Entry(); self.inLon2 = Gtk.Entry(); self.domain_changed_event(self.cbox_domains) # update with default domain # Cell size selection cellsbox = Gtk.HBox(homogeneous=False, spacing=5) self.chkf1 = Gtk.CheckButton("1") self.chkf2 = Gtk.CheckButton("2") self.chkf3 = Gtk.CheckButton("3") self.chkf4 = Gtk.CheckButton("4") cellsbox.pack_end(self.chkf4, True, True, 0) cellsbox.pack_end(self.chkf3, True, True, 0) cellsbox.pack_end(self.chkf2, True, True, 0) cellsbox.pack_end(self.chkf1, True, True, 0) # Colour range box: crangebox = Gtk.HBox(homogeneous=False, spacing=5) self.cmin = Gtk.Entry() self.cmax = Gtk.Entry() self.cauto = Gtk.CheckButton('Auto') crangebox.pack_start(self.cmin, True, True, 0) crangebox.pack_start(self.cmax, True, True, 0) crangebox.pack_start(self.cauto, True, True, 0) self.cauto.set_active(True) self.cmin.set_sensitive(False) self.cmax.set_sensitive(False) self.cauto.connect('toggled', self.cauto_changed_event) ## controls layout grid = Gtk.Table(rows=8, columns=3) grid.attach(Gtk.Label(label='Field'), 0, 1, 0, 1, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(Gtk.Label(label='Time'), 0, 1, 1, 2, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(Gtk.Label(label='Projection'),0, 1, 2, 3, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(Gtk.Label(label='Coastline'), 0, 1, 3, 4, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(Gtk.Label(label='Domain '), 0, 1, 4, 5, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(Gtk.Label(label='Lat Range'), 0, 1, 5, 6, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(Gtk.Label(label='Lon Range'), 0, 1, 6, 7, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(Gtk.Label(label='Cell Factor'), 0, 1, 7, 8, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(Gtk.Label(label='Colour range'),0, 1, 8, 9, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.cbox_field, 1, 3, 0, 1, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.cbox_times, 1, 3, 1, 2 ,yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.cbox_proj, 1, 3, 2, 3 ,yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.cbox_coast, 1, 3, 3, 4 ,yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.cbox_domains, 1, 3, 4, 5 ,yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.inLat1, 1, 2, 5, 6, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.inLat2, 2, 3, 5, 6, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.inLon1, 1, 2, 6, 7, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(self.inLon2, 2, 3, 6, 7, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(cellsbox, 1, 3, 7, 8, yoptions=Gtk.AttachOptions.SHRINK) grid.attach(crangebox, 1, 3, 8, 9, yoptions=Gtk.AttachOptions.SHRINK) #grid.attach(btnPlot, 0, 1, 8, 9, yoptions=Gtk.AttachOptions.SHRINK, xoptions=Gtk.AttachOptions.SHRINK) # Hbox for plot buttons btn_hbox = Gtk.HBox(homogeneous=False, spacing=5) btn_hbox.pack_start(btnPrev, True, False, 0) btn_hbox.pack_start(btnPlot, True, False, 0) btn_hbox.pack_start(btnNext, True, False, 0) ## File details text view txt = Gtk.TextBuffer() txt.set_text('Please load a file') self.tv_file_details = Gtk.TextView.new_with_buffer(txt) vbox = Gtk.VBox(spacing=5) vbox.pack_start(grid, False, True, 0) vbox.pack_start(btn_hbox, False, True, 0) vbox.pack_end(self.tv_file_details, True, True, 0) # plot controls from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar toolbar = NavigationToolbar(self.canvas, self.win) #vbox.pack_end(toolbar, False, False) # Top level layout box: topbox = Gtk.VBox() topbox.pack_start(menu_bar, False, True, 0) box = Gtk.HBox(homogeneous=False, spacing=5) topbox.pack_end(box, True, True, 0) # canvas/toolbar layout plotbox = Gtk.VBox(homogeneous=False, spacing=0) plotbox.pack_start(self.canvas, True, True, 0) plotbox.pack_end(toolbar, False, False, 0) box.pack_start(plotbox, True, True, 0) box.pack_end(vbox, False, False, 0) self.win.add(topbox) ################### # connect signals: ################### # destroy/delete: self.win.connect("delete_event", self.delete_event) self.win.connect("destroy", self.destroy) btnPlot.connect("clicked", self.plot_event) btnNext.connect("clicked", self.next_time_event) btnPrev.connect("clicked", self.prev_time_event) self.cbox_domains.connect('changed', self.domain_changed_event) # show window self.win.show_all() #### Load file, if passed in: if self.ncfn is not None: self.loadfile(self.ncfn)
def __init__(self): # arrays used to draw figures (First number) self.x = [] self.y = [] # multi dimensional time series self.series1 = [] self.series2 = [] # arrays used to compare two number self.compare_x = [] self.compare_y = [] self.number_of_events = [] self.compare_number_of_events = [] # main window variable self.window = tk.Tk() # labels and drop down lists frame self.mainframe = Frame(self.window) # graph variables self.figure = plt.Figure(figsize=(4, 2), dpi=100) self.ax = self.figure.add_subplot(111) self.graph_x = FigureCanvasTkAgg(self.figure, self.window) self.graph_y = FigureCanvasTkAgg(self.figure, self.window) self.graph_number = FigureCanvasTkAgg(self.figure, self.window) # tkinter variables self.folder_name = StringVar(self.mainframe) self.session_name = StringVar(self.mainframe) self.file_name = StringVar(self.mainframe) self.compare_folder_name = StringVar(self.mainframe) self.compare_session_name = StringVar(self.mainframe) self.compare_file_name = StringVar(self.mainframe) # the list of options self.folder_list = os.listdir('e-BioDigit_DB/') self.folder_list.sort() self.compare_folder_list = os.listdir('e-BioDigit_DB/') self.compare_folder_list.sort() self.session_list = os.listdir('e-BioDigit_DB/' + self.folder_list[0]) self.session_list.sort() self.compare_session_list = os.listdir('e-BioDigit_DB/' + self.compare_folder_list[0]) self.compare_session_list.sort() self.number_list = os.listdir('e-BioDigit_DB/' + self.folder_list[0] + '/' + self.session_list[0]) self.number_list.sort() self.compare_number_list = os.listdir('e-BioDigit_DB/' + self.compare_folder_list[0] + '/' + self.compare_session_list[0]) self.compare_number_list.sort() self.popup_menu = OptionMenu(self.mainframe, self.file_name, *self.number_list) self.compare_popup_menu = OptionMenu(self.mainframe, self.compare_file_name, *self.compare_number_list) # set the main window title and size self.window.title("Number Representation") self.window.geometry('690x840') # add a grid frame self.mainframe.grid(column=0, row=0, sticky=(N, W)) self.mainframe.columnconfigure(0, weight=1) self.mainframe.rowconfigure(0, weight=1) self.mainframe.config(bg='black') self.mainframe.pack(side=tk.TOP, anchor=tk.NW) # create the drop down lists self.create_folder_option_menu() self.create_comparison_menu() # link functions to drop down value changes self.folder_name.trace('w', self.database_folder_changed) self.session_name.trace('w', self.session_folder_changed) self.file_name.trace('w', self.txt_file_changed) self.compare_folder_name.trace('w', self.compare_database_folder_changed) self.compare_session_name.trace('w', self.compare_session_folder_changed) self.compare_file_name.trace('w', self.compare_txt_file_changed) # it generates 2 files with over 89k lines which takes over 10 minutes, # comment the below line if you don't want to regenerate it # experimental_protocol(self.folder_list, self.session_list[1]) # start the main window self.window.mainloop()
command=lambda: Buttons('attack_speed')) attack_speed.pack(in_=top, side=tk.LEFT) attack_damage = ttk.Button(root, text='Attack Damage', command=lambda: Buttons('attack_damage')) attack_damage.pack(in_=top, side=tk.LEFT) attack_damage_level = ttk.Button( root, text="Attack Dmg/Level", command=lambda: Buttons('attack_damage_level')) attack_damage_level.pack(in_=top, side=tk.LEFT) armor = ttk.Button(root, text='Armor', command=lambda: Buttons('armor')) armor.pack(in_=top, side=tk.LEFT) hp = ttk.Button(root, text='Hitpoints', command=lambda: Buttons('hp')) hp.pack(in_=top, side=tk.LEFT) move_speed = ttk.Button(root, text='Movement Speed', command=lambda: Buttons('move_speed')) move_speed.pack(in_=top, side=tk.LEFT) figure1 = plt.Figure(figsize=[14.70, 8.27], dpi=100) scatter1 = FigureCanvasTkAgg(figure1, root) scatter1.get_tk_widget().pack(in_=bottom, fill=tk.BOTH) root.mainloop()
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk import matplotlib.pyplot as plt import tkinter as Tk import sys def destroy(e): sys.exit() root = Tk.Tk() root.wm_title("Embedding in TK") #root.bind("<Destroy>", destroy) f = plt.Figure() def grafica(): ax = f.add_subplot(111) ax.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6]) canvas.draw() # a tk.DrawingArea canvas = FigureCanvasTkAgg(f, master=root) canvas.get_tk_widget().pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1) toolbar = NavigationToolbar2Tk(canvas, root) toolbar.update()
def setUI(self): # canvas self.fig = plt.Figure() self.canvas = FigureCanvas(self.fig) # title label title_label = QLabel("🏠 예상 가격 🏠") title_label.setFont(QFont('맑은 고딕', 20)) # result text self.result = QTextEdit() self.result.setReadOnly(True) self.result.setFont(QFont('맑은 고딕', 30)) # left layout leftLayout = QVBoxLayout() leftLayout.addWidget(self.canvas) leftLayout.addWidget(title_label) leftLayout.addWidget(self.result) # form formGroupBox = QGroupBox("House Information") formLayout = QFormLayout() # 주소(시, 구, 동) self.address = QComboBox() self.address.addItem("-") self.address.addItems(sorted(self.addressItems)) self.address.currentTextChanged.connect(self.addressChanged) # 상세주소(단지) self.complexName = QComboBox() self.complexName.currentTextChanged.connect(self.complexNameChanged) self.supplyArea = QComboBox() # 평 수 self.floor = QSpinBox() # 층 수 self.recent_price = QLineEdit() # 매입가 self.recent_contact_date = QLineEdit() # 매입일 self.sell_date = QLineEdit() # 매매 예정일 formLayout.addRow(QLabel("주소(시, 구, 동)"), self.address) formLayout.addRow(QLabel("상세주소(단지명)"), self.complexName) formLayout.addRow(QLabel("평 수:"), self.supplyArea) formLayout.addRow(QLabel("층 수:"), self.floor) formLayout.addRow(QLabel("매입가:"), self.recent_price) formLayout.addRow(QLabel("매입일:"), self.recent_contact_date) formLayout.addRow(QLabel("매매 예정일:"), self.sell_date) formGroupBox.setLayout(formLayout) self.predictButton = QPushButton("predict") self.predictButton.clicked.connect(self.predictButtonClicked) # frame img = QPixmap(dirname(__file__) + "/title_img.PNG") img = img.scaledToWidth(450) img = img.scaledToHeight(300) frame = QLabel() frame.setPixmap(img) # Right Layout rightLayout = QVBoxLayout() rightLayout.addWidget(frame) rightLayout.addWidget(formGroupBox) rightLayout.addWidget(self.predictButton) # Merge leftLayout and rightLayout (5: 4) layout = QHBoxLayout() layout.addLayout(leftLayout) layout.addLayout(rightLayout) layout.setStretchFactor(leftLayout, 5) layout.setStretchFactor(rightLayout, 4) self.setLayout(layout)
drift_plot_tab = tk.Frame(tabs) drift_plot_tab.pack(fill='both', expand=True) tabs.add(drift_plot_tab, text="Drift plot") top_frame = tk.Frame(image_tab) bottom_frame = tk.Frame(image_tab) progress_frame = tk.Frame(image_tab) top_frame.pack(side=tk.TOP, expand=True) progress_frame.pack(side=tk.BOTTOM) bottom_frame.pack(side=tk.BOTTOM) plot_frame = tk.Frame(drift_plot_tab) plot_frame.pack(fill='both', expand=True) figure1 = plt.Figure(dpi=100) image_ax = figure1.add_subplot(111) image_canvas = FigureCanvasTkAgg(figure1, top_frame) image_canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=True) file_list_frame = tk.Frame(bottom_frame) file_list = FileList(fits_images, file_list_frame) file_list_frame.pack(side=tk.LEFT, padx=30, pady=30) fragment_displayer = FragmentDisplayer(bottom_frame) plotter = Plotter(plot_frame) displayer = ImageDisplayer(file_list, image_ax, images_dir, image_canvas, fragment_displayer, plotter) image_canvas.mpl_connect('button_press_event', displayer.select_star) remove_button = tk.Button(file_list_frame,
#%% #Uncomment the plotly code to use interactive plot # fig = go.Figure() # fig.add_trace(go.Scatter(x=np.arange(len(segment_51)), # y= segment_51, # name='segment 51')) # fig.add_trace(go.Scatter(x=np.arange(len(segment_51), # len(segment_51)+len(segment_52)), # y= segment_52, # name='segment 52')) # fig.show() fig = plt.Figure() plt.plot(np.arange(len(segment_51)), segment_51) plt.plot(np.arange(len(segment_51),len(segment_51)+len(segment_52)), segment_52) plt.show() #%% md ### Example of splitting the whole data into subsegment using time domain for PPG. #%% save_file_name = "example_file" save_file_folder = "subsegments_time" if not os.path.exists(save_file_folder):
def topic_graph(topic): context = {} dfc = dataset[dataset['topic'] == topic] dfc.reset_index(inplace=True) #################wordcloud###################### topictweets = str(dfc['full_text']) twitter = WordCloud(background_color='black', max_words=1000, stopwords=stopwords, collocations=False) twitter.generate(topictweets) fig = plt.figure() fig.set_figwidth(12) fig.set_figheight(12) plt.imshow(twitter, interpolation='bilinear') plt.axis('off') context['fig1'] = graphic(fig) ##################SENTIMENTS##################### possitive, negative, neutral = 0, 0, 0 for i in range(dfc.shape[0]): analysis = TextBlob(dfc['full_text'][i]) if analysis.sentiment.polarity > 0: possitive = possitive + 1 elif analysis.sentiment.polarity == 0: neutral = neutral + 1 else: negative = negative + 1 sentdf = pd.DataFrame() sentdf['type'] = ['possitive', 'neutral', 'negative'] sentdf.set_index('type', inplace=True) sentdf['count'] = [possitive, neutral, negative] ####################BARGRAPH######################## fig = plt.figure() sentdf.plot(kind='bar', figsize=(10, 6), color=('lightblue', 'orange', 'red')) plt.xlabel('emotion') plt.ylabel('No of tweets') plt.title(f"Sentiments for {topic}") context['fig2'] = graphic(fig) ####################PIECHART########################## sentdf['count'].plot(kind='pie', autopct='%1.1f%%', startangle=90, figsize=(10, 6), shadow=True, colors=['skyblue', 'yellow', 'red'], explode=[0.1, 0, 0], labels=None) fig = plt.Figure() plt.title('Overall Sentiment', y=1.12) plt.axis('equal') plt.ylabel('') plt.legend(labels=sentdf.index, loc='upper left') context['fig3'] = graphic(fig) ###################DAYBARGRAPGH######################## #dataset['created_at']=pd.to_datetime(dataset['created_at']) dfc['time'] = pd.to_datetime(dfc['created_at']) dfc['time'] = dfc['time'].dt.hour #dfc['time']=dataset['created_at'].dt.hour #listhour=[int(i[3:5]) for i in dfc['time'].tolist()] listhour = dfc['time'] listhour = sorted(listhour) binsh = np.arange(listhour[0], listhour[len(listhour) - 1], 1) fignewhour = plt.figure() plt.hist(listhour, bins=binsh, alpha=0.5) plt.title('hour graph for' + topic) plt.xlabel('hour') plt.ylabel('No of tweets') context['fig4'] = graphic(fignewhour) return context