def __init__(self): super().__init__() self.main = QWidget() self.setCentralWidget(self.main) layout = QHBoxLayout(self.main) # Zdefiniowanie canvasa na którym beda rysowane wykresy self.figure = Figure(figsize=(6, 6)) self.ax = self.figure.subplots() self.canvas = FigureCanvas(self.figure) layout.addWidget(self.canvas) side_layout = QVBoxLayout(self.main) layout.addLayout(side_layout) # zdefiniowanie textboxu FUNCTION self.label = QLabel('Function:', self) self.textbox_function = QLineEdit(self) self.textbox_function.move(20, 20) side_layout.addWidget(self.label) side_layout.addWidget(self.textbox_function) print(self.textbox_function) # zdefiniowanie textboxu MIN self.label = QLabel('Min:', self) self.spinbox_min = QDoubleSpinBox(self) self.spinbox_min.setRange(-100000, 100000) self.spinbox_min.setSingleStep(1) side_layout.addWidget(self.label) side_layout.addWidget(self.spinbox_min) # zdefiniowanie textboxu MAX self.label = QLabel('Max:', self) self.spinbox_max = QDoubleSpinBox(self) self.spinbox_max.setRange(-100000, 100000) self.spinbox_max.setSingleStep(1) side_layout.addWidget(self.label) side_layout.addWidget(self.spinbox_max) # zdefiniowanie textboxu STEP self.label = QLabel('Step:', self) self.spinbox_step = QDoubleSpinBox(self) self.spinbox_step.setRange(0, 100000) self.spinbox_step.setSingleStep(1) side_layout.addWidget(self.label) side_layout.addWidget(self.spinbox_step) # Zdefiniowanie przycisku i podlaczenie funkcji do niego self.calculate_button = QPushButton("Draw") self.calculate_button.clicked.connect(self.calculate_slot) side_layout.addWidget(self.calculate_button) side_layout.addStretch(1)
def spectrumFinished(self, mca_data, calib, config): a = str(self.directoryInput.text()).split(os.path.sep) suffix_path = os.path.join(*a[4:]) if 'inhouse' in a: a_dir = os.path.join('/data/pyarch/', a[2], suffix_path) else: a_dir = os.path.join('/data/pyarch/', a[4], a[3], *a[5:]) if a_dir[-1] != os.path.sep: a_dir += os.path.sep print "a_dir --------------------------->", a_dir if not os.path.exists(os.path.dirname(a_dir)): os.makedirs(os.path.dirname(a_dir)) filename_pattern = os.path.join( str(self.directoryInput.text()), "%s_%s_%%02d" % (str(self.prefixInput.text()), time.strftime("%d_%b_%Y"))) filename_pattern = os.path.extsep.join((filename_pattern, "png")) filename = filename_pattern % 1 i = 2 while os.path.isfile(filename): filename = filename_pattern % i i = i + 1 try: a = float(calib[0]) b = float(calib[1]) c = float(calib[2]) except BaseException: a = 0 b = 1 c = 0 calibrated_data = [] for line in mca_data: channel = line[0] counts = line[1] energy = a + b * channel + c * channel * channel calibrated_line = [energy, counts] calibrated_data.append(calibrated_line) calibrated_array = numpy.array(calibrated_data) fig = Figure(figsize=(15, 11)) ax = fig.add_subplot(111) ax.set_title(filename) ax.grid(True) #ax.plot(*(zip(*mca_data)), **{"color":'black'}) ax.plot(*(zip(*calibrated_array)), **{"color": 'black'}) #ax.set_xlabel("MCA channel") #ax.set_ylabel("MCA counts") ax.set_xlabel("Energy") ax.set_ylabel("Counts") canvas = FigureCanvasAgg(fig) logging.getLogger().info("Rendering spectrum to PNG file : %s", filename) canvas.print_figure(filename, dpi=80) logging.getLogger().debug("Copying PNG file to: %s", a_dir) shutil.copy(filename, a_dir) logging.getLogger().debug("Copying .fit file to: %s", a_dir) # tmpname=filename.split(".") color = XfeSpectrumBrick.STATES['ok'] self.statusBox.setTitle("Xfe spectrum status") config['max'] = config['max_user'] config['htmldir'] = a_dir try: self.emit(PYSIGNAL("xfeSpectrumDone"), (mca_data, calib, config)) except BaseException: logging.getLogger().exception( "XfeSpectrumBrick: problem updating embedded PyMCA") self.spectrumStatus.setPaletteBackgroundColor(QColor(color)) self.startSpectrumButton.commandDone() self.emit(PYSIGNAL("xfeSpectrumRun"), (False, )) self.parametersBox.setEnabled(True)
from matplotlib.axes import Subplot from matplotlib.backends.backend_gtk import FigureCanvasGTK from matplotlib.figure import Figure import gtk win = gtk.Window() win.set_name("Embedding in GTK") win.connect("destroy", gtk.mainquit) win.set_border_width(5) vbox = gtk.VBox(spacing=3) win.add(vbox) vbox.show() f = Figure(figsize=(5, 4), dpi=100) a = Subplot(f, 111) t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) a.plot(t, s) f.add_axis(a) canvas = FigureCanvasGTK(f) # a gtk.DrawingArea canvas.show() vbox.pack_start(canvas) button = gtk.Button('Quit') button.connect('clicked', lambda b: gtk.mainquit()) button.show() vbox.pack_start(button)
# Run the data through the autoencoder and convert back to iris cube pm_modified = ic.copy() pm_modified.data = normalise(pm_modified.data) ict = tf.convert_to_tensor(pm_modified.data, numpy.float32) ict = tf.reshape(ict, [1, 91 * 180]) # ???? result = autoencoder_modified.predict_on_batch(ict) result = tf.reshape(result, [91, 180]) pm_modified.data = unnormalise(result) # Make a comparison plot - original, then old autoencoder, then new one fig = Figure( figsize=(15, 15 * 1.06 / 1.04 * 1.5), # Width, Height (inches) dpi=100, facecolor=(0.88, 0.88, 0.88, 1), edgecolor=None, linewidth=0.0, frameon=False, subplotpars=None, tight_layout=None) canvas = FigureCanvas(fig) # Global projection projection = ccrs.RotatedPole(pole_longitude=180.0, pole_latitude=90.0) extent = [-180, 180, -90, 90] # Top third for the originals ax_orig = fig.add_axes([0.02, 0.67, 0.96, 0.32], projection=projection) ax_orig.set_axis_off() ax_orig.set_extent(extent, crs=projection) ax_old = fig.add_axes([0.02, 0.34, 0.96, 0.32], projection=projection)
from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.backend_bases import key_press_handler import scipy.constants as sc import matplotlib.patches as mpatches import sys if sys.version_info[0] < 3: import Tkinter as Tk else: import tkinter as Tk home = Tk.Tk() home.wm_title("Banda prohibida de los semiconductores") #Declaracion de limites f = Figure() plota = f.add_subplot(111) #Declaracion de Variables a = num.arange(0.1, 1000, 0.1)#Temperatura #Definicion de las funciones b=3.470-((7.70*10**(-4))*a**2/(a+600)) #GaN c=2.340-((6.20*10**(-4))*a**2/(a+460)) #GaP d=1.519-((5.41*10**(-4))*a**2/(a+204)) #GaAS e=1.425-((4.50*10**(-4))*a**2/(a+327)) #InP g=1.170-((4.73*10**(-4))*a**2/(a+636)) #Si h=0.744-((4.77*10**(-4))*a**2/(a+235)) #Ge #Se les asigna el label correspondiente a cada eje plota.plot(a,b,color='y',label='GaN') plota.plot(a,c,color='b',label='GaP') plota.plot(a,d,color='g',label='GaAS')
def __init__(self, parent): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"Captura de señales para el gesto 1", pos=wx.DefaultPosition, size=wx.Size(1400, 700), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) bSizer4 = wx.BoxSizer(wx.VERTICAL) self.m_staticText2 = wx.StaticText( self, wx.ID_ANY, u"Captura de señales para el primer gesto \n", wx.DefaultPosition, wx.Size(700, -1), 0) self.m_staticText2.Wrap(-1) self.m_staticText2.SetFont( wx.Font(34, 70, 90, 90, False, wx.EmptyString)) bSizer4.Add(self.m_staticText2, 0, wx.ALIGN_CENTER_HORIZONTAL, 10) bSizer49 = wx.BoxSizer(wx.VERTICAL) bSizer50 = wx.BoxSizer(wx.HORIZONTAL) bSizer50.SetMinSize(wx.Size(700, -1)) self.m_staticText30 = wx.StaticText( self, wx.ID_ANY, u"Para iniciar el experimento por favor observe \n ", wx.DefaultPosition, wx.Size(1000, -1), 0) self.m_staticText30.Wrap(-1) self.m_staticText30.SetFont( wx.Font(17, 70, 90, 90, False, wx.EmptyString)) bSizer50.Add(self.m_staticText30, 0, wx.ALL, 5) bSizer52 = wx.BoxSizer(wx.VERTICAL) bSizer52.SetMinSize(wx.Size(90, -1)) self.m_button32 = wx.Button( self, wx.ID_ANY, u"Inicio", wx.Point(-1, -1), wx.Size(150, -1), 0) self.m_button32.SetFont(wx.Font(25, 70, 90, 90, False, wx.EmptyString)) bSizer52.Add(self.m_button32, 0, wx.TOP, 10) bSizer50.Add(bSizer52, 1, 0, 5) self.m_animCtrl1 = AnimationCtrl(self, pos=( 40, 40), size=(24, 24), name="AnimationCtrl") self.m_animCtrl1.LoadFile(u"/Users/macfabian/Desktop/manos.gif") self.m_animCtrl1.Play() self.m_animCtrl1.SetMinSize(wx.Size(200, -1)) bSizer50.Add(self.m_animCtrl1, 0, wx.ALIGN_CENTER, 5) bSizer49.Add(bSizer50, 1, 0, 5) bSizer51 = wx.BoxSizer(wx.VERTICAL) self.m_staticText31 = wx.StaticText( self, wx.ID_ANY, u"Señal EMG", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText31.Wrap(-1) self.m_staticText31.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer51.Add(self.m_staticText31, 0, wx.ALL, 5) self.figure = Figure(figsize=(1, 2), dpi=80) self.axes = self.figure.add_subplot(111) t = np.arange(0.0, 3.0, 0.01) s = np.sin(2 * np.pi * t) self.axes.plot(t, s) self.canvas = FigureCanvas(self, -1, self.figure) bSizerEMG = wx.BoxSizer(wx.VERTICAL) bSizerEMG.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND) bSizer49.Add(bSizerEMG, 1, wx.EXPAND, 5) bSizer49.Add(bSizer51, 1, wx.EXPAND, 5) bSizer53 = wx.BoxSizer(wx.VERTICAL) self.m_staticText32 = wx.StaticText( self, wx.ID_ANY, u"Señal EEG", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText32.Wrap(-1) self.m_staticText32.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) self.figure = Figure(figsize=(1, 2), dpi=80) self.axes = self.figure.add_subplot(111) t = np.arange(0.0, 3.0, 0.01) s = np.sin(2 * np.pi * t) self.axes.plot(t, s) self.canvas = FigureCanvas(self, -1, self.figure) bSizerEEG = wx.BoxSizer(wx.VERTICAL) bSizerEEG.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND) bSizer49.Add(bSizerEEG, 1, wx.EXPAND, 5) bSizer53.Add(self.m_staticText32, 0, wx.ALL, 5) bSizer49.Add(bSizer53, 1, wx.EXPAND, 5) bSizer8 = wx.BoxSizer(wx.HORIZONTAL) self.m_staticText33 = wx.StaticText( self, wx.ID_ANY, u"Tiempo:", wx.DefaultPosition, wx.Size(550, -1), 0) self.m_staticText33.Wrap(-1) self.m_staticText33.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer8.Add(self.m_staticText33, 0, wx.ALL, 5) pos = wx.DefaultPosition size = wx.DefaultSize style = gizmos.LED_ALIGN_CENTER self.led = gizmos.LEDNumberCtrl(self, -1, pos, size, style) self.led.SetBackgroundColour("white") self.led.SetForegroundColour("black") bSizerTimmer = wx.BoxSizer(wx.VERTICAL) bSizerTimmer.Add(self.led, 1, wx.TOP | wx.LEFT | wx.EXPAND) bSizer49.Add(bSizerTimmer, 1, wx.EXPAND, 5) self.button_siguiente = wx.Button( self, wx.ID_ANY, u"Aceptar", wx.DefaultPosition, wx.Size(150, -1), 0) self.button_siguiente.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer8.Add(self.button_siguiente, 0, wx.ALL, 5) self.button_salir = wx.Button( self, wx.ID_ANY, u"Salir", wx.DefaultPosition, wx.Size(150, -1), 0) self.button_salir.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer8.Add(self.button_salir, 0, wx.ALL, 5) bSizer49.Add(bSizer8, 0, wx.TOP, 1) bSizer4.Add(bSizer49, 1, wx.EXPAND, 5) self.SetSizer(bSizer4) self.Layout() self.Centre(wx.BOTH) # Connect Events self.m_button32.Bind(wx.EVT_BUTTON, self.OnClickInicio) self.button_siguiente.Bind(wx.EVT_BUTTON, self.OnClickConcentimiento) self.button_salir.Bind(wx.EVT_BUTTON, self.OnClickSalir)
def create_dataset(n_sample=60000): """Creates toy dataset and save to disk.""" concept = np.reshape(np.random.randint(2, size=15 * n_sample), (-1, 15)).astype(np.bool_) concept[:15, :15] = np.eye(15) fig = Figure(figsize=(3, 3)) canvas = FigureCanvas(fig) axes = fig.gca() axes.set_xlim([0, 10]) axes.set_ylim([0, 10]) axes.axis('off') width, height = fig.get_size_inches() * fig.get_dpi() width = int(width) height = int(height) location = [(1.3, 1.3), (3.3, 1.3), (5.3, 1.3), (7.3, 1.3), (1.3, 3.3), (3.3, 3.3), (5.3, 3.3), (7.3, 3.3), (1.3, 5.3), (3.3, 5.3), (5.3, 5.3), (7.3, 5.3), (1.3, 7.3), (3.3, 7.3), (5.3, 7.3)] location_bool = np.zeros(15) x = np.zeros((n_sample, width, height, 3)) color_array = ['green', 'red', 'blue', 'black', 'orange', 'purple', 'yellow'] for i in range(n_sample): if i % 1000 == 0: print('{} images are created'.format(i)) if concept[i, 5] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], 'x', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 6] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], '3', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 7] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], 's', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 8] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], 'p', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 9] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], '_', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 10] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], 'd', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 11] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], 'd', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 12] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], 11, color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 13] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], 'o', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 14] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], '.', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 0] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], '+', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 1] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], '1', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 2] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], '*', color=color_array[np.random.randint(100) % 7], markersize=30, mew=3, ms=5) if concept[i, 3] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], '<', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) if concept[i, 4] == 1: a = np.random.randint(15) while location_bool[a] == 1: a = np.random.randint(15) location_bool[a] = 1 axes.plot( location[a][0], location[a][1], 'h', color=color_array[np.random.randint(100) % 7], markersize=20, mew=4, ms=8) canvas.draw() image = np.fromstring( canvas.tostring_rgb(), dtype='uint8').reshape(width, height, 3) x[i, :, :, :] = image # imgplot = plt.imshow(image) # plt.show() # create label by booling functions y = np.zeros((n_sample, 15)) y[:, 0] = ((1 - concept[:, 0] * concept[:, 2]) + concept[:, 3]) > 0 y[:, 1] = concept[:, 1] + (concept[:, 2] * concept[:, 3]) y[:, 2] = (concept[:, 3] * concept[:, 4]) + (concept[:, 1] * concept[:, 2]) y[:, 3] = np.bitwise_xor(concept[:, 0], concept[:, 1]) y[:, 4] = concept[:, 1] + concept[:, 4] y[:, 5] = (1 - (concept[:, 0] + concept[:, 3] + concept[:, 4])) > 0 y[:, 6] = np.bitwise_xor(concept[:, 1] * concept[:, 2], concept[:, 4]) y[:, 7] = concept[:, 0] * concept[:, 4] + concept[:, 1] y[:, 8] = concept[:, 2] y[:, 9] = np.bitwise_xor(concept[:, 0] + concept[:, 1], concept[:, 3]) y[:, 10] = (1 - (concept[:, 2] + concept[:, 4])) > 0 y[:, 11] = concept[:, 0] + concept[:, 3] + concept[:, 4] y[:, 12] = np.bitwise_xor(concept[:, 1], concept[:, 2]) y[:, 13] = (1 - (concept[:, 0] * concept[:, 4] + concept[:, 3])) > 0 y[:, 14] = np.bitwise_xor(concept[:, 4], concept[:, 3]) np.save('x_data.npy', x) np.save('y_data.npy', y) np.save('concept_data.npy', concept) return width, height
def __init__(self, parent=None): self.master = parent self.h = Tkinter.StringVar() self.h.set("14.1") self.speed = Tkinter.StringVar() self.speed.set("0.") self.speedSet = False self.command = "STOP" self.status = "Unknown" self.SetHeightButtonColor = 'orange' self.directionNumber = 0 self.SonarValue = 0. self.Light = 0 self.ImageSide = "Right" self.imagecommand = 0 self.commandDictionnary = {} self.commandDictionnary['STOP'] = 0 self.commandDictionnary['MOVE'] = 1 self.commandDictionnary['RESET'] = 2 self.commandDictionnary['SETH'] = 3 self.commandDictionnary['ERROR'] = 4 self.position = np.array([0., 0., 0.]) self.orientation = np.array([1., 0., 0.]) self.LegsAngles = [np.array([0., 0., 0.]) for i in range(6)] self.geometry_data = tools.file_loader( '/home/dardelet/Documents/SAR/Projet/Code/Robot-Hexapode/PROG/Python/SRC/Algo_mouvement_Laurent_V2/geometry.txt' ) self.master.title("Cornelius GUI") self.label = Tkinter.Label(self.master, text="Main commands") self.label.grid(row=0, columnspan=5, sticky='EW') LegsWindow = Tkinter.Frame(self.master, borderwidth=2) LegsWindow.grid(row=1, column=0, rowspan=2) self.LegsLabels = [ Tkinter.Label(LegsWindow, text=" \n {0} \n ".format(n_leg), bg="red", fg="white") for n_leg in range(6) ] self.LegsStatus = [] for n_legLabel in range(len(self.LegsLabels)): self.LegsStatus += [0] self.LegsLabels[n_legLabel].grid(row=int(0 + n_legLabel / 3), column=n_legLabel % 3) self.master.protocol("WM_DELETE_WINDOW", self.master.quit) light = Tkinter.PhotoImage(file='Icons/light.png') self.ButtonLight = Tkinter.Button(self.master, width=50, height=50, image=light, bg='red') self.ButtonLight.image = light self.ButtonLight.grid(row=1, column=3, sticky='E') self.ButtonLight.bind("<Button-1>", self.SwitchLight) RobotDataWindow = Tkinter.Frame(self.master, borderwidth=2) RobotDataWindow.grid(row=1, column=4) self.PositionLabel = Tkinter.Label(RobotDataWindow, text="Position : ") self.PositionLabel.grid(row=0, column=0) self.OrientationLabel = Tkinter.Label(RobotDataWindow, text="Orientation : ") self.OrientationLabel.grid(row=1, column=0) self.SonarLabel = Tkinter.Label(RobotDataWindow, text="Sonar : ") self.SonarLabel.grid(row=2, column=0) self.PlotPlot = Figure(figsize=(5, 4), dpi=100) self.SubPlotPlot = self.PlotPlot.add_subplot(111, projection='3d') self.PlotCanvas = FigureCanvasTkAgg(self.PlotPlot, master=self.master) self.PlotCanvas.get_tk_widget().grid(row=3, column=0, columnspan=4) self.SubPlotPlot.mouse_init() self.PlotPosition = Figure(figsize=(5, 4), dpi=100) self.SubPlotPosition = self.PlotPosition.add_subplot(111) self.PositionCanvas = FigureCanvasTkAgg(self.PlotPosition, master=self.master) self.PositionCanvas.get_tk_widget().grid(row=4, column=0, columnspan=4) CameraOptionsWindow = Tkinter.Frame(self.master, borderwidth=2) CameraOptionsWindow.grid(row=2, column=4) self.SideButton = Tkinter.Button(CameraOptionsWindow, text="Camera : Master", command=self.SwitchSide) self.SideButton.grid(row=0, column=0) self.SaveButton = Tkinter.Button(CameraOptionsWindow, text="Save", command=self.SavePicture) self.SaveButton.grid(row=0, column=1) f = Figure(figsize=(5, 4), dpi=100) self.SubPlotPicture = f.add_subplot(111) self.img = np.zeros([480, 640, 3]) self.PictureCanvas = FigureCanvasTkAgg(f, master=self.master) self.PictureCanvas.show() self.PictureCanvas.get_tk_widget().grid(row=3, column=4, columnspan=1) self.PlotMap = Figure(figsize=(5, 4), dpi=100) self.SubPlotMap = self.PlotMap.add_subplot(111, projection='3d') self.MapCanvas = FigureCanvasTkAgg(self.PlotMap, master=self.master) self.MapCanvas.get_tk_widget().grid(row=4, column=4, columnspan=1) self.SubPlotMap.mouse_init() DirectionWindow = Tkinter.Frame(self.master, borderwidth=2) DirectionWindow.grid(row=5, column=0, columnspan=3) self.master.bind("<KeyPress>", self.keyEventCallback) left = Tkinter.PhotoImage(file='Icons/up_left.png') self.ButtonLeft = Tkinter.Button(DirectionWindow, width=50, height=50, image=left, bg='gray') self.ButtonLeft.image = left self.ButtonLeft.bind("<Button-1>", lambda event, d=1: self.SetDirection(d)) self.ButtonLeft.bind("<ButtonRelease-1>", lambda event, d=0: self.SetDirection(d)) self.ButtonLeft.pack(side=Tkinter.LEFT) front = Tkinter.PhotoImage(file='Icons/up.png') self.ButtonFront = Tkinter.Button(DirectionWindow, width=50, height=50, image=front, bg='gray') self.ButtonFront.image = front self.ButtonFront.bind("<Button-1>", lambda event, d=2: self.SetDirection(d)) self.ButtonFront.bind("<ButtonRelease-1>", lambda event, d=0: self.SetDirection(d)) self.ButtonFront.pack(side=Tkinter.LEFT) right = Tkinter.PhotoImage(file='Icons/up_right.png') self.ButtonRight = Tkinter.Button(DirectionWindow, width=50, height=50, image=right, bg='gray') self.ButtonRight.image = right self.ButtonRight.bind("<Button-1>", lambda event, d=3: self.SetDirection(d)) self.ButtonRight.bind("<ButtonRelease-1>", lambda event, d=0: self.SetDirection(d)) self.ButtonRight.pack(side=Tkinter.LEFT) #self.master.bind("<KeyRelease>", self.keyReleaseCallback) print "Starting ROSWorker class" self.RosWorker = ROSWorker(self) ParametersWindow = Tkinter.Frame(self.master, borderwidth=2) ParametersWindow.grid(row=5, column=3) HLabel = Tkinter.Label(ParametersWindow, text="H = ") HLabel.grid(row=0, column=0) self.HEntry = Tkinter.Entry(ParametersWindow, textvariable=self.h) self.HEntry.grid(row=0, column=1) self.HButton = Tkinter.Button(ParametersWindow, text="Set Height", background='gray', command=self.RosWorker.SetH) self.HButton.grid(row=0, column=2) SpeedLabel = Tkinter.Label(ParametersWindow, text="Speed = ") SpeedLabel.grid(row=1, column=0) self.SpeedEntry = Tkinter.Entry(ParametersWindow, textvariable=self.speed) self.SpeedEntry.grid(row=1, column=1) self.SpeedButton = Tkinter.Button(ParametersWindow, text="Set Speed", background='orange', command=self.RosWorker.SetSpeed) self.SpeedButton.grid(row=1, column=2) CommandWindow = Tkinter.Frame(self.master, borderwidth=2) CommandWindow.grid(row=5, column=4) self.StatusLabel = Tkinter.Label(CommandWindow, text="Current status : " + self.status) self.StatusLabel.grid(row=0, column=0, columnspan=4) self.CommandLabel = Tkinter.Label(CommandWindow, text="Current command : " + self.command) self.CommandLabel.grid(row=1, column=0, columnspan=4) self.StopButton = Tkinter.Button(CommandWindow, text=" \nSTOP\n ", background='red', command=lambda: self.SetCommand(0)) self.StopButton.grid(row=2, column=0) self.MoveButton = Tkinter.Button(CommandWindow, text=" \nMove\n ", background='red', command=lambda: self.SetCommand(1)) self.MoveButton.grid(row=2, column=1) self.ResetButton = Tkinter.Button(CommandWindow, text=" \nReset\n ", background='red', command=lambda: self.SetCommand(2)) self.ResetButton.grid(row=2, column=2) self.SetHeightButton = Tkinter.Button( CommandWindow, text=" \nSet Height\n ", background='red', command=lambda: self.SetCommand(3)) self.SetHeightButton.grid(row=2, column=3) self.UpdateCommand() self.UpdateStatus() #self.RosProcess = Process(target = self.RosWorker.run(), args=()) self.N = 1 self.UpdateStructure() self.UpdatePicture() self.UpdateRobotData() self.UpdatePosition() self.UpdateMap() self.UpdateLegs() self.UpdateSonar()
def __init__(self, ispec, z, parent=None, llist=None, norm=True, vmnx=[-300., 300.] * u.km / u.s, fwhm=0.): ''' spec = Spectrum1D Norm: Bool (False) Normalized spectrum? abs_sys: AbsSystem Absorption system class ''' super(IGGVelPlotWidget, self).__init__(parent) # Initialize self.parent = parent spec, spec_fil = xxgu.read_spec(ispec) self.spec = spec self.spec_fil = spec_fil self.fwhm = fwhm self.z = z self.vmnx = vmnx self.norm = norm # Init self.flag_add = False self.flag_idlbl = False self.flag_mask = False self.wrest = 0. self.avmnx = np.array([0., 0.]) * u.km / u.s self.model = XSpectrum1D.from_tuple( (spec.dispersion, np.ones(len(spec.dispersion)))) self.psdict = {} # Dict for spectra plotting self.psdict[ 'xmnx'] = self.vmnx.value # Too much pain to use units with this self.psdict['ymnx'] = [-0.1, 1.1] self.psdict['nav'] = xxgu.navigate(0, 0, init=True) # Status Bar? #if not status is None: # self.statusBar = status # Line List if llist is None: self.llist = xxgu.set_llist(['HI 1215', 'HI 1025']) else: self.llist = llist self.llist['z'] = self.z # Indexing for line plotting self.idx_line = 0 self.init_lines() # Create the mpl Figure and FigCanvas objects. # self.dpi = 150 self.fig = Figure((8.0, 4.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus) self.canvas.setFocus() self.canvas.mpl_connect('key_press_event', self.on_key) self.canvas.mpl_connect('button_press_event', self.on_click) # Sub_plots self.sub_xy = [3, 4] self.fig.subplots_adjust(hspace=0.0, wspace=0.1) vbox = QtGui.QVBoxLayout() vbox.addWidget(self.canvas) self.setLayout(vbox) # Draw on init self.on_draw()
def __init__(self, parent, config): wx.Panel.__init__(self, parent, -1, size=(100, 100)) self.figure = Figure() self.axes = self.figure.add_subplot(111)
def __init__(self, parent, config, Screens, scale_w, scale_h): displaysize = wx.GetDisplaySize() w = displaysize[0] h = displaysize[1] self.gui_width = (w * scale_w) / Screens self.gui_height = (h * scale_h) #print("Scaled GUI width", self.gui_width, "and height", self.gui_height) if self.gui_width < 600 or self.gui_height < 500: print("Your screen width", w, "and height", h) print("Scaled GUI width", self.gui_width, "and height", self.gui_height) print("Please adjust scale_h and scale_w, or get a bigger screen!") self.size = displaysize wx.Frame.__init__(self, None, title="DeepLabCut2.0 - Manual Frame Extraction GUI", size=(self.gui_width, self.gui_height)) self.Button1 = wx.Button(self, -1, "Load Video", size=(150, 40), pos=(self.gui_width * .1, self.gui_height * .9)) self.Button1.Bind(wx.EVT_BUTTON, self.browseDir) self.Button1.Enable(True) self.Button2 = wx.Button(self, -1, "Grab a Frame", size=(150, 40), pos=(self.gui_width * .4, self.gui_height * .9)) self.Button2.Bind(wx.EVT_BUTTON, self.grabFrame) self.Button2.Enable(False) self.Button3 = wx.Button(self, -1, "Help", size=(80, 40), pos=(self.gui_width * .3, self.gui_height * .9)) self.Button3.Bind(wx.EVT_BUTTON, self.helpButton) self.Button4 = wx.Button(self, -1, "Quit", size=(80, 40), pos=(self.gui_width * .7, self.gui_height * .9)) self.Button4.Bind(wx.EVT_BUTTON, self.quitButton) self.numberFrames = 0 self.currFrame = 0 self.figure = Figure() self.axes = self.figure.add_subplot(111) self.drs = [] with open(str(config), 'r') as ymlfile: self.cfg = yaml.load(ymlfile) self.Task = self.cfg['Task'] self.start = self.cfg['start'] self.stop = self.cfg['stop'] self.date = self.cfg['date'] self.videos = self.cfg['video_sets'].keys() self.video_names = [Path(i).stem for i in self.videos] self.config_path = Path(config)
except: tolS = 1.0 print("enter Float for tolS") tolSentry.delete(0, END) tolSentry.insert(0, '1.0') return tolN, tolS def drawNewTree(): tolN, tolS = getInputs() #get values from Entry boxes reDraw(tolS, tolN) root = Tk() reDraw.f = Figure(figsize=(5, 4), dpi=100) #create canvas reDraw.canvas = FigureCanvasTkAgg(reDraw.f, master=root) reDraw.canvas.show() reDraw.canvas.get_tk_widget().grid(row=0, columnspan=3) Label(root, text="tolN").grid(row=1, column=0) tolNentry = Entry(root) tolNentry.grid(row=1, column=1) tolNentry.insert(0, '10') Label(root, text="tolS").grid(row=2, column=0) tolSentry = Entry(root) tolSentry.grid(row=2, column=1) tolSentry.insert(0, '1.0') Button(root, text="ReDraw", command=drawNewTree).grid(row=1, column=2, rowspan=3)
def __init__(self, parent): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"変位たわみ分布", pos=wx.DefaultPosition, size=wx.Size(980, 600), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) self.SetForegroundColour( wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)) self.SetBackgroundColour( wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)) self.dammy1_figure = Figure(figsize=(8, 4.3), dpi=100) self.dammy1_canvas = FigureCanvasWxAgg(self, -1, self.dammy1_figure) self.dammy1_navigationToolbar = NavigationToolbar2Wx( self.dammy1_canvas) self.dammy1_navigationToolbar.Realize() self.dammy1_navigationToolbar.update() import configdata self.mpoint = configdata.dis.shape[1] self.scale = 3000 # 仮設定(表示倍率) self.data = configdata.dis.sel(layer=0, features=["dis_x", "dis_y"], stats="mu").values self.pxpy = configdata.pxpys.sel(layer=0, features=["x", "y"]).values self.bsize = configdata.bss.sel(point=0, layer=0, features="y").values gSizer1 = wx.BoxSizer(wx.VERTICAL) bSizer34 = wx.BoxSizer(wx.VERTICAL) # 右上 bSizer34.Add(self.dammy1_canvas, 0, wx.EXPAND) bSizer34.Add(self.dammy1_navigationToolbar, 0, wx.EXPAND) gSizer1.Add(bSizer34, 0, wx.EXPAND, 0) bSizer19 = wx.BoxSizer(wx.HORIZONTAL) self.m_sliderDD = wx.Slider(self, wx.ID_ANY, 0, 0, self.data.shape[0] - 1, wx.DefaultPosition, wx.Size(830, 30), style=wx.SL_LABELS | wx.SL_AUTOTICKS) self.m_sliderDD.SetTickFreq(20) bSizer19.Add(self.m_sliderDD, 0, wx.ALIGN_BOTTOM | wx.BOTTOM, 50) self.m_textCtrl3 = wx.TextCtrl(self, wx.ID_ANY, u"---", wx.DefaultPosition, wx.DefaultSize, wx.TE_CENTRE) bSizer19.Add(self.m_textCtrl3, 0, wx.ALIGN_BOTTOM | wx.BOTTOM, 40) gSizer1.Add(bSizer19, 1, wx.ALIGN_BOTTOM, 50) self.Bind(wx.EVT_SLIDER, self.m_replotsliderDD) self.SetSizer(gSizer1) self.Layout() self.Centre(wx.BOTH) frame = 0 # frame = self.m_sliderDD.GetValue() cv2img = cv2.imread(configdata.image_filelist[0]) self.im = cv2.cvtColor(cv2img, cv2.COLOR_BGR2RGB) self.y2 = (self.data[frame, :, 1] * self.scale) + (self.im.shape[0] / 2) self.dammy1_figure.subplots_adjust(left=0.005, right=0.995, bottom=0.1, top=0.9) self.dammy1_axes = self.dammy1_figure.add_subplot(111, facecolor='black') # for i in range(self.mpoint): # self.dammy1_axes.add_patch(plt.Rectangle((self.pxpy[i, 0], self.pxpy[i, 1]), self.bsize, self.bsize, alpha=0.4, # edgecolor="red")) self.dammy1_axes.minorticks_on() self.dammy1_axes.tick_params(axis='both', which='major', direction='inout', colors="black", labelsize=8, bottom='on', left='on') self.dammy1_axes.grid(True) self.dammy1_axes.tick_params(axis='both', which='minor', direction='inout', length=5, colors="black") self.dammy1_axes.set_title('Deflection Y') self.dammy1_axes.plot(self.pxpy[:, 0] + int(self.bsize / 2), self.y2, color='red') self.dammy1_axes.imshow(self.im) self.dammy1_canvas.draw()
def __init__(self, iface, parent=None): """Constructor.""" super(SpatialDecisionDockWidget, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) # define globals self.iface = iface self.canvas = self.iface.mapCanvas() # set up GUI operation signals # data self.iface.projectRead.connect(self.updateLayers) self.iface.newProjectCreated.connect(self.updateLayers) self.iface.legendInterface().itemRemoved.connect(self.updateLayers) self.iface.legendInterface().itemAdded.connect(self.updateLayers) self.openScenarioButton.clicked.connect(self.openScenario) self.saveScenarioButton.clicked.connect(self.saveScenario) self.selectLayerCombo.activated.connect(self.setSelectedLayer) self.selectAttributeCombo.activated.connect(self.setSelectedAttribute) self.startCounterButton.clicked.connect(self.startCounter) self.cancelCounterButton.clicked.connect(self.cancelCounter) # analysis self.graph = QgsGraph() self.tied_points = [] self.setNetworkButton.clicked.connect(self.buildNetwork) self.shortestRouteButton.clicked.connect(self.calculateRoute) self.clearRouteButton.clicked.connect(self.deleteRoutes) self.serviceAreaButton.clicked.connect(self.calculateServiceArea) self.bufferButton.clicked.connect(self.calculateBuffer) self.selectBufferButton.clicked.connect(self.selectFeaturesBuffer) self.makeIntersectionButton.clicked.connect(self.calculateIntersection) self.selectRangeButton.clicked.connect(self.selectFeaturesRange) self.expressionSelectButton.clicked.connect(self.selectFeaturesExpression) self.expressionFilterButton.clicked.connect(self.filterFeaturesExpression) # visualisation self.displayStyleButton.clicked.connect(self.displayBenchmarkStyle) self.displayRangeButton.clicked.connect(self.displayContinuousStyle) self.updateAttribute.connect(self.plotChart) # reporting self.featureCounterUpdateButton.clicked.connect(self.updateNumberFeatures) self.saveMapButton.clicked.connect(self.saveMap) self.saveMapPathButton.clicked.connect(self.selectFile) self.updateAttribute.connect(self.extractAttributeSummary) self.saveStatisticsButton.clicked.connect(self.saveTable) self.emitPoint = QgsMapToolEmitPoint(self.canvas) self.featureCounterUpdateButton.clicked.connect(self.enterPoi) self.emitPoint.canvasClicked.connect(self.getPoint) # set current UI values self.counterProgressBar.setValue(0) # add button icons self.medicButton.setIcon(QtGui.QIcon(':icons/medic_box.png')) self.ambulanceButton.setIcon(QtGui.QIcon(':icons/ambulance.png')) self.logoLabel.setPixmap(QtGui.QPixmap(':icons/ambulance.png')) movie = QtGui.QMovie(':icons/loading2.gif') self.logoLabel.setMovie(movie) movie.start() # add matplotlib Figure to chartFrame self.chart_figure = Figure() self.chart_subplot_hist = self.chart_figure.add_subplot(221) self.chart_subplot_line = self.chart_figure.add_subplot(222) self.chart_subplot_bar = self.chart_figure.add_subplot(223) self.chart_subplot_pie = self.chart_figure.add_subplot(224) self.chart_figure.tight_layout() self.chart_canvas = FigureCanvas(self.chart_figure) self.chartLayout.addWidget(self.chart_canvas) # initialisation self.updateLayers()
def __init__(self, parent=None): super(Window, self).__init__(parent) self.runStatus = False self.setGeometry(100, 100, 1200, 700) self.setFixedSize(1200, 700) self.setWindowTitle('1D Forward Modeling Magnetotelluric') self.setWindowIcon(QtGui.QIcon('../images/icon.png')) self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.buttonPlot = QtWidgets.QPushButton('Run') self.buttonPlot.clicked.connect(self.get_data) self.buttonAbout = QtWidgets.QPushButton('About') self.buttonAbout.clicked.connect(self.form_about) self.buttonSModel = QtWidgets.QPushButton('Save Model') self.buttonSModel.clicked.connect(self.save_model) self.buttonSData = QtWidgets.QPushButton('Save Data') self.buttonSData.clicked.connect(self.save_data) textMaxPeriode = QtWidgets.QLabel('Maximum Period:') textNumDec = QtWidgets.QLabel('Number of Decade:') textPerDec = QtWidgets.QLabel('Periode per Decade:') self.lineEditMaxPeriode = QtWidgets.QLineEdit('1000', self) self.lineEditNumDec = QtWidgets.QLineEdit('6', self) self.lineEditPerDec = QtWidgets.QLineEdit('10', self) textRes = QtWidgets.QLabel('Resistivity:') textThi = QtWidgets.QLabel('Thickness:') self.lineEditRes = QtWidgets.QLineEdit('100, 10, 1000', self) self.lineEditThi = QtWidgets.QLineEdit('1000, 2000', self) horizontalLayout1 = QtWidgets.QHBoxLayout() horizontalLayout1.addWidget(textMaxPeriode) horizontalLayout1.addWidget(self.lineEditMaxPeriode) horizontalLayout1.addWidget(textNumDec) horizontalLayout1.addWidget(self.lineEditNumDec) horizontalLayout1.addWidget(textPerDec) horizontalLayout1.addWidget(self.lineEditPerDec) horizontalLayout2 = QtWidgets.QHBoxLayout() horizontalLayout2.addWidget(textRes) horizontalLayout2.addWidget(self.lineEditRes) horizontalLayout2.addWidget(textThi) horizontalLayout2.addWidget(self.lineEditThi) horizontalLayout3 = QtWidgets.QHBoxLayout() horizontalLayout3.addWidget(self.buttonPlot) horizontalLayout3.addWidget(self.buttonSModel) horizontalLayout3.addWidget(self.buttonSData) horizontalLayout3.addWidget(self.buttonAbout) verticalLayout = QtWidgets.QVBoxLayout() verticalLayout.addLayout(horizontalLayout1) verticalLayout.addLayout(horizontalLayout2) verticalLayout.addWidget(self.toolbar) verticalLayout.addWidget(self.canvas) verticalLayout.addLayout(horizontalLayout3) self.setLayout(verticalLayout)
def plot_noise_nc(fglob, **kwargs): """ Create noise measurements from all noise sweeps in a netcdf file, make plots, and pickle the noise measurements fglob : string or list filename glob. Can be either a filename, which can contain * or ? wildcards, or a list of files plot_all : bool (default False) if True, plot all sweeps, otherwise just plot the first one for each resonator **kwargs are passed to the noise measurement class """ if type(fglob) is str: fnames = glob.glob(fglob) else: fnames = fglob plotall = kwargs.pop('plot_all', False) fnames.sort() errors = {} pdf = None for fname in fnames: try: fdir, fbase = os.path.split(fname) fbase, ext = os.path.splitext(fbase) rnc = readoutnc.ReadoutNetCDF(fname) nms = [] for (k, ((sname, swg), (tname, tsg))) in enumerate( zip(rnc.sweeps_dict.items(), rnc.timestreams_dict.items())): #fig = plot_noise(swg,tsg,hwg,chip,**kwargs) indexes = np.unique(swg.index) for index in indexes: try: nm = SweepNoiseMeasurement(fname, sweep_group_index=k, timestream_group_index=k, resonator_index=index, **kwargs) except IndexError: print "failed to find index", index, "in", sname, tname continue if plotall or k == 0: try: if pdf is None: chipfname = nm.chip_name.replace(' ', '_').replace( ',', '') pdfname = os.path.join( BASE_DATA_DIR, 'plots/%s_%s.pdf') % (fbase, chipfname) pdf = PdfPages(pdfname) try: os.chmod(pdfname, 0666) except OSError: print "could not change permissions of", pdfname fig = Figure(figsize=(16, 8)) title = ('%s %s' % (sname, tname)) nm.plot(fig=fig, title=title) canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) pdf.savefig(fig, bbox_inches='tight') except Exception: print "failed to plot", k, index, sname, tname, fname # else: # if pdf is not None: # pdf.close() # pdf = None nm._fractional_fluctuation_timeseries = None nms.append(nm) print fname, nm.start_temp, "K" if pdf is not None: pdf.close() pdf = None rnc.close() pklname = os.path.join(BASE_DATA_DIR, 'noise_sweeps_' + fbase + '.pkl') fh = open(pklname, 'w') cPickle.dump(nms, fh, -1) fh.close() try: os.chmod(pklname, 0666) except OSError: print "could not change permissions of", pklname except KeyboardInterrupt: raise except Exception, e: # raise errors[fname] = e
def test_kwargs_pass(): fig = Figure(label='whole Figure') sub_fig = fig.subfigures(1, 1, label='sub figure') assert fig.get_label() == 'whole Figure' assert sub_fig.get_label() == 'sub figure'
def redraw(self): variables = [] if self.includeallcheckBox.isChecked(): for i in range(self.interactionlistWidget.count()): variables.append(self.interactionlistWidget.item(i).text()) else: for i in range(self.selectedlistWidget.count()): variables.append(self.selectedlistWidget.item(i).text()) nX = len(variables) if nX < 1: QtWidgets.QMessageBox.critical(self,'Error',"Too few variables selected!",\ QtWidgets.QMessageBox.Ok) return () Yname = self.YcomboBox.currentText() Lc = DS.Lc[DS.Ic] Gc = DS.Gc[DS.Ic] Lcy = Lc[Gc] Lcx = Lc[-Gc] data = DS.Raw.loc[DS.Ir, DS.Ic] Y = data[Lcy] X = data[Lcx] if nX > X.shape[0]: QtWidgets.QMessageBox.critical(self,'Error',"Factors > Observation! \n Reduce factors.",\ QtWidgets.QMessageBox.Ok) return () ny = self.YcomboBox.currentIndex() Y = Y.values.astype('float') X = X.values.astype('float') Y = Y[:, ny] nr = len(Y) basey = [Term([LookupFactor(Yname)])] basex = [] for term in variables: if term == 'Intercept': basex = [INTERCEPT] variables.remove(term) for term in variables: vterm = term.split(':') term_lookup = [LookupFactor(x) for x in vterm] if len(term_lookup) > 1: if vterm[0] == vterm[1]: term_lookup = [EvalFactor(vterm[0] + ' ** 2')] basex.append(Term(term_lookup)) desc = ModelDesc(basey, basex) data = np.column_stack((X, Y)) columns = Lcx.tolist() columns.append(Yname) data = pd.DataFrame(data, columns=columns) y, mx = dmatrices(desc, data, return_type='dataframe') dism = np.linalg.inv(np.dot(mx.T.values, mx.values)) mod = OLS(y, mx) DOE.res = mod.fit() # calculation of cross-validation ypcv = list() rcv = list() bres = list() loo = LeaveOneOut() loo.get_n_splits(mx) for train_index, test_index in loo.split(mx): mx_train = mx.ix[train_index, :] mx_test = mx.ix[test_index, :] y_train = y.ix[train_index, :] y_test = y.ix[test_index, :] modcv = OLS(y_train, mx_train) rescv = modcv.fit() ypcv.append(rescv.predict(mx_test).values[0]) rcv.append(rescv.predict(mx_test).values[0] - y_test.values[0]) bres.append((rescv.params - DOE.res.params).values**2) bres = pd.DataFrame(bres) bres = bres.sum() * nr / (nr - 1) bres = np.sqrt(bres.values) tres = np.abs(DOE.res.params.values / bres) pt = 2 * t.pdf(tres, nr) fig = Figure() ax = fig.add_subplot(111) if self.coefradioButton.isChecked(): if DOE.res.params.index[0] == 'Intercept': ind = np.arange(1, len(DOE.res.params)) vcol = [] for i in ind: if (DOE.res.pvalues[i] < 0.05): vcol.append('red') else: vcol.append('blue') ax.bar(ind, DOE.res.params[1:], align='center', color=vcol) ax.set_title('Coefficient Value : Intercept {:10.4f}-{:10.4f}-{:10.4f}'.\ format(DOE.res.conf_int().ix[0,0],DOE.res.params[0],DOE.res.conf_int().ix[0,1])) ax.set_xticklabels(DOE.res.params.index[1:], rotation='vertical') cmin = DOE.res.params[1:] - DOE.res.conf_int().ix[1:, 0] cmax = DOE.res.conf_int().ix[1:, 1] - DOE.res.params[1:] ax.errorbar(ind, DOE.res.params[1:], yerr=[cmin.values, cmax.values], fmt='o', ecolor='green') else: ind = np.arange(1, len(DOE.res.params) + 1) ax.bar(ind, DOE.res.params, align='center') ax.set_title('Coefficient Value : None Intercept') ax.set_xticklabels(DOE.res.params.index[0:], rotation='vertical') cmin = DOE.res.conf_int().ix[0:, 0] - DOE.res.params[0:] cmax = DOE.res.conf_int().ix[0:, 1] - DOE.res.params[0:] ax.errorbar(ind, DOE.res.params[0:], yerr=[cmin.values, cmax.values], fmt='o', ecolor='green') ax.set_xticks(ind) ax.set_xlabel('Coefficient Number (except Intercept)') ax.annotate('red bar: significance 5%', xy=(0.75, 0.95), xycoords='figure fraction', fontsize=8) elif self.coefpredradioButton.isChecked(): if DOE.res.params.index[0] == 'Intercept': ind = np.arange(1, len(DOE.res.params)) vcol = [] for i in ind: if (pt[i] < 0.05): vcol.append('red') else: vcol.append('blue') ax.bar(ind, DOE.res.params[1:], align='center', color=vcol) ax.set_title( 'Coefficient Value : Intercept {:10.4f}-{:10.4f}-{:10.4f}'. format(DOE.res.params[0] - tres[0] * bres[0] / np.sqrt(nr), DOE.res.params[0], DOE.res.params[0] + tres[0] * bres[0] / np.sqrt(nr))) ax.set_xticklabels(DOE.res.params.index[1:], rotation='vertical') ax.errorbar(ind, DOE.res.params[1:], yerr=tres[1:] * bres[1:] / np.sqrt(nr), fmt='o', ecolor='green') else: ind = np.arange(1, len(DOE.res.params) + 1) ax.bar(ind, DOE.res.params, align='center') ax.set_title('Coefficient Value : None Intercept') ax.set_xticklabels(DOE.res.params.index[0:], rotation='vertical') ax.errorbar(ind, DOE.res.params[0:], yerr=tres[0:] * bres[0:] / np.sqrt(nr), fmt='o', ecolor='green') ax.set_xticks(ind) ax.set_xlabel('Coefficient Number (except Intercept)') ax.annotate('red bar: significance 5%', xy=(0.75, 0.95), xycoords='figure fraction', fontsize=8) elif self.fitradioButton.isChecked(): yf = DOE.res.fittedvalues.tolist() resid = DOE.res.resid.tolist() ax.scatter(y, yf, color='red', alpha=0.3, marker='o') ax.set_ylabel('Fitted Values', color='red') ax.tick_params('y', colors='red') ax1 = ax.twinx() ax1.scatter(y, resid, color='blue', alpha=0.3, marker='o') ax1.set_ylabel('Residuals', color='blue') ax1.tick_params('y', colors='blue') xmin, xmax = ax.get_xlim() ax.set_ylim([xmin, xmax]) df = DOE.res.df_resid vares = np.sum(DOE.res.resid**2) / df rmsef = np.sqrt(vares) vary = np.var(y.values) evar = (1 - vares / vary) * 100 ax.set_title( 'df {:3.0f}; RMSEF {:6.2f}; Exp.Var.{:5.1f}%'.format( df, rmsef, evar)) ax.add_line(Line2D([xmin, xmax], [xmin, xmax], color='red')) ax1.add_line(Line2D([xmin, xmax], [0, 0], color='blue')) ax.set_xlabel('Measured Values') if self.VcheckBox.isChecked(): Lr = DOE.res.model.data.row_labels for i, txt in enumerate(Lr): ax.annotate(str(txt), (y.ix[i], yf[i])) elif self.predradioButton.isChecked(): ax.scatter(y, ypcv, color='red', alpha=0.3, marker='o') ax.set_ylabel('CV Predicted Values', color='red') ax.tick_params('y', colors='red') ax1 = ax.twinx() ax1.scatter(y, rcv, color='blue', alpha=0.3, marker='o') ax1.set_ylabel('CV Residuals', color='blue') ax1.tick_params('y', colors='blue') xmin, xmax = ax.get_xlim() ax.set_ylim([xmin, xmax]) ax.set_xlabel('Measured Values') df = DS.Raw.shape[0] varcv = np.sum(np.array(rcv)**2) / df rmsecv = np.sqrt(varcv) vary = np.var(y.values) evar = (1 - varcv / vary) * 100 ax.set_title( 'df {:3.0f}; RMSECV {:6.2f}; Exp.Var.{:5.1f}%'.format( df, rmsecv, evar)) ax.add_line(Line2D([xmin, xmax], [xmin, xmax], color='red')) ax1.add_line(Line2D([xmin, xmax], [0, 0], color='blue')) if self.VcheckBox.isChecked(): Lr = DOE.res.model.data.row_labels for i, txt in enumerate(Lr): ax.annotate(str(txt), (y.ix[i], ypcv[i])) elif self.levradioButton.isChecked(): Ftable = surtabDlg.launch(None) if len(np.shape(Ftable)) == 0: return () if np.argmax(Ftable['X axis'].values) == np.argmax( Ftable['Y axis'].values): QtWidgets.QMessageBox.critical(self,'Error',"Two variables on the same axis",\ QtWidgets.QMessageBox.Ok) return () fig = plt.figure() ax = fig.add_subplot(111) npts = 20 xname = Ftable[(Ftable['X axis'] == True).values].index[0] yname = Ftable[(Ftable['Y axis'] == True).values].index[0] cname = Ftable[(Ftable['Constant'] == True).values].index.tolist() cvalue = Ftable.loc[(Ftable['Constant'] == True).values, 'value'] zname = Yname x = np.linspace(float(Ftable['min'][xname]), float(Ftable['max'][xname]), npts) y = np.linspace(float(Ftable['min'][yname]), float(Ftable['max'][yname]), npts) px = [] py = [] for i in range(npts): for j in range(npts): px.append(x[i]) py.append(y[j]) data = pd.DataFrame({xname: px, yname: py, zname: px}) xtitle = '' for i in range(len(cname)): xtitle = xtitle + cname[i] + ' = ' + str( cvalue.values.tolist()[i]) data[cname[i]] = np.ones(npts**2) * float(cvalue[i]) my, mx = dmatrices(desc, data, return_type='dataframe') pz = np.diag(np.dot(np.dot(mx, dism), mx.T)) px = np.array(px) py = np.array(py) pz = np.array(pz) z = plt.mlab.griddata(px, py, pz, x, y, interp='linear') plt.contour(x, y, z, 15, linewidths=0.5, colors='k') plt.contourf(x, y, z, 15, cmap=plt.cm.rainbow) plt.colorbar() ax.set_xlabel(xname) ax.set_ylabel(yname) ax.set_title(xtitle) ax.set_xlim([px.min(), px.max()]) ax.set_ylim([py.min(), py.max()]) elif self.surradioButton.isChecked(): Ftable = surtabDlg.launch(None) if len(np.shape(Ftable)) == 0: return () if np.argmax(Ftable['X axis'].values) == np.argmax( Ftable['Y axis'].values): QtWidgets.QMessageBox.critical(self,'Error',"Two variables on the same axis",\ QtWidgets.QMessageBox.Ok) return () fig = plt.figure() ax = fig.add_subplot(111) npts = 100 xname = Ftable[(Ftable['X axis'] == True).values].index[0] yname = Ftable[(Ftable['Y axis'] == True).values].index[0] cname = Ftable[(Ftable['Constant'] == True).values].index.tolist() cvalue = Ftable.loc[(Ftable['Constant'] == True).values, 'value'] zname = Yname x = np.linspace(float(Ftable['min'][xname]), float(Ftable['max'][xname]), npts) y = np.linspace(float(Ftable['min'][yname]), float(Ftable['max'][yname]), npts) px = [] py = [] for i in range(npts): for j in range(npts): px.append(x[i]) py.append(y[j]) data = pd.DataFrame({xname: px, yname: py, zname: px}) xtitle = '' for i in range(len(cname)): xtitle = xtitle + cname[i] + ' = ' + str( cvalue.values.tolist()[i]) data[cname[i]] = np.ones(npts**2) * float(cvalue[i]) my, mx = dmatrices(desc, data, return_type='dataframe') pz = DOE.res.predict(mx) px = np.array(px) py = np.array(py) pz = np.array(pz) z = plt.mlab.griddata(px, py, pz, x, y, interp='linear') plt.contour(x, y, z, 15, linewidths=0.5, colors='k') plt.contourf(x, y, z, 15, cmap=plt.cm.rainbow) plt.colorbar() ax.set_xlabel(xname) ax.set_ylabel(yname) ax.set_title(xtitle) ax.set_xlim([px.min(), px.max()]) ax.set_ylim([py.min(), py.max()]) elif self.dismradioButton.isChecked(): fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(dism) fig.colorbar(cax) ax.set_title('Trace = {:10.4f}'.format(np.trace(dism))) elif self.inflradioButton.isChecked(): mxc = preprocessing.scale(mx.values, with_mean=True, with_std=False) mxc2 = mxc**2 infl = np.sum(mxc2, axis=0) * np.diag(dism) fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(infl.reshape(1, -1), cmap='gray_r') fig.colorbar(cax) ax.yaxis.grid(False) ax.tick_params(axis='y', which='both', left='off', right='off', labelleft='off') ax.set_xlabel('Inlaction Factor') if self.XcheckBox.isChecked(): if self.XlineEdit.text(): ax.set_xlabel(self.XlineEdit.text()) else: ax.set_xlabel('') if self.YcheckBox.isChecked(): if self.YlineEdit.text(): ax.set_ylabel(self.YlineEdit.text()) else: ax.set_ylabel('') if self.XGcheckBox.isChecked(): ax.xaxis.grid(True) else: ax.xaxis.grid(False) if self.YGcheckBox.isChecked(): ax.yaxis.grid(True) else: ax.yaxis.grid(False) if not self.XMcheckBox.isChecked(): ax.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off') if not self.YMcheckBox.isChecked(): ax.tick_params(axis='y', which='both', left='off', right='off', labelleft='off') self.rmmpl() self.addmpl(fig)
def draw_GUI(paper, year_data, advisor_name, exam_method, recommend_method, other_method): second_window = Tk() second_window.title('搜尋' + advisor_name + '教授的結果') second_window.geometry('1700x800') #簡易資料frame simple_frame = Frame(second_window) simple_frame.place(x=200, y=10, height=350, width=1200) simple_frame_addmission = Frame(simple_frame, width=250, background="lightyellow") simple_frame_addmission.place(x=0, y=0, height=350, width=600) simple_frame_graduateYear = Frame(simple_frame, background='lightgreen') simple_frame_graduateYear.place(x=600, y=0, height=350, width=600) label_addmission = Label(simple_frame_addmission, font=20, text="入學方式統計結果", background='gold') label_addmission.pack(side='top', fill='x') label_graduateYear = Label(simple_frame_graduateYear, font=20, text="畢業時間統計結果", background='yellowgreen') label_graduateYear.pack(side='top', fill='x') #圓餅圖 - 畢業時間 pieChart_graduate_label = [] pieChart_graduate_rate = [] for i in range(1, 11): if year_data[i] != 0: pieChart_graduate_label.append(str(i) + " years") pieChart_graduate_rate.append(year_data[i]) fig_graduateYear = Figure(facecolor='lightgreen') ax = fig_graduateYear.add_subplot(111) ax.pie(pieChart_graduate_rate, radius=1, labels=pieChart_graduate_label, autopct='%0.2f%%', shadow=True) pieChart_graduateYear = FigureCanvasTkAgg(fig_graduateYear, simple_frame_graduateYear) pieChart_graduateYear.get_tk_widget().place(x=5, y=30, height=300, width=420) #圓餅圖 - 入學方式 pieChart_addmission_label = ['Exam', 'Recommand', 'Others'] pieChart_addmission_rate = [exam_method, recommend_method, other_method] fig_addmission = Figure(facecolor='lightyellow') ax = fig_addmission.add_subplot(111) ax.pie(pieChart_addmission_rate, radius=1, labels=pieChart_addmission_label, autopct='%0.2f%%', shadow=True) pieChart_addmission = FigureCanvasTkAgg(fig_addmission, simple_frame_addmission) pieChart_addmission.get_tk_widget().place(x=5, y=30, height=300, width=420) #統計表格 - 畢業時間 table_graduateYear = ttk.Treeview(simple_frame_graduateYear, selectmode='browse') table_graduateYear['show'] = 'headings' table_graduateYear["columns"] = ("畢業時間", "人數") table_graduateYear.column("畢業時間", width=80) table_graduateYear.column("人數", width=60) table_graduateYear.heading("畢業時間", text="畢業時間") table_graduateYear.heading("人數", text="人數") for i in range(1, 11): if year_data[i] != 0: table_graduateYear.insert("", 'end', value=(str(i) + " 年畢業", year_data[i])) table_graduateYear.place(x=440, y=45, height=250, width=150) #統計表格 - 入學方式 table_addmission = ttk.Treeview(simple_frame_addmission, selectmode='browse') table_addmission['show'] = 'headings' table_addmission["columns"] = ("入學方式", "人數") table_addmission.column("入學方式", width=80) table_addmission.column("人數", width=60) table_addmission.heading("入學方式", text="入學方式") table_addmission.heading("人數", text="人數") table_addmission.insert("", 'end', value=("考試入學", exam_method)) table_addmission.insert("", 'end', value=("推甄入學", recommend_method)) table_addmission.insert("", 'end', value=("其他管道", other_method)) table_addmission.place(x=440, y=45, height=250, width=150) #詳細資料frame&表格 detail_frame = Frame(second_window) detail_frame.place(x=250, y=375, width=1150, height=350) table_detail = ttk.Treeview(detail_frame, selectmode='browse', height=350) scrollbar = ttk.Scrollbar(detail_frame, orient="vertical", command=table_detail.yview) scrollbar.grid(row=0, column=1, sticky="ns") table_detail['yscrollcommand'] = scrollbar.set scrollbar.pack(side='right', fill="y") table_detail.configure(yscrollcommand=scrollbar.set) table_detail['show'] = 'headings' table_detail["columns"] = ("學生編號", "畢業年度", "入學方式", "就學期間", "論文名稱") table_detail.column("學生編號", width=80) table_detail.column("畢業年度", width=80) table_detail.column("入學方式", width=80) table_detail.column("就學期間", width=80) table_detail.column("論文名稱", width=800) table_detail.heading("學生編號", text="學生編號") table_detail.heading("畢業年度", text="畢業年度") table_detail.heading("入學方式", text="入學方式") table_detail.heading("就學期間", text="就學期間") table_detail.heading("論文名稱", text="論文名稱") for i in range(len(paper)): table_detail.insert( "", 'end', value=(i + 1, paper[i].graduate_year, paper[i].addmission_method, paper[i].duringSchool, paper[i].paper_title)) table_detail.pack() second_window.mainloop()
def store_2ddata(data, fname, pltitle='', dir='./', fits=False, plot=True, plrange=(None, None), log=False, rollaxes=False, cmap='RdYlBu', xlab='X [pix]', ylab='Y [pix]', cbarlab=None, hdr=(), ident=True): """ Store **data** to disk as FITS and/or plot as annotated plot in PDF. @param [in] data 2D data array to show @param [in] fname Filename base to use (also fallback for plot title) @param [in] pltitle Plot title (if given) @param [in] dir Output directory @param [in] fits Toggle FITS output @param [in] plot Toggle 2D plot output as PDF @param [in] plrange Use this range for plotting in imshow() (None for autoscale) @param [in] log Take logarithm of data before storing. @param [in] rollaxes Roll axes for PDF plot such that (0,0) is the center @param [in] cmap Colormap to use for PDF @param [in] xlab X-axis label @param [in] ylab Y-axis label @param [in] cbarlab Colorbar label (for units) @param [in] hdr Additional FITS header items, give a list of tuples: [(key1, val1), (key2, val2)] @param [in] ident Add identification string to plots @returns Tuple of (fitsfile path, plotfile path) """ # Do not store empty data if (len(data) <= 0): return data_arr = np.asanyarray(data) if (log): data_arr = np.log10(data_arr) extent = None if (rollaxes): sh = data_arr.shape extent = (-sh[1] / 2., sh[1] / 2., -sh[0] / 2., sh[0] / 2.) # Check if dir exists, or create if (not os.path.isdir(dir)): os.makedirs(dir) fitsfile = filenamify(fname) + '.fits' fitspath = os.path.join(dir, fitsfile) plotfile = filenamify(fname) + '.pdf' plotpath = os.path.join(dir, plotfile) if (fits): # Generate some metadata. Also store plot settings here hdr_dict = dict({ 'filename': fitsfile, 'desc': fname, 'title': pltitle, 'plxlab': xlab, 'plylab': ylab, 'pllog': log, 'plrlxs': rollaxes, 'plcmap': cmap, 'plrng0': plrange[0] if plrange[0] else 0, 'plrng1': plrange[1] if plrange[1] else 0, }.items() + dict(hdr).items()) hdr = mkfitshdr(hdr_dict) # Store data to disk pyfits.writeto(fitspath, data_arr, header=hdr, clobber=True, checksum=True) if (plot): #plot_from_fits(fitspath) pltit = fname if (pltitle): pltit = pltitle # Plot without GUI, using matplotlib internals fig = Figure(figsize=(6, 6)) ax = fig.add_subplot(111) # Make margin smaller fig.subplots_adjust(left=0.15, right=0.95, top=0.9, bottom=0.1) img = 0 # Colormaps # plus min: cmap=cm.get_cmap('RdYlBu') # linear: cmap=cm.get_cmap('YlOrBr') # gray: cmap=cm.get_cmap('gray') img = ax.imshow(data_arr, interpolation='nearest', cmap=cm.get_cmap(cmap), aspect='equal', extent=extent, vmin=plrange[0], vmax=plrange[1]) ax.set_title(pltit) ax.set_xlabel(xlab) ax.set_ylabel(ylab) # dimension 0 is height, dimension 1 is width # When the width is equal or more than the height, use a horizontal bar, otherwise use vertical if (data_arr.shape[0] / data_arr.shape[1] >= 1.0): cbar = fig.colorbar(img, orientation='vertical', aspect=30, pad=0.05, shrink=0.8) else: cbar = fig.colorbar(img, orientation='horizontal', aspect=30, pad=0.12, shrink=0.8) if (cbarlab): cbar.set_label(cbarlab) # Add ID string if (ident): # Make ID string datestr = datetime.datetime.utcnow().isoformat() + 'Z' # Put this in try-except because os.getlogin() fails in screen(1) try: idstr = "%s@%s %s %s" % (os.getlogin(), os.uname()[1], datestr, sys.argv[0]) except OSError: idstr = "%s@%s %s %s" % (getpass.getuser(), os.uname()[1], datestr, sys.argv[0]) ax.text(0.01, 0.01, idstr, fontsize=7, transform=fig.transFigure) canvas = FigureCanvas(fig) #canvas.print_figure(plotfile, bbox_inches='tight') canvas.print_figure(plotpath) return (fitspath, plotpath)
def __init__(self, shapes=[221, 222, 224], parent=None, width=50, height=20, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.fig.patch.set_facecolor('#19232D') self.fig.subplots_adjust(top=0.94, bottom=0.109, left=0.067, right=0.962, hspace=0.343, wspace=0.197) #ax = fig.add_subplot(4,4,(1,16)) #ax.set_yticks([]) #ax.axis('off') I = 10 self.ax1 = self.fig.add_subplot(3, 3, (1, 8)) self.ax1.set_xlabel('w') self.ax1.set_ylabel('v') self.ax1.tick_params(axis='x', colors='#5e6f80', labelsize=7) self.ax1.tick_params(axis='y', colors='#5e6f80', labelsize=7) self.ax1.set_facecolor("#c6c9cc") self.phase_line, = self.ax1.plot([], [], 'ro') self.ax2 = self.fig.add_subplot(3, 3, 3, title='v_plot') self.ax2.set_xlim([0, t_total]) self.ax2.set_ylim([-2, 2]) self.ax2.set_ylabel('v') self.ax2.set_xlabel('t') self.ax2.tick_params(axis='x', colors='#5e6f80', labelsize=7) self.ax2.tick_params(axis='y', colors='#5e6f80', labelsize=7) self.ax2.set_facecolor("#c6c9cc") self.v_track, = self.ax2.plot([], []) self.ax3 = self.fig.add_subplot(3, 3, 9, title='w_plot') self.ax3.set_xlim([0, t_total]) self.ax3.set_ylim([-2, 2]) self.ax3.set_ylabel('w') self.ax3.set_xlabel('t') #ax.autoscale_view(scaley=True) self.ax3.autoscale(axis='y') self.ax3.tick_params(axis='x', colors='#5e6f80', labelsize=7) self.ax3.tick_params(axis='y', colors='#5e6f80', labelsize=7) self.ax3.set_facecolor("#c6c9cc") self.w_track, = self.ax3.plot([], []) self.ax4 = self.fig.add_subplot(3, 3, 6) self.ax4.text(0, 0, 'I = {}'.format(I), fontsize=12, horizontalalignment='center', verticalalignment='center') self.ax4.set_xlim([-0.5, 0.5]) self.ax4.set_ylim([-0.5, 0.5]) self.ax4.set_facecolor("#19232D") self.ax4.set_axis_off() super().__init__(self.fig)
def ref(): #print(p.cpu_percent()) a = amp.get() # print('AMPLITUDE = ', a) f = freq.get() # print('FREQUENCY = ', f) ho = hoff.get() # print('HORI OFF = ', ho) vo = voff.get() # print('VERI OFF = ', vo) # print(' ') x = list() y = list() s = float() for i in range(1, 200, 1): x.append(i) if opt.get() == 1: s = a * m.sin((2 * 3.14 * f * i) + ho) + vo y.append(s) elif opt.get() == 2: s = a * m.sin((2 * 3.14 * f * i) + ho) + vo if s < 0.0: y.append(-1) elif s > 0.0: y.append(1) elif s == 0.0: y.append(0) elif opt.get() == 3: s = -(2 * a / 3.14) * m.atan(1 / m.tan(i * 3.14 * f + ho)) + vo y.append(s) elif opt.get() == 4: s = (2 * a / 3.14) * m.asin(m.sin(i * 2 * 3.14 * f + ho)) + vo y.append(s) else: y.append(0) fig = Figure(figsize=(7, 5), dpi=75, facecolor='aqua') aggg = fig.add_subplot(111) aggg.plot(x, y, color='#00f7ff', linewidth=2.5) aggg.grid(True, color='black') aggg.set_xlabel('time') aggg.set_ylabel('amplitude') aggg.set_facecolor('#071770') c = FigureCanvasTkAgg(fig, master=window) #tool=NavigationToolbar2Tk(c,window) #stool.update() c.get_tk_widget().place(x=20, y=100) cpu = tk.Label(canvas, text='CPU : {} %'.format(psutil.cpu_percent()), fg='white', relief=FLAT, bg='#1a2024', font=('AgencyFB', 8, 'normal')).place(x=10, y=10) blank1 = tk.Label(canvas, text=' ', fg='white', relief=FLAT, bg='#1a2024', font=('AgencyFB', 8, 'normal')).place(x=720, y=410) blank2 = tk.Label(canvas, text=' ', fg='white', relief=FLAT, bg='#1a2024', font=('AgencyFB', 8, 'normal')).place(x=720, y=460) window.update_idletasks()
def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = Figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) # Just some button connected to `plot` method self.randomize_button = QtGui.QPushButton('Randomize') self.plot_button = QtGui.QPushButton('Plot') self.change_rep_button = QtGui.QPushButton('Change Rep') self.find_alpha_button = QtGui.QPushButton('Find alpha') self.randomize_button.clicked.connect(self.randomizeButton) self.plot_button.clicked.connect(self.plotButton) self.change_rep_button.clicked.connect(self.changeRepButton) self.find_alpha_button.clicked.connect(self.FindAlphaRepButton) # set the layout layout = QtGui.QVBoxLayout() inputLayout = QtGui.QGridLayout() outputLayout = QtGui.QGridLayout() self.inputs = {'m': {}, 'v': {}, 'u': {}} self.outputs = {'r': {}} for j in range(1, 9): field = QtGui.QLabel(str(j)) inputLayout.addWidget(field, 1, j + 1) for i in range(1, 4): field = QtGui.QLabel(['', 'Receiver', 'Sender', 'Representative'][i]) inputLayout.addWidget(field, i + 1, 1) for j in range(1, 9): field = QtGui.QDoubleSpinBox() field.setSingleStep(0.1) field.setMinimum(-20) field.setMaximum(20) if i != 3: value = 0 while value == 0: value = round(random.uniform(-20, 20), 0) field.setValue(value) else: field.setValue(self.inputs['m'][j].value()) # field.setAlignment(QtCore.Qt.AlignRight) field.setFont(QtGui.QFont("Ariel", 16)) inputLayout.addWidget(field, i + 1, j + 1) self.inputs[['m', 'v', 'u'][i - 1]][j] = field # display r outputLayout.addWidget(QtGui.QLabel('r'), 1, 1) for j in range(1, 9): field = QtGui.QLabel() # field.setAlignment(QtCore.Qt.AlignRight) field.setFont(QtGui.QFont("Ariel", 16)) outputLayout.addWidget(field, 1, j + 1) self.outputs['r'][j] = field # display f(w*) and alpha outputLayout.addWidget(QtGui.QLabel('f(w*)'), 2, 1) self.outputs['f(w*)'] = QtGui.QLabel() self.outputs['f(w*)'].setFont(QtGui.QFont("Ariel", 16)) outputLayout.addWidget(self.outputs['f(w*)'], 2, 2) outputLayout.addWidget(QtGui.QLabel('alpha'), 3, 1) self.outputs['alpha'] = QtGui.QDoubleSpinBox() self.outputs['alpha'].setSingleStep(0.01) self.outputs['alpha'].setMinimum(0) self.outputs['alpha'].setMaximum(1) self.outputs['alpha'].setFont(QtGui.QFont("Ariel", 16)) outputLayout.addWidget(self.outputs['alpha'], 3, 2) outputLayout.addWidget(self.change_rep_button, 3, 3) outputLayout.addWidget(self.find_alpha_button, 3, 4) # set layouts layout.addWidget(self.toolbar) layout.addWidget(self.randomize_button) layout.addLayout(inputLayout) layout.addLayout(outputLayout) layout.addWidget(self.plot_button) layout.addWidget(self.canvas) self.setLayout(layout) self.plotButton()
def test_power(output, refcdm, refb, ref_z, final=8): """Check the initial power against linear theory and a linearly grown IC power""" print('testing', output) pkcdm, pkb, z = compute_power(output) #Check types have the same power fig = Figure(figsize=(5, 5), dpi=200) canvas = FigureCanvasAgg(fig) ax = fig.add_subplot(121) pklin = LinearPower(WMAP9, redshift=z) D = WMAP9.scale_independent_growth_factor( z) / WMAP9.scale_independent_growth_factor(ref_z) ax.plot(pkcdm['k'][1:], pkcdm['power'][1:].real / pklin(pkcdm['k'][1:]), label=output + " DM") ax.plot(refcdm['k'][1:], refcdm['power'][1:].real * D**2 / pklin(refcdm['k'][1:]), ls="--", label='refcdm, linearly grown') ax.set_xscale('log') ax.set_ylim(0.8, 1.2) ax.legend() ax = fig.add_subplot(122) ax.plot(pkb['k'][1:], pkb['power'][1:].real / pklin(pkb['k'][1:]), ls="-.", label=output + " gas") ax.plot(refb['k'][1:], refb['power'][1:].real * D**2 / pklin(refb['k'][1:]), ls="--", label='refcdm gas, linearly grown') ax.set_xscale('log') ax.set_ylim(0.8, 1.2) ax.legend() fig.savefig(os.path.basename(output) + '.png') # asserting the linear growth is 1% accurate assert_allclose(pkcdm['power'][2:final], refcdm['power'][2:final] * D**2, rtol=0.012, atol=0.0) # Assert we agree with linear theory assert_allclose(pkcdm['power'][2:final], pklin(refcdm['k'])[2:final], rtol=0.025 * D**2, atol=0.0) # asserting the linear growth is 1% accurate assert_allclose(pkb['power'][2:final], refb['power'][2:final] * D**2, rtol=0.012, atol=0.0) # Assert we agree with linear theory assert_allclose(pkb['power'][2:final], pklin(refb['k'])[2:final], rtol=0.025 * D**2, atol=0.0)
def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear', preview=False): """ make a thumbnail of image in *infile* with output filename *thumbfile*. *infile* the image file -- must be PNG or PIL readable if you have `PIL <http://www.pythonware.com/products/pil/>`_ installed *thumbfile* the thumbnail filename *scale* the scale factor for the thumbnail *interpolation* the interpolation scheme used in the resampling *preview* if True, the default backend (presumably a user interface backend) will be used which will cause a figure to be raised if :func:`~matplotlib.pyplot.show` is called. If it is False, a pure image backend will be used depending on the extension, 'png'->FigureCanvasAgg, 'pdf'->FigureCanvasPdf, 'svg'->FigureCanvasSVG See examples/misc/image_thumbnail.py. .. htmlonly:: :ref:`misc-image_thumbnail` Return value is the figure instance containing the thumbnail """ basedir, basename = os.path.split(infile) baseout, extout = os.path.splitext(thumbfile) im = imread(infile) rows, cols, depth = im.shape # this doesn't really matter, it will cancel in the end, but we # need it for the mpl API dpi = 100 height = float(rows) / dpi * scale width = float(cols) / dpi * scale extension = extout.lower() if preview: # let the UI backend do everything import matplotlib.pyplot as plt fig = plt.figure(figsize=(width, height), dpi=dpi) else: if extension == '.png': from matplotlib.backends.backend_agg \ import FigureCanvasAgg as FigureCanvas elif extension == '.pdf': from matplotlib.backends.backend_pdf \ import FigureCanvasPdf as FigureCanvas elif extension == '.svg': from matplotlib.backends.backend_svg \ import FigureCanvasSVG as FigureCanvas else: raise ValueError("Can only handle " "extensions 'png', 'svg' or 'pdf'") from matplotlib.figure import Figure fig = Figure(figsize=(width, height), dpi=dpi) canvas = FigureCanvas(fig) ax = fig.add_axes([0, 0, 1, 1], aspect='auto', frameon=False, xticks=[], yticks=[]) basename, ext = os.path.splitext(basename) ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation) fig.savefig(thumbfile, dpi=dpi) return fig
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) # Position: convert from top-left anchor to center anchor canvas.create_image(loc[0] + figure_w / 2, loc[1] + figure_h / 2, image=photo) # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) # Return a handle which contains a reference to the photo object # which must be kept live or else the picture disappears return photo w, h = 300, 200 window = tk.Tk() window.title("A figure in a canvas") canvas = tk.Canvas(window, width=w, height=h) canvas.pack() fig = Figure(figsize=(2, 1)) a = fig.add_subplot(111) img_arr = mpimg.imread('paths0.png') a.imshow(img_arr) fig_x, fig_y = 100, 100 fig_photo = draw_figure(canvas, fig, loc=(fig_x, fig_y)) fig_w, fig_h = fig_photo.width(), fig_photo.height() tk.mainloop()
def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) super().__init__(fig)
def __init__(self, parent=None, width=6, height=6, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9) super().__init__(self.fig) self.fig.canvas.setFocusPolicy(Qt.ClickFocus) self.fig.canvas.setFocus()
def histogramButtonClicked(self): if not self.inputLoaded and not self.targetLoaded: # Error: "First load input and target images" in MessageBox QMessageBox.about(self, "Error", "First load input and target images") elif not self.inputLoaded: # Error: "Load input image" in MessageBox QMessageBox.about(self, "Error", "Load input image") elif not self.targetLoaded: # Error: "Load target image" in MessageBox QMessageBox.about(self, "Error", "Load target image") else: self.label3 = QLabel(self) self.boxLayout3 = QVBoxLayout(self.groupBox3) self.boxLayout3.addWidget(self.label3) # The image self.image1 = cv2.imread(self.imagePath) self.image2 = cv2.imread(self.imagePath2) self.h1 = histogram(self.image1) self.h2 = histogram(self.image2) c1_0 = cdf(self.h1[:, 0]) c2_0 = cdf(self.h2[:, 0]) c1_1 = cdf(self.h1[:, 1]) c2_1 = cdf(self.h2[:, 1]) c1_2 = cdf(self.h1[:, 2]) c2_2 = cdf(self.h2[:, 2]) LUT0 = lookup_table(c1_0, c2_0) LUT1 = lookup_table(c1_1, c2_1) LUT2 = lookup_table(c1_2, c2_2) out_im0 = histogram_match(LUT0, self.image1, 0) out_im1 = histogram_match(LUT1, self.image1, 1) out_im2 = histogram_match(LUT2, self.image1, 2) self.out_im = np.dstack((out_im0, out_im1, out_im2)) self.hist3 = histogram(self.out_im) self.out_im = np.divide(self.out_im, 255) self.output_image = self.out_im[..., ::-1] plt.imsave("outputt.png", self.output_image) self.pixmap3 = QPixmap("outputt.png") self.label3.setPixmap(self.pixmap3) # Histogram of image self.canvas6 = FigureCanvas(Figure(figsize=(5, 3))) self.canvas7 = FigureCanvas(Figure(figsize=(5, 3))) self.canvas8 = FigureCanvas(Figure(figsize=(5, 3))) self.boxLayout3.addWidget(self.canvas6) self.boxLayout3.addWidget(self.canvas7) self.boxLayout3.addWidget(self.canvas8) self.canvas6_plot = self.canvas6.figure.subplots() self.canvas6_plot.axes.bar(range(0, 256), self.hist3[:, 2], color="red") self.canvas6.draw() self.canvas7_plot = self.canvas7.figure.subplots() self.canvas7_plot.axes.bar(range(0, 256), self.hist3[:, 1], color="green") self.canvas7.draw() self.canvas8_plot = self.canvas8.figure.subplots() self.canvas8_plot.axes.bar(range(0, 256), self.hist3[:, 0], color="blue") self.canvas8.draw() self.label3.setAlignment(Qt.AlignCenter) self.label3.show()
def __init__(self, iface, parent=None): """Constructor.""" super(FlowEstimatorDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect #QDialog.__init__(self, None, Qt.WindowStaysOnTopHint) self.iface = iface self.setupUi(self) self.btnOk = self.buttonBox.button(QtGui.QDialogButtonBox.Ok) self.btnOk.setText("Save Data") self.btnClose = self.buttonBox.button(QtGui.QDialogButtonBox.Close) self.btnBrowse.clicked.connect(self.writeDirName) self.btnLoadTXT.clicked.connect(self.loadTxt) self.btnSampleLine.setEnabled(False) self.btnSampleSlope.setEnabled(False) self.calcType = 'Trap' # add matplotlib figure to dialog self.figure = Figure() self.axes = self.figure.add_subplot(111) self.figure.subplots_adjust(left=.1, bottom=0.15, right=.78, top=.9, wspace=None, hspace=.2) self.mplCanvas = FigureCanvas(self.figure) #self.widgetPlotToolbar = NavigationToolbar(self.mplCanvas, self.widgetPlot) #lstActions = self.widgetPlotToolbar.actions() #self.widgetPlotToolbar.removeAction(lstActions[7]) self.vLayout.addWidget(self.mplCanvas) self.vLayout.minimumSize() #self.vLayout.addWidget(self.widgetPlotToolbar) self.figure.patch.set_visible(False) # and configure matplotlib params # rcParams["font.serif"] = "Verdana, Arial, Liberation Serif" # rcParams["font.sans-serif"] = "Tahoma, Arial, Liberation Sans" # rcParams["font.cursive"] = "Courier New, Arial, Liberation Sans" # rcParams["font.fantasy"] = "Comic Sans MS, Arial, Liberation Sans" # rcParams["font.monospace"] = "Courier New, Liberation Mono" # #print self.cbDEM.changeEvent self.depth.valueChanged.connect(self.run) self.botWidth.valueChanged.connect(self.run) self.leftSS.valueChanged.connect(self.run) self.rightSS.valueChanged.connect(self.run) self.n.valueChanged.connect(self.run) self.slope.valueChanged.connect(self.run) self.cbWSE.valueChanged.connect(self.run) self.ft.clicked.connect(self.run) self.m.clicked.connect(self.run) self.cbUDwse.valueChanged.connect(self.run) self.manageGui() self.btnSampleLine.clicked.connect(self.sampleLine) self.btnSampleSlope.clicked.connect(self.sampleSlope)