def check_and_plot(self, A_nn, A0_nn, digits, keywords=''): # Construct fingerprint of input matrices for comparison fingerprint = np.array([md5_array(A_nn, numeric=True), md5_array(A0_nn, numeric=True)]) # Compare fingerprints across all processors fingerprints = np.empty((world.size, 2), np.int64) world.all_gather(fingerprint, fingerprints) if fingerprints.ptp(0).any(): raise RuntimeError('Distributed matrices are not identical!') # If assertion fails, catch temporarily while plotting, then re-raise try: self.assertAlmostEqual(np.abs(A_nn-A0_nn).max(), 0, digits) except AssertionError: if world.rank == 0 and mpl is not None: from matplotlib.figure import Figure fig = Figure() ax = fig.add_axes([0.0, 0.1, 1.0, 0.83]) ax.set_title(self.__class__.__name__) im = ax.imshow(np.abs(A_nn-A0_nn), interpolation='nearest') fig.colorbar(im) fig.text(0.5, 0.05, 'Keywords: ' + keywords, \ horizontalalignment='center', verticalalignment='top') from matplotlib.backends.backend_agg import FigureCanvasAgg img = 'ut_hsops_%s_%s.png' % (self.__class__.__name__, \ '_'.join(keywords.split(','))) FigureCanvasAgg(fig).print_figure(img.lower(), dpi=90) raise
def check_and_plot(self, A_nn, A0_nn, digits, keywords=''): # Construct fingerprint of input matrices for comparison fingerprint = np.array( [md5_array(A_nn, numeric=True), md5_array(A0_nn, numeric=True)]) # Compare fingerprints across all processors fingerprints = np.empty((world.size, 2), np.int64) world.all_gather(fingerprint, fingerprints) if fingerprints.ptp(0).any(): raise RuntimeError('Distributed matrices are not identical!') # If assertion fails, catch temporarily while plotting, then re-raise try: self.assertAlmostEqual(np.abs(A_nn - A0_nn).max(), 0, digits) except AssertionError: if world.rank == 0 and mpl is not None: from matplotlib.figure import Figure fig = Figure() ax = fig.add_axes([0.0, 0.1, 1.0, 0.83]) ax.set_title(self.__class__.__name__) im = ax.imshow(np.abs(A_nn - A0_nn), interpolation='nearest') fig.colorbar(im) fig.text(0.5, 0.05, 'Keywords: ' + keywords, \ horizontalalignment='center', verticalalignment='top') from matplotlib.backends.backend_agg import FigureCanvasAgg img = 'ut_hsops_%s_%s.png' % (self.__class__.__name__, \ '_'.join(keywords.split(','))) FigureCanvasAgg(fig).print_figure(img.lower(), dpi=90) raise
def draw_labels(figure: Figure, axes: Axes, y_label: str, label_rotation=90, axes_position='bottom'): # text and text parameters xlabel_text = r'$incubation\ time\ \slash\ days$' ylabel_text = y_label ylabel_rotation = label_rotation is_bottom = True if ('bottom' in axes_position or axes_position == 'single') else False # MRE notation, if is_bottom: MRE_notation_marks(axes) # add arrows where MRE was applied # remove x axis from top and middle axes if not is_bottom: axes.get_xaxis().set_visible(False) # x label figure.text(0.5, 0.03, xlabel_text, ha='center') # y label figure.text(0.05, 0.5, ylabel_text, va='center', rotation=ylabel_rotation) # legend axes.get_lines() handles = axes.get_lines() labels = SOILS figure.legend(handles, labels, 'center right')
def create_figure(drag_coef, sust_coef): ca = drag_coef rho = 1.2 A = 0.1 velocidades = np.linspace(0, 3.6 * 35, 3.6 * 36) cte = 0.5 * rho * A * ca cs = sust_coef cte_sus = 0.5 * rho * cs sustentacion = [] arrastre = [] for vel in velocidades: arrastre.append(vel * vel * cte) sustentacion.append(vel * vel * cte_sus) fig = Figure() axis = fig.add_subplot(1, 1, 1) axis.plot(velocidades, arrastre, color="blue", label="Fuerza de Arrastre") axis.plot(velocidades, sustentacion, color="red", label="Fuerza de Sustenación") fig.text(0.5, 0.04, 'Velocidad (km/h)', ha='center') fig.text(0, 0.5, 'Fuerza (N)', va='center', rotation='vertical') axis.title.set_text('Fuerza de Arrastre y Sustentación vs Velocidad') axis.legend(loc='upper left', frameon=True) return fig
def save_formula(formula: str, file: str): # This technically makes the text selectable, but "corrupts" it in a way that it produces an invalid formula # The fault is not with copy and paste, but is instead with this setting # plt.rcParams['svg.fonttype'] = 'none' fig = Figure(dpi=100) fig.text(0.5, 0.5, formula, fontsize=40) fig.savefig(file, bbox_inches="tight", facecolor=(0, 0, 0, 1))
def eq(code, **kwargs): from matplotlib.figure import Figure if "horizontalalignment" not in kwargs: kwargs["horizontalalignment"] = "center" if "verticalalignment" not in kwargs: kwargs["verticalalignment"] = "center" f = Figure(frameon=False) f.text(0.5, 0.5, code, **kwargs) return f
def _confidence_degree_patcher(figure: Figure, **kwargs): label = "DCIR" if "flat_table_name" in kwargs.keys(): label = kwargs["flat_table_name"] desc = "\n".join([ "{} in {}".format(", ".join(cols), single_table_name) for single_table_name, cols in _CNAM_COLS_MAPPING[label].items() ]) figure.text(0.95, 0.5, desc) figure.subplots_adjust(right=0.9)
def test_unicode_won(): fig = Figure() fig.text(.5, .5, r'\textwon', usetex=True) with BytesIO() as fd: fig.savefig(fd, format='svg') buf = fd.getvalue().decode('ascii') won_id = 'Computer_Modern_Sans_Serif-142' assert re.search(r'<path d=(.|\s)*?id="{0}"/>'.format(won_id), buf) assert re.search(r'<use[^/>]*? xlink:href="#{0}"/>'.format(won_id), buf)
def eq(code, **kwargs): from matplotlib.figure import Figure import matplotlib.pyplot as plt plt.rc('text', usetex=True) plt.rc('font', family='serif') if "horizontalalignment" not in kwargs: kwargs["horizontalalignment"] = "center" if "verticalalignment" not in kwargs: kwargs["verticalalignment"] = "center" f = Figure(frameon=False) f.text(0.5, 0.5, code, **kwargs) return f
def button_click(i,j): shelf=6-int(i)/2 row=int(j)+1 location=shelf*100+row*10+1 c = db.cursor() db.begin() query_0=("select Date_and_Time,Temperature,Target_Time from test1 where Location=%s",[location]) c.execute(*query_0) result_0=c.fetchall() c.close() entry_time=result_0[0][0] Ti=result_0[0][1] target_time=result_0[0][2] time_left= 23 current_temp=52 label[0][5]=Label(my_window,width = '20', height = '3',text=Ti, bd=10,bg = 'white',anchor='w') label[2][5]=Label(my_window,width = '20', height = '3',text=entry_time, bd=10,bg = 'white',anchor='w') label[3][5]=Label(my_window,width = '20', height = '3',text=target_time, bd=10,bg = 'white',anchor='w') label[4][5]=Label(my_window,width = '20', height = '3',text=time_left, bd=10,bg = 'white',anchor='w') label[5][5]=Label(my_window,width = '20', height = '3',text=current_temp, bd=10,bg = 'white',anchor='w') label[0][5].grid(row=0,column=5) label[2][5].grid(row=2,column=5) label[3][5].grid(row=3,column=5) label[4][5].grid(row=4,column=5) label[5][5].grid(row=5,column=5) z=int(cooling_time(Ti)) Re = 5000 Pr = 0.71 Nu = 0.3 + ((0.62*(Re**0.5)*(Pr**(1/3)))/(1+(0.4*Pr**(2/3)))**0.25)+(1+(Re/282000)**5/8)**(4/5) k = 0.17 #W.m^-1.k^-1 d = 0.04 #m h = Nu*k/d #W.m^2.k^-1 Tamb = 10 #k a_conv = 5.38*10**(-3) #m^2 v = 2.87*10**(-5) #m^3 d = 1070 #kg.m^-3 c = 1432.512 #J.k^-1 b=h*a_conv/(d*v*c) x = [i for i in range(z)] y = [2*math.exp(b*(z-i))+10 for i in x] plt.title('Cooling curve') plt.xlabel('Time (sec)') plt.ylabel('Temp (deg C)') fig=Figure(figsize=(5,4),dpi=100) ax=fig.add_subplot(111).plot(x,y) fig.text(0.5, 0.04, 'Time (sec)', ha='center', va='center') fig.text(0.06, 0.5, 'Temp (deg C)', ha='center', va='center', rotation='vertical') canvas=FigureCanvasTkAgg(fig,master=my_window) canvas.draw() canvas.get_tk_widget().grid(row=2,column=6,rowspan=6)
def label_grid(self, fig: Figure, axes: Sequence[Axes]): x_center = mean([get_pos(axes[0, 0]).xmin, get_pos(axes[0, -1]).xmax]) y_center = mean([get_pos(axes[0, 0]).ymax, get_pos(axes[-2, 0]).ymin]) kwargs = dict(ha="center", va="center", fontsize=22) fig.text(x_center, 0.01, self.xlabel, **kwargs) fig.text( 0.03, y_center, self.ylabel, **kwargs, rotation=90, rotation_mode="anchor", )
def test_unicode_won(): fig = Figure() fig.text(.5, .5, r'\textwon', usetex=True) with BytesIO() as fd: fig.savefig(fd, format='svg') buf = fd.getvalue() tree = xml.etree.ElementTree.fromstring(buf) ns = 'http://www.w3.org/2000/svg' won_id = 'SFSS3583-8e' assert len(tree.findall(f'.//{{{ns}}}path[@d][@id="{won_id}"]')) == 1 assert f'#{won_id}' in tree.find(f'.//{{{ns}}}use').attrib.values()
def getQPixmap4Variable(self): guardFig = Figure(figsize=(2.5, 0.4)) canvas = FigureCanvas(guardFig) strData=self.boxName try: guardFig.text(0.1,0.3, strData, fontsize=10) except: pass canvas.draw() size = canvas.size() width, height = size.width(), size.height() im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32) return QPixmap(im)
def getQPixmap4Reset(self): guardFig = Figure(figsize=(5, 0.4)) canvas = FigureCanvas(guardFig) strData = self.reset try: guardFig.text(0.1, 0.3, strData, family="Consolas", fontsize=10) except: pass canvas.draw() size = canvas.size() width, height = size.width(), size.height() im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32) return QPixmap(im)
class CMdisplay(): def show_colormaps(self): screen_height = self.ico_frame.winfo_screenheight() try: plt.close(self._f_ic) except AttributeError: pass try: self._ic_canvas.delete(ALL) except AttributeError: pass # self._f_ci = Figure(facecolor = [0.95,0.95,0.96], figsize=(5,10)) self._f_ci = Figure(facecolor=[0.95, 0.95, 0.96]) self._f_ci.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99) a = np.linspace(0, 2, 256).reshape(1, -1) a = np.vstack((a, a)) # Get a list of the colormaps in matplotlib. Ignore the ones that end with # '_r' because these are simply reversed versions of ones that don't end # with '_r' maps_0 = sorted(m for m in plt.cm.datad if not m.endswith("_r")) if screen_height <= 1000: maps = [maps_0[n] for n in np.arange(0, len(maps_0), step=2)] else: maps = maps_0 nmaps = len(maps) + 1 self._colormap_options['Available'] = maps for i, m in enumerate(maps): ax = self._f_ci.add_subplot(nmaps, 1, i + 1) ax.axis("off") ax.imshow(a, aspect='auto', cmap=plt.get_cmap(m), origin='lower') pos = list(ax.get_position().bounds) self._f_ci.text(pos[0] - 0.01, pos[1], m, fontsize=10, horizontalalignment='right') self._ic_canvas = FigureCanvasTkAgg(self._f_ci, master=self.ico_frame) self._ic_frame_canvas = self._ic_canvas.get_tk_widget() self._ic_frame_canvas.grid(row=0, column=0, sticky='nsew') self._ic_canvas.draw()
def text_to_rgba(s, *, dpi, **kwargs): # To convert a text string to an image, we can: # - draw it on an empty and transparent figure; # - save the figure to a temporary buffer using ``bbox_inches="tight", # pad_inches=0`` which will pick the correct area to save; # - load the buffer using ``plt.imread``. # # (If desired, one can also directly save the image to the filesystem.) fig = Figure(facecolor="none") fig.text(0, 0, s, **kwargs) buf = BytesIO() fig.savefig(buf, dpi=dpi, format="png", bbox_inches="tight", pad_inches=0) buf.seek(0) rgba = plt.imread(buf) return rgba
class Equation_display: def __init__(self, parent, fgs, port): self.fig = Figure((2, 0.5), 75) self.canvas = FigureCanvas(parent, -1, self.fig) self.fig.text(0.05, 0.5, "$%s$" % port.name, size=10) sizer = wx.BoxSizer(wx.HORIZONTAL) self.canvas.draw() sizer.Add(self.canvas, 7, wx.ALIGN_CENTRE | wx.LEFT) fgs.Add(sizer, 0, wx.TOP | wx.EXPAND)
def buildMetadataImage(self, layerInfoList, width): """ Creates the metadata caption for figures in styles that display a title only. """ # Find first non-outline layer. nonOutlineLayers = [l for l in layerInfoList if l.id != outline_layer.OUTLINE_LAYER_ID] layerInfo = nonOutlineLayers[0] if len(nonOutlineLayers) > 0 else None # Get the title of the first set of keyword data, i.e., that for the layer rather than one # of its antecedent layers or datasets. titleText = '' if layerInfo and (len(layerInfo.keywordData) > 0): titleText = layerInfo.keywordData[0].get('title', '') height = 500 dpi = 100 transparent = False figsize = (width / float(dpi), height / float(dpi)) fig = Figure(figsize=figsize, dpi=dpi, facecolor='w', frameon=(not transparent)) renderer = Renderer(fig.dpi) text = fig.text(0.5, 0.98, titleText, fontdict=titleFont, horizontalalignment='center', verticalalignment='top') # Trim the height of the text image. extent = text.get_window_extent(renderer) textHeight = (extent.y1 - extent.y0 + 8) fig.set_figheight(textHeight / float(dpi)) return image_util.figureToImage(fig)
def test_text_specific(): """This text is for considering some specific special strings.""" np.random.seed(19680801) # TODO ss = ['', ' ', '\n'] # Other whitespaces are unprintable in DejaVu. has = ['center', 'right', 'left'] mas = ['center', 'right', 'left'] rotation_modes = ['default', 'anchor'] vas = ['top', 'bottom', 'center', 'baseline', 'center_baseline'] fig = Figure() renderer = FigureCanvasAgg(fig).get_renderer() for s in ss: for i in range(100): x = np.random.rand() y = np.random.rand() ha = np.random.choice(has) ma = np.random.choice(mas) va = np.random.choice(vas) r = np.random.rand() * 360.0 rotation_mode = np.random.choice(rotation_modes) t = fig.text(x, y, s, ha=ha, ma=ma, va=va, rotation=r, rotation_mode=rotation_mode) points = _get_points_surrounding_text(t, renderer) bbox = t.get_window_extent(renderer) np.testing.assert_almost_equal(np.min(points[:, 0]), bbox.x0) np.testing.assert_almost_equal(np.max(points[:, 0]), bbox.x1) np.testing.assert_almost_equal(np.min(points[:, 1]), bbox.y0) np.testing.assert_almost_equal(np.max(points[:, 1]), bbox.y1)
def test_text_random(): np.random.seed(19680801) a = list(string.digits + string.ascii_letters + string.punctuation.replace('$', '') # To avoid the math mode + ' \n') # Other whitespaces are unprintable in DejaVu has = ['center', 'right', 'left'] mas = ['center', 'right', 'left'] rotation_modes = ['default', 'anchor'] vas = ['top', 'bottom', 'center', 'baseline', 'center_baseline'] fig = Figure() renderer = FigureCanvasAgg(fig).get_renderer() for i in range(100): x = np.random.rand() y = np.random.rand() n = np.random.randint(20) s = ''.join(np.random.choice(a, n)) ha = np.random.choice(has) ma = np.random.choice(mas) va = np.random.choice(vas) r = np.random.rand() * 360.0 rotation_mode = np.random.choice(rotation_modes) t = fig.text(x, y, s, ha=ha, ma=ma, va=va, rotation=r, rotation_mode=rotation_mode) points = _get_points_surrounding_text(t, renderer) bbox = t.get_window_extent(renderer) np.testing.assert_almost_equal(np.min(points[:, 0]), bbox.x0) np.testing.assert_almost_equal(np.max(points[:, 0]), bbox.x1) np.testing.assert_almost_equal(np.min(points[:, 1]), bbox.y0) np.testing.assert_almost_equal(np.max(points[:, 1]), bbox.y1)
class UIInt(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, title=PICHI_STR, size=(400, 300)) self.funpanel = wx.Panel(self, -1) self.initSizers() self.initCanvas() self.initCtrls() self.SetBackgroundColour("#FFFFFF") self.Centre(1) self.Show() def initSizers(self): self.mainsz = wx.BoxSizer(wx.VERTICAL) self.funsz = wx.BoxSizer(wx.HORIZONTAL) self.funpanel.SetSizer(self.funsz) self.SetSizer(self.mainsz) def initCtrls(self): self.funlabel = wx.StaticText(self.funpanel, -1, " f(x) ") self.fun = wx.TextCtrl(self.funpanel, -1, "") self.boton = wx.Button(self, -1, "Integrar", size=(100, 25)) # Fonts font1 = self.funlabel.GetFont() font1.SetPointSize(12) self.funlabel.SetFont(font1) self.fun.SetFont(font1) self.fun.SetForegroundColour((0, 0, 255)) self.funsz.Add(self.funlabel, 1, wx.EXPAND | wx.ALL, 5) self.funsz.Add(self.fun, 7, wx.EXPAND | wx.ALL, 5) self.mainsz.Add(self.funpanel, 1, wx.EXPAND | wx.ALL, 5) self.mainsz.Add(self.canvas, 6, wx.EXPAND | wx.ALL, 5) self.mainsz.Add(self.boton, 0, wx.ALIGN_CENTRE | wx.ALL, 5) self.Bind(wx.EVT_BUTTON, self.integrar, self.boton) def initCanvas(self): self.figure = Figure() # FigureCanvas self.canvas = FigureCanvas(self, -1, self.figure) self.figure.set_facecolor((1, 1, 1)) self.string = self.figure.text(0.05, 0.5, "") self.string.set_fontsize(18) def integrar(self, event): x = sympy.Symbol("x") fx = self.fun.GetValue() # Función original fx = preproc(fx) Fx = sympy.integrate(eval(fx)) # Función integrada str_Fx = "$\int \, (%s) \,dx \,= \,%s + C$" % (sympy.latex( eval(fx)), sympy.latex(Fx)) self.string.set_text(str_Fx) self.canvas.draw()
class GraficaPanel(wx.Panel): def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) self.parent = parent self.ig = datetime.datetime.now() self.marcador = False self.figure = Figure(facecolor='darkslategray') self.axes = self.figure.add_subplot(111) self.axes.get_yaxis().set_visible(False) self.figure.text(0.5, 0.02, 'tiempo', ha='center', va='center') self.axes.grid() self.canvas = FigureCanvas(self, 0, self.figure) self.figure.tight_layout() self.dinamicas = None mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(self.canvas, 0, wx.EXPAND | wx.ALL) self.SetSizer(mainSizer) def graficado(self, s, inicio_grabacion): print 'dentro graficado' self.ig = inicio_grabacion def timeTicks(x, pos): d = (self.ig + datetime.timedelta(seconds=x)).time() return str(d) segmento = s.readframes(s.getnframes()) duracion_archivo = int(np.round(s.getnframes() / float(s.getframerate()))) data = np.fromstring(segmento, np.int16) samples = data[0::32768] ejetiempo = np.linspace(0, duracion_archivo, num=len(samples)) self.axes.set_xlim([0, duracion_archivo]) formatter = ticker.FuncFormatter(timeTicks) self.axes.xaxis.set_major_formatter(formatter) self.axes.plot(ejetiempo, samples) self.canvas.draw() self.dinamicas = GraficaDinamica(self, fig=self.canvas.figure) self.dinamicas.show() def marcable(self): self.marcador = True
def plot(data_file, invert_x=True, log_y=True, level='', text_color='#07529a'): with tb.open_file(data_file, 'r') as f: data = f.root.raw_data[:] run_config = ConfigDict(f.root.configuration.run_config[:]) x, y, yerr = [], [], [] for d in data: x.append(d[0]) y.append(abs(d[1])) yerr.append(d[2]) fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) fig.subplots_adjust(top=0.85) y_coord = 0.92 chip_type = run_config['chip_type'] fig.text(0.1, y_coord, '{0} {1}'.format(chip_type, level), fontsize=12, color=text_color, transform=fig.transFigure) identifier = run_config['module'] fig.text(0.65, y_coord, 'Module: {0}'.format(identifier), fontsize=12, color=text_color, transform=fig.transFigure) ax.errorbar(x, y, yerr=yerr, linestyle='none', marker='.', color='C0') ax.set_title('Sensor IV curve', color=text_color) ax.set_xlabel('Bias voltage [V]') ax.set_ylabel('Leakage current [A]') ax.grid() if invert_x: ax.invert_xaxis() if log_y: ax.set_yscale('log') fig.savefig(data_file[:-3] + '.pdf')
def getQImage4Invariant(self): InvariantFig = Figure(figsize=(2.5, 0.4)) canvas = FigureCanvas(InvariantFig) strData = self.invariant try: InvariantFig.text(0.1, 0.3, strData, family="Consolas", fontsize=10) except: pass canvas.draw() size = canvas.size() width, height = size.width(), size.height() im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32) return im
class UIInt(wx.Frame): def __init__(self,parent): wx.Frame.__init__(self,parent,title=PICHI_STR,size=(400,300)) self.funpanel = wx.Panel(self, -1) self.initSizers() self.initCanvas() self.initCtrls() self.SetBackgroundColour("#FFFFFF") self.Centre(1) self.Show() def initSizers(self): self.mainsz = wx.BoxSizer(wx.VERTICAL) self.funsz = wx.BoxSizer(wx.HORIZONTAL) self.funpanel.SetSizer(self.funsz) self.SetSizer(self.mainsz) def initCtrls(self): self.funlabel = wx.StaticText(self.funpanel, -1, " f(x) ") self.fun = wx.TextCtrl(self.funpanel, -1, "") self.boton = wx.Button(self, -1, "Integrar", size=(100,25)) # Fonts font1 = self.funlabel.GetFont() font1.SetPointSize(12) self.funlabel.SetFont(font1) self.fun.SetFont(font1) self.fun.SetForegroundColour((0,0,255)) self.funsz.Add(self.funlabel, 1, wx.EXPAND|wx.ALL, 5) self.funsz.Add(self.fun, 7, wx.EXPAND|wx.ALL, 5) self.mainsz.Add(self.funpanel, 1, wx.EXPAND|wx.ALL, 5) self.mainsz.Add(self.canvas, 6, wx.EXPAND|wx.ALL, 5) self.mainsz.Add(self.boton, 0, wx.ALIGN_CENTRE|wx.ALL, 5) self.Bind(wx.EVT_BUTTON, self.integrar, self.boton) def initCanvas(self): self.figure = Figure() # FigureCanvas self.canvas = FigureCanvas(self, -1, self.figure) self.figure.set_facecolor((1,1,1)) self.string = self.figure.text(0.05, 0.5, "") self.string.set_fontsize(18) def integrar(self,event): x = sympy.Symbol("x") fx = self.fun.GetValue() # Función original fx = preproc(fx) Fx = sympy.integrate(eval(fx)) # Función integrada str_Fx = "$\int \, (%s) \,dx \,= \,%s + C$"%(sympy.latex(eval(fx)), sympy.latex(Fx)) self.string.set_text(str_Fx) self.canvas.draw()
def getPlots(self, startDate, endDate): plt.ioff() inferno = self.getData(startDate, endDate) ######################################## #plot data ######################################## figure = Figure(figsize=(10, 12)) FigureCanvas(figure) #make subplots axes = figure.add_subplot(4, 1, 1) inferno.OverflowRate.plot(legend=True, ax=axes) axes.set_ylabel("l/s") axes.set_xlabel("Timestamp UTC") axes = figure.add_subplot(4, 1, 2) inferno.OverflowTemp.plot(legend=True, ax=axes) axes.set_ylabel("degC") axes.set_xlabel("Timestamp UTC") axes.set_ylim([-10, 110]) axes = figure.add_subplot(4, 1, 3) inferno.InfernoRL.plot(legend=True, ax=axes) axes.set_ylabel("m") axes.set_xlabel("Timestamp UTC") axes = figure.add_subplot(4, 1, 4) inferno.InfernoTemp.plot(legend=True, ax=axes) axes.set_ylabel("degC") axes.set_xlabel("Timestamp UTC") axes.set_ylim([-10, 110]) #create a time plot drawn label timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") figure.text(0, 0, 'Plot drawn: ' + str(timestamp)) figure.subplots_adjust(hspace=1.0) imageBuffer = io.BytesIO() figure.savefig(imageBuffer, format='png') return imageBuffer.getvalue()
def plot_png(): """ Renders the plot on the fly. """ # calculating num_reviews_A, k_A, num_reviews_B, k_B = session.get('beta_params') p_scan = np.linspace(0, 1, 201) pdf_A = beta.pdf(p_scan, k_A + 1, num_reviews_A - k_A + 1) pdf_B = beta.pdf(p_scan, k_B + 1, num_reviews_B - k_B + 1) expected_rating_A = (k_A + 1) / (num_reviews_A + 2) expected_rating_B = (k_B + 1) / (num_reviews_B + 2) beta_max = max([max(pdf_A), max(pdf_B)]) # plotting fig = Figure() axis = fig.add_subplot(1, 1, 1, position=(0.1, 0.2, 0.8, 0.7)) axis.plot(p_scan * 100, pdf_A, label='A', c='b') axis.plot(p_scan * 100, pdf_B, label='B', c='r') axis.vlines(expected_rating_A * 100, 0, beta_max, colors='b', linestyles='--') axis.vlines(expected_rating_B * 100, 0, beta_max, colors='r', linestyles='--') axis.set_xlabel('Actual Rating (%)') axis.set_ylabel('Relative Probability') axis.set_title('Relative Probabilities of Possible Actual Rating') axis.legend(loc='best') fig.text(.5, .05, "Dashed lines indicate expected actual rating", ha='center') output = io.BytesIO() FigureCanvasAgg(fig).print_png(output) return Response(output.getvalue(), mimetype="image/png")
def plot_ct_curves(processing_results: ProcessingResults): """plot ct curves per well in 96 well plate""" well_results = processing_results.well_results protocol = processing_results.protocol quant_amp_data = processing_results.quant_amp_data fig = Figure(figsize=(10.5, 6)) max_y = dict() gene_text = dict() for fluor in protocol.mapping: fluor_genes = set(protocol.mapping[fluor].values()).intersection( protocol.gene_cutoffs) max_y[fluor] = nice(quant_amp_data[fluor], protocol.mapping[fluor], fluor_genes) gene_text[fluor] = f"{fluor} ({', '.join(sorted(fluor_genes))})" max_fluors = " ".join( f"{g_text} normalized to {int(round(max_y[fluor], 0))}" for fluor, g_text in gene_text.items()) fig.text(x=0.5, y=0.9, s=max_fluors, ha="center", fontsize=8) for well_id, ax in _plot_96_wells(fig, (1, )): for fluor in protocol.mapping: for idx, gene in protocol.mapping[fluor].items(): if gene not in protocol.gene_cutoffs: continue # Map a well_id and idx from 96-well plate to the corresponding # well on the 384 well plate. well_384 = MAP_96_TO_384_NO_PAD[well_id][idx] ax.plot( quant_amp_data[fluor]["Cycle"], np.clip(quant_amp_data[fluor][well_384] / max_y[fluor], 0, None), label=gene, alpha=0.8, ) add_call(ax, well_results[well_id].call) return fig
def plot(self): #x=np.linspace(-gap,gap,gap*2*fs/1000) gap_ms = self.gap / (self.fs / 1000) if self.peak_time_manual < self.gap: time = np.linspace(-self.peak_time_manual / (self.fs / 1000), gap_ms, self.cutout_raw.shape[0]) y_thr = np.linspace(self.threshold, self.threshold, self.cutout_raw.shape[0]) else: time = np.linspace(-gap_ms, gap_ms, gap_ms * 2 * (self.fs / 1000)) y_thr = np.linspace(self.threshold, self.threshold, gap_ms * 2 * (self.fs / 1000)) fig = Figure(figsize=(10, 8)) raw = fig.add_subplot(3, 1, 1) raw.plot(time, self.cutout_raw, color='black', label='raw_signal') raw.legend(loc='upper left') ripple = fig.add_subplot(3, 1, 2) ripple.plot(time, self.cutout_ripple, color='blue', label='ripple_filtered_signal') ripple.legend(loc='upper left') enve = fig.add_subplot(3, 1, 3) enve.plot(time, self.cutout_enve, color='orange', label='Hilbert_transformed_signal') enve.plot(time, y_thr) enve.legend(loc='upper left') peak_time_sec = self.peak_time_manual / (self.fs) fig.text(0.45, 0.03, 'Time of ripple peak in sec: %f' % peak_time_sec, fontsize=20) width = self.window.winfo_screenwidth() height = self.window.winfo_screenheight() self.window.geometry("%dx%d" % (width, height)) self.window.state('zoomed') canvas = FigureCanvasTkAgg(fig, master=self.window) canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1) canvas.show()
def graph(): Ti = 25 Ti = int(Ti) z = int(cooling_time(Ti)) Re = 5000 Pr = 0.71 Nu = 0.3 + ((0.62 * (Re**0.5) * (Pr**(1 / 3))) / (1 + (0.4 * Pr**(2 / 3)))**0.25) + (1 + (Re / 282000)**5 / 8)**(4 / 5) k = 0.17 #W.m^-1.k^-1 d = 0.04 #m h = Nu * k / d #W.m^2.k^-1 Tamb = 10 #k a_conv = 5.38 * 10**(-3) #m^2 v = 2.87 * 10**(-5) #m^3 d = 1070 #kg.m^-3 c = 1432.512 #J.k^-1 b = h * a_conv / (d * v * c) x = [i for i in range(z)] y = [2 * math.exp(b * (z - i)) + 10 for i in x] plt.title('Cooling curve') plt.xlabel('Time') plt.ylabel('Temp') # fig,ax=plt.subplots(nrows=1,ncols=1) # ax.plot(x,y) # fig.savefig('/home/pi/testImg.png') # plt.close(fig) # img=PhotoImage(file="testImg.png") # label[0][6]=Label(my_window,image=img) # label[0][6].grid(row=6,column=6,rowspan=6,columnspan=2) fig = Figure(figsize=(5, 4), dpi=100) ax = fig.add_subplot(111).plot(x, y) fig.text(0.5, 0.04, 'Time', ha='center', va='center') fig.text(0.06, 0.5, 'Temp', ha='center', va='center', rotation='vertical') #ax.set_title('Cooling curve') canvas = FigureCanvasTkAgg(fig, master=my_window) canvas.draw() canvas.get_tk_widget().grid(row=2, column=6, rowspan=6)
def getQImage4Equation(self): iEditLine = len(self.equation) iHeight = 1.0 iWidth = 2.5 #if (iEditLine>4): # iHeight=0.2*(iEditLine-4)+1; if hasattr(self, 'rect'): # if self.rect.height()>100: # iHeight=self.rect.height()/100.0 if self.rect.width() > 200: iWidth = 2.5 * self.rect.width() / 200 InvariantFig = Figure(figsize=(iWidth, iHeight)) canvas = FigureCanvas(InvariantFig) SympyLines = [] for i in range(iEditLine): strData = self.equation[i] try: if '=' in strData: str1 = strData.split('=') leftEquation = str1[0].replace('$', '') rightEquation = str1[1].replace('$', '') strLeftEquation = str(process_sympy(leftEquation)) strRightEquation = str(process_sympy(rightEquation)) SympyLines.append('='.join( [strLeftEquation, strRightEquation])) InvariantFig.text(0.1, iHeight - 0.2 * (i + 1), strData, fontsize=10) except Exception as e: SympyLines.append(strData + "Error:" + str(e)) # print (str(e)) #try: # InvariantFig.text(0.1,iHeight-0.2*(i+1), strData,family="Consolas", fontsize=10) #except: # pass canvas.draw() size = canvas.size() width, height = size.width(), size.height() im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32) return im
def GetPixmap(self, text): iEditLine = len(text) iHeight = 1 if (iEditLine > 4): iHeight = 0.2 * (iEditLine - 4) + 1 InvariantFig = Figure(figsize=(5, iHeight)) canvas = FigureCanvas(InvariantFig) for i in range(iEditLine): strData = text[i] InvariantFig.text(0.1, iHeight - 0.2 * (i + 1), strData, fontsize=10) canvas.draw() size = canvas.size() width, height = size.width(), size.height() im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32) return QPixmap(im)
def generate_svg(self, raw_tex): fig = Figure(figsize=(5, 4), dpi=300) canvas = FigureCanvasAgg(fig) fig.text(.5, .5, r"$" + raw_tex + r"$", fontsize=40) fig.savefig("output.svg", bbox_inches="tight", facecolor=(1, 1, 1, 0)) self.svg.load("output.svg") renderer = QSvgRenderer('output.svg').defaultSize() w = renderer.width() h = renderer.height() if w / h > 578 / 200: display_w = 578 display_h = int(578 * h / w) else: display_h = 200 display_w = int(200 * w / h) self.svg.setFixedWidth(display_w) self.svg.setFixedHeight(display_h) self.svg.setGeometry( QRect(289 - int(display_w / 2), 100 - int(display_h / 2), display_w, display_h))
def render_to_response(self, context): """Create a png image and write the control chart image to it""" fig = Figure(dpi=72, facecolor="white") dpi = fig.get_dpi() fig.set_size_inches( self.get_number_from_request("width", 700) / dpi, self.get_number_from_request("height", 480) / dpi, ) canvas = FigureCanvas(fig) dates, data = [], [] if context["data"] and context["data"].values(): name, points = context["data"].items()[0] dates, data = zip(*[(ti["date"], ti["value"]) for ti in points]) n_baseline_subgroups = self.get_number_from_request("n_baseline_subgroups", 2, dtype=int) n_baseline_subgroups = max(2, n_baseline_subgroups) subgroup_size = self.get_number_from_request("subgroup_size", 2, dtype=int) if not (1 < subgroup_size < 100): subgroup_size = 1 include_fit = self.request.GET.get("fit_data", "") == "true" response = HttpResponse(mimetype="image/png") if n_baseline_subgroups < 1 or n_baseline_subgroups > len(data) / subgroup_size: fig.text(0.1, 0.9, "Not enough data for control chart", fontsize=20) canvas.print_png(response) else: try: control_chart.display(fig, numpy.array(data), subgroup_size, n_baseline_subgroups, fit=include_fit, dates=dates) fig.autofmt_xdate() canvas.print_png(response) except (RuntimeError, OverflowError) as e: # pragma: nocover fig.clf() msg = "There was a problem generating your control chart:\n%s" % str(e) fig.text(0.1, 0.9, "\n".join(textwrap.wrap(msg, 40)), fontsize=12) canvas.print_png(response) return response
def fig_plot(frame, tarr, parr, nshot, y_ticks=[], col='#c00000', ylbl=''): fig = Figure(figsize=(8.2, 8.2), dpi=100) can = FigureCanvasTkAgg(fig, master=frame) can._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) fig.subplots_adjust(left=0.1, bottom=0.1, right=0.95, top=0.92, hspace=0) fig.text(.5, .95, '#%d' %nshot, ha='center') nsrc = parr.shape[1] for jx in range(nsrc): ax = fig.add_subplot(8, 1, jx+1) ax.plot(tarr, parr[:, jx], color=col) ax.set_ylabel('%s%d' %(ylbl, jx+1), fontsize=fsize) ax.set_yticks(y_ticks) ax.ticklabel_format(axis='y', style='sci', scilimits=(-4,-4)) ax.yaxis.major.formatter._useMathText = True if jx < nsrc-1: ax.tick_params(axis='x', which='both', bottom='on', top='on', labelbottom='off') ax.set_xlabel('Time [s]', fontsize=fsize) can.mpl_connect('button_press_event', fconf.on_click) toolbar = NavigationToolbar2TkAgg(can, frame) toolbar.update()
def buildDetailsImage(self, layerInfoList, width): """ Creates the metadata details for figures using templates. """ # Find first non-outline layer. nonOutlineLayers = [l for l in layerInfoList if l.id != outline_layer.OUTLINE_LAYER_ID] layerInfo = nonOutlineLayers[0] if len(nonOutlineLayers) > 0 else None # Flatten the keyword dictionaries, giving priority to entries from descendants over # antecedents. keywordData = {} if layerInfo: for kw in reversed(layerInfo.keywordData): keywordData.update(kw) detailsText = caption_manager.getCaption(layerInfo, keywordData) height = 500 dpi = 100 transparent = False figsize = (width / float(dpi), height / float(dpi)) fig = Figure(figsize=figsize, dpi=dpi, facecolor='w', frameon=(not transparent)) renderer = Renderer(fig.dpi) text = fig.text(0.02, 0.98, detailsText, fontdict=metadataFont, horizontalalignment='left', verticalalignment='top') # Trim the height of the text image. extent = text.get_window_extent(renderer) textHeight = (extent.y1 - extent.y0 + 8) fig.set_figheight(textHeight / float(dpi)) return image_util.figureToImage(fig)
def plotResults(request, image_id): import os import tempfile os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp() from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np fig = Figure() ax=fig.add_subplot(3,1,1) if Original_nrrd.objects.filter(image=image_id).count() > 0: records = Original_nrrd.objects.filter(image=image_id).values() chanCol = ['red','green','blue'] for record in records: i = int(record['channel']) ax=fig.add_subplot(3,1,i) hist = list(record['pre_hist']) k = range(0,len(hist)) v = [long(y) for y in hist] m = int(record['new_min']) M = int(record['new_max']) ax.fill([m,M,M,m], [np.min(v),np.min(v),np.max(v),np.max(v)], 'cyan', fill=True, hatch='/', edgecolor="grey") # ax.broken_barh([(m, (M-m))] , (ax.yaxis, (np.max(v)-np.min(v))), facecolors='grey') ax.bar(k, v, color=chanCol[i-1])#, log=True ax.set_xlim(0,260) ax.set_ylim(0,np.max(v)) ax.set_yscale('symlog', linthreshx=np.average(v)) ax.grid(True) gc.collect() ax.set_title('Ch' + str(i) + ' histogram', fontsize=14, color=chanCol[i-1]) else: fig.text(0.3,0.5,'No Data Found!', fontsize=32) fig.text(0.5, 0.015, 'Intensity', ha='center', va='center') fig.text(0.015, 0.5, 'Count (log)', ha='center', va='center', rotation='vertical') fig.tight_layout() canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/png') gc.collect() canvas.print_png(response) return response
def eigshow(matrix = None): """ Main function to plot eigshow. Usage: eigshow() or eigshow(A) where, A is a Numpy 2x2 matrix or array. When no aguments are passed to eigshow(), it starts with a default matrix A = np.matrix([[1/4,3/4],[1,2/4]]) and one can choose several other matrices using the "Select Matrix" menu on the top menu panel. When A is given, eigshow starts with the given matrix. """ global line1old, line2old, text1old, text2old, line3old, line4old, text3old global text4old, egv1, egv2, singv1, singv2, egv1txt, egv2txt, indTxt global svd1txt, svd2txt, bSVD, svdVis, oldModeText, tlr, redrawCount global root, A, fig, ax bSVD = False # svd mode or not (initially set to eigen mode) svdVis = False # Visibility of lines for svd mode (not visible in eigen mode) tlr = 0.75 # text on line position ratio redrawCount = 0 if matrix is None: # The matrix (initial matrix) A = np.matrix([[1/4, 3/4], [1, 2/4]]) # matrixList[4] else: A = np.matrix(matrix) root = Tk.Tk() root.wm_title('eigshow') # Create a toplevel menu (for selecting matrices) menubar = Tk.Menu(root) # Create the Matrix pulldown menu, and add it to the menubar filemenu = Tk.Menu(menubar, tearoff=0) for i, mat in enumerate(matrixList): expression = 'filemenu.add_command(label=mat,command=lambda: selectMatrix({}))'.format(i) eval(expression) menubar.add_cascade(label="Select Matrix", menu=filemenu) # Display the menu root.config(menu=menubar) # Create a figure and an axes within it fig = Figure(facecolor='w') ax = fig.add_subplot(111) # a tk drawing area canvas = FigureCanvasTkAgg(fig, master=root) # no resize callback as of now canvas.get_tk_widget().pack(side=Tk.BOTTOM) # Connect redrawPlot callback function to mouse-click event fig.canvas.mpl_connect('button_press_event', redrawPlot) # buttons on the right on main figure ax_reset = fig.add_axes([0.83, 0.70, 0.16, 0.12]) b_reset = Button(ax_reset, 'Reset', color='0.95', hovercolor='0.85') b_reset.on_clicked(reset) ax_eigen_svd = fig.add_axes([0.83, 0.55, 0.16, 0.12]) b_eigen_svd = Button(ax_eigen_svd, 'Eigen/SVD', color='0.95', hovercolor='0.85') b_eigen_svd.on_clicked(toggleSVDmode) ax_showvecs = fig.add_axes([0.83, 0.40, 0.16, 0.12]) b_showvecs = Button(ax_showvecs, 'Show\nEigen/Singular\nvectors', color='0.95', hovercolor='0.85') b_showvecs.on_clicked(toggleEigenSVDvectorsVisibility) ax_closeFig = fig.add_axes([0.83, 0.25, 0.16, 0.12]) b_closeFig = Button(ax_closeFig, 'Close', color='0.95', hovercolor='0.85') b_closeFig.on_clicked(closeFigure) # Initialize some of the objects (lines, texts, etc) oldModeText = fig.text(0.01, 0.8, 'dummytext', fontsize='large') # dummy text # Start rendering the plot drawPlot() drawlegend() # Draw the plot on the canvas canvas.show() Tk.mainloop()
class HIST(QtGui.QWidget, Script): def __init__(self): Script.__init__(self, "file histogram") self.freq = [0 for i in xrange(0, 256)] self.xcount = [i for i in xrange(0, 256)] def start(self, args): self.stateinfo = "counting byte occurences 0%" try: self.node = args["file"].value() f = self.node.open() buff = f.read(10*1024*1024) size = self.node.size() read = 0 while len(buff) > 0: for c in buff: self.freq[ord(c)] += 1 read += 1 self.stateinfo = "counting byte occurences " + str(float(read*100/size)) + "%" buff = f.read(10*1024*1024) f.close() except: pass def updateWidget(self): pass def g_display(self): QtGui.QWidget.__init__(self) self.oldtxt = None self.fig = Figure(figsize=(5, 5), dpi=100) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.canvas.updateGeometry() self.canvas.mpl_connect('motion_notify_event', self.on_motion) self.ax = self.fig.add_axes([0.2,0.2,0.5,0.7]) self.ax.set_xlabel("Byte") self.ax.set_ylabel("Frequency") self.ax.set_title("Byte Distribution of file \"" + self.node.name() + "\"") self.ax.set_xlim(0, 256) self.rects = self.ax.bar(self.xcount, self.freq, width=1, color='g', edgecolor='k') self.ax.set_xticks([i for i in xrange(0, 256, 10)]) for label in self.ax.xaxis.get_ticklabels(): label.set_color('black') label.set_rotation(45) label.set_fontsize(12) for label in self.ax.yaxis.get_ticklabels(): label.set_color('black') label.set_rotation(-45) label.set_fontsize(12) self.ax.grid(True) self.ax.autoscale(enable=True, axis='y') self.txt = self.fig.text(0, 0.1, '') self.orect = None vbox = QtGui.QVBoxLayout(self) vbox.addWidget(self.canvas) def on_motion(self, event): if event.xdata != None: x = int(event.xdata) rect = self.rects[x] if self.orect != None and self.orect != rect: self.orect.set_facecolor('g') rect.set_facecolor('b') self.orect = rect self.txt.set_text("byte: " + hex(x) + " -- frequency: " + str(self.freq[x])) self.canvas.draw() def setupUi(self): pass
def DWR1(nshot, signals, tbeg=0., tend=10., topframe=None, plot=True): if plot: if topframe is None: topframe = tk.Toplevel() topframe.title('Several signals') topframe.geometry('1200x960') nb = ttk.Notebook(topframe, name='nb') nb.pack(side=tk.TOP, fill=tk.X) sigframe = ttk.Frame(nb) nbiframe = ttk.Frame(nb) echframe = ttk.Frame(nb) icrframe = ttk.Frame(nb) nb.add(sigframe, text='Several signals') nb.add(nbiframe, text='NBI sources') nb.add(echframe, text='ECRH gyrotrons') nb.add(icrframe, text='ICRF antennae') udb = '%s/udb/%s' %(os.getenv('HOME'), nshot) os.system('mkdir -p %s' %udb) tlbl = 'Time'.ljust(20) + 'Seconds' #------------ # Time traces #------------ if plot: sfigframe = ttk.Frame(sigframe) sfigframe.pack(side=tk.TOP, fill=tk.X) sigfig = Figure(figsize=(8.2, 8.2), dpi=100) sig_can = FigureCanvasTkAgg(sigfig, master=sfigframe) sig_can._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) sigfig.subplots_adjust(left=0.1, bottom=0.1, right=0.95, top=0.92, hspace=0) sigfig.text(.5, .95, '#%d' %nshot, ha='center') xminorLocator = MultipleLocator(0.2) xmajorLocator = MultipleLocator(1.) #================ # Ipl, Bt, Uloop #================ n_ct = 1 n_sub = len(signals) + 2 for diag, val in signals.items(): for sig, par in val.items(): dlbl = par['lbl'] fac = par['fac'] ylab = par['yl'] print(diag, sig, fac) try: if sf.Open(diag, nshot): tim = sf.GetTimebase(sig) dat = sf.GetSignal(sig) sf.Close() # Plot index = (tim >= tbeg) & (tim <= tend) tarr = tim[index] darr = fac*dat[index] darr[0] = np.abs(darr[0]) # TRANSP determines sign(Ipl) from 1st entry uf_d = { 'pre': diag, 'ext': sig.strip(), 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': tarr}}, \ 'data': {'lbl': dlbl, 'arr': darr} } ufiles.WU(uf_d) t_av = np.atleast_1d(np.nanmean(tarr)) d_av = np.atleast_1d(np.nanmean(darr)) ufa_d = { 'pre': diag, 'ext': sig.strip()+'_AVG', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_av}}, \ 'data': {'lbl': dlbl, 'arr': d_av} } ufiles.WU(ufa_d) if plot: ymaj = MaxNLocator(5) ymin = MaxNLocator(10) ax = sigfig.add_subplot(n_sub, 1, n_ct) ax.plot(tarr, darr, color=col[n_ct]) ax.set_ylabel(ylab, fontsize=fsize) ax.xaxis.set_minor_locator(xminorLocator) ax.xaxis.set_major_locator(xmajorLocator) ax.yaxis.set_minor_locator(ymin) ax.yaxis.set_major_locator(ymaj) ax.tick_params(axis='x', which='both', bottom='on', top='on', labelbottom='off') ax.tick_params(axis='y', which='both', left='on', right='on') ax.ticklabel_format(axis='y', style='sci', scilimits=(-4,-4)) ax.yaxis.major.formatter._useMathText = True n_ct += 1 else: print('Signal %s of diag %s not found' %(sig, diag)) continue except: print('Problems with signal %s:%s' %(diag, sig)) #================================= # DCN for Zef H. Meister's formula #================================= dlbl = 'Zeff' try: zbrs = CalcZef.Zeff(nshot) index = (zbrs.timeZeff >= tbeg) & (zbrs.timeZeff <= tend) tbr = zbrs.timeZeff[index] zbr = zbrs.Zeff0[index] if zbr.all() == 0: zbr = zbrs.Zeff uf_d = { 'pre': 'Z', 'ext': 'BRS', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': tbr} }, \ 'data': {'lbl': dlbl, 'arr': zbr} } ufiles.WU(uf_d) t_av = np.atleast_1d(np.nanmean(tbr)) d_av = np.atleast_1d(np.nanmean(zbr)) ufa_d = { 'pre': 'Z', 'ext': 'BRS_AVG', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_av} }, \ 'data': {'lbl': dlbl, 'arr': d_av} } ufiles.WU(ufa_d) except: print('CalcZef Bremsstrahlung unsuccesful') try: zfml = CalcZef.Zeff_fml(nshot) # From formula index = (zfml.timeZeff >= tbeg) & (zfml.timeZeff <= tend) tfml = zfml.timeZeff[index] dfml = zfml.Zeff0[index] uf_d = { 'pre': 'Z', 'ext': 'FML', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': tfml} }, \ 'data': {'lbl': dlbl, 'arr': dfml} } ufiles.WU(uf_d) t_av = np.atleast_1d(np.nanmean(tfml)) d_av = np.atleast_1d(np.nanmean(dfml)) ufa_d = { 'pre': 'Z', 'ext': 'FML_AVG', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_av} }, \ 'data': {'lbl': dlbl, 'arr': d_av} } ufiles.WU(ufa_d) except: print('CalcZef formula unsuccesful') # Constant Zeff=1.6 uf_d = { 'pre': 'Z', 'ext': 'ZEF', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': np.array([tbeg, tend])}}, \ 'data': {'lbl': dlbl, 'arr': np.array([1.6, 1.6])} } ufiles.WU(uf_d) if plot: ax = sigfig.add_subplot(n_sub, 1, n_ct) if 'zbrs' in locals(): ax.plot(tbr, zbr, color=col[n_ct]) ax.set_ylabel(r'$Z_{eff, BR}$', fontsize=fsize) else: if 'zfml' in locals(): ax.plot(zfml.time, zfml.zeff, color=col[n_ct]) ax.set_ylabel(r'$Z_{eff, FML}$', fontsize=fsize) ax.set_xlabel('Time [s]', fontsize=fsize) ax.xaxis.set_minor_locator(xminorLocator) ax.xaxis.set_major_locator(xmajorLocator) ymaj = MaxNLocator(5) ymin = MaxNLocator(10) ax.yaxis.set_minor_locator(ymin) ax.yaxis.set_major_locator(ymaj) ax.tick_params(axis='y', which='both', left='on', right='on') sig_can.mpl_connect('button_press_event', fconf.on_click) toolbar = NavigationToolbar2TkAgg(sig_can, sigframe) toolbar.update() #---- # NBI #---- diag = 'NIS' sig = 'PNIQ' nbi_diff = 1.e3 if sf.Open(diag, nshot): tim = sf.GetTimebase(sig) index = (tim >= tbeg) & (tim <= tend) dat = sf.GetSignal(sig) sf.Close() tim = tim[index] dat = dat[index] ntim, box_size, nbox = dat.shape nsrc = box_size*nbox print('Diag %s nt = %d' %(diag, ntim)) print('#boxes %d' %nbox) print('#chann %d' %nsrc) ptmp = np.zeros((ntim, nsrc)) jx=0 for jbox in range(nbox): for jsrc in range(box_size): ptmp[:, jx] = dat[:, jsrc, jbox] jx += 1 ind_nbi = red_time.red_time(nbi_diff, ptmp) nt_tra = len(ind_nbi) t_nbi = tim[ind_nbi] pnbi = ptmp[ind_nbi, :] nbi_min = 3e4 for jsrc in range(nsrc): if np.max(pnbi[:, jsrc]) <= nbi_min: pnbi[:, jsrc] = np.zeros(nt_tra) # Ufile output xlbl = 'Channel number' dlbl = 'NBI power'.ljust(20) + 'W' x_nbi = 1. + np.arange(nsrc) if np.max(pnbi) > nbi_min: uf_2d = { 'pre': 'P', 'ext': 'NBI', 'shot': nshot, \ 'grid': {'X':{'lbl': tlbl, 'arr': t_nbi}, \ 'Y':{'lbl': xlbl, 'arr': x_nbi}}, \ 'data': {'lbl': dlbl, 'arr': pnbi} } ufiles.WU(uf_2d) t_av = np.atleast_1d(np.nanmean(tim)) ptmp[ptmp < nbi_min] = 0. pnbi_av = np.atleast_2d(np.nanmean(ptmp, axis=0)).reshape((1, nsrc)) ufa_2d = { 'pre': 'P', 'ext': 'NBI_AVG', 'shot': nshot, \ 'grid': {'X':{'lbl': tlbl, 'arr': t_av}, \ 'Y':{'lbl': xlbl, 'arr': x_nbi}}, \ 'data': {'lbl': dlbl, 'arr': pnbi_av} } ufiles.WU(ufa_2d) # Plots if plot: fig_plot(nbiframe, t_nbi, pnbi, nshot, y_ticks=[0, 1e6, 2e6,3e6], col=col[0], ylbl='NBI') #----- # ECRH #----- #------ # power #------ diag = 'ECS' n_gy = (4, 4) ngy = n_gy[0] + n_gy[1] ech_diff = 2.e3 gy_lbl = [] ps_lbl = [] for jgy in range(n_gy[0]): gy_lbl.append('%d' %(jgy + 1)) for jgy in range(n_gy[1]): gy_lbl.append('%dN' %(jgy + 1)) for jsys, glen in enumerate(n_gy): sys_str = '%d' %(jsys + 1) if jsys == 0 and nshot > 33725: sys_str = '3' for jgy in range(glen): ps_lbl.append('P_sy%s_g%d' %(sys_str, jgy+1)) if sf.Open(diag, nshot): tim = sf.GetTimebase('T-B') index = (tim >= tbeg) & (tim <= tend) & (tim >0) tim = tim[index] ntim = len(tim) ptmp = np.zeros((ntim, ngy)) alpha = np.zeros(ngy) beta = np.zeros(ngy) for jgy in range(ngy): beta [jgy] = sf.GetParameter(ps_lbl[jgy], 'GPolPos') alpha[jgy] = sf.GetParameter(ps_lbl[jgy], 'GTorPos') pows = 'PG' + gy_lbl[jgy] print('Requested signal %s' %pows) dat = sf.GetSignal(pows) if dat is not None: if dat.dtype == np.float32: ptmp[:, jgy] = dat[index] sf.Close() print('nt = %d' %ntim) # Reduce time array size ind_ech = red_time.red_time(ech_diff, ptmp) t_ech = tim[ind_ech] pech = ptmp[ind_ech, :] ech_min = 3.e4 for jgy in range(ngy): if np.max(pech[:, jgy]) < ech_min: pech[:, jgy] = np.zeros(len(t_ech)) # Ufile output xlbl = 'Channel number' dlbl = 'ECRH power'.ljust(20) + 'W' x_ech = 1. + np.arange(ngy) if np.max(pech) > ech_min: uf_d = { 'pre': 'P', 'ext': 'ECH', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_ech}, \ 'Y': {'lbl': xlbl, 'arr': x_ech} }, \ 'data': {'lbl': dlbl, 'arr': pech} } ufiles.WU(uf_d) t_av = np.atleast_1d(np.nanmean(tim)) ptmp[ptmp< ech_min] = 0. pech_av = np.atleast_2d(np.nanmean(ptmp, axis=0)).reshape((1, ngy)) ufa_2d = { 'pre': 'P', 'ext': 'ECH_AVG', 'shot': nshot, \ 'grid': {'X':{'lbl': tlbl, 'arr': t_av}, \ 'Y':{'lbl': xlbl, 'arr': x_ech} }, \ 'data': {'lbl': dlbl, 'arr': pech_av} } ufiles.WU(ufa_2d) # Plots if plot: fig_plot(echframe, t_ech, pech, nshot, y_ticks=[0, 2.5e5, 5e5, 7.5e5, 1e6], col=col[1], ylbl='Gy') #------- # Angles if nshot > 23187: diag = 'ECN' # ECRH2 phi_diff = 1.e-2 the_diff = 1.e-1 if sf.Open(diag, nshot): tim = sf.GetTimebase('T-Base') index = (tim >= tbeg) & (tim <= tend) & (tim >0) tim_ecn = tim[index] ntim = len(tim_ecn) # Reduce time points phi1 = np.zeros((1, ngy)) the1 = np.zeros((1, ngy)) phi_t = np.zeros((ntim, ngy)) the_t = np.zeros((ntim, ngy)) for jgy in range(ngy): angle = ec_an(alpha[jgy], beta[jgy], jgy) phi1[0, jgy] = - angle.tor the1[0, jgy] = - angle.pol # Time dependence: only ECN:G1POL and only ECRH2 for jgy in range(n_gy[0], n_gy[0] + n_gy[1]): sigpol = 'G%dPOL' %(jgy + 1 - n_gy[0]) datpol = sf.GetSignal(sigpol, cal=True) if datpol is not None: beta_t = 0.01*datpol[index] # Convert to TORBEAM angles for jt in range(ntim): angle = ec_an(alpha[jgy], beta_t[jt], jgy) phi_t[jt, jgy] = - angle.tor the_t[jt, jgy] = - angle.pol sf.Close() ind_phi = red_time.red_time(phi_diff, phi_t[:, n_gy[0]:n_gy[0] + n_gy[1]]) ind_the = red_time.red_time(the_diff, the_t[:, n_gy[0]:n_gy[0] + n_gy[1]]) t_phi = tim_ecn[ind_phi] t_the = tim_ecn[ind_the] phi = phi_t[ind_phi, :] the = the_t[ind_the, :] print(beta_t.shape) print(phi_t.shape) print(phi.shape) print(the.shape) # Ufile output dlbl = 'ECRH tor. angle'.ljust(20) + 'deg' uf_d = { 'pre': 'PHI', 'ext': 'ECH', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_phi}, \ 'Y': {'lbl': xlbl, 'arr': x_ech} }, \ 'data': {'lbl': dlbl, 'arr': phi} } ufiles.WU(uf_d) dlbl = 'ECRH pol. angle'.ljust(20) + 'deg' uf_d = { 'pre': 'THE', 'ext': 'ECH', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_the}, \ 'Y': {'lbl': xlbl, 'arr': x_ech} }, \ 'data': {'lbl': dlbl, 'arr': the} } ufiles.WU(uf_d) # Constant in time t_av = np.atleast_1d(np.nanmean(tim_ecn)) dlbl = 'ECRH tor. angle'.ljust(20) + 'deg' ufa_d = { 'pre': 'PHI', 'ext': 'ECH_AVG', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_av}, \ 'Y': {'lbl': xlbl, 'arr': x_ech} }, \ 'data': {'lbl': dlbl, 'arr': phi1} } ufiles.WU(ufa_d) dlbl = 'ECRH pol. angle'.ljust(20) + 'deg' ufa_d = { 'pre': 'THE', 'ext': 'ECH_AVG', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_av}, \ 'Y': {'lbl': xlbl, 'arr': x_ech} }, \ 'data': {'lbl': dlbl, 'arr': the1} } ufiles.WU(ufa_d) #----- # ICRF #----- diag = 'ICP' nant = 4 icr_diff = 5.e3 if sf.Open(diag, nshot): for jant in range(nant): tbas = diag + '.'.ljust(9) sig1 = 'pnet%d' %(jant + 1) sig2 = 'ploss%d' %(jant + 1) print('Requested signal %s' %sig1) tim = sf.GetTimebase(sig1) index = (tim >= tbeg) & (tim <= tend) & (tim >0) tim = tim[index] dat1 = sf.GetSignal(sig1)[index] dat2 = sf.GetSignal(sig2)[index] if jant == 0: ntim = len(tim) ptmp = np.zeros((ntim, nant)) ptmp[:, jant] = dat1 - dat2 sf.Close() ind_icr = red_time.red_time(icr_diff, ptmp) t_icr = tim[ind_icr] picr = ptmp[ind_icr, :] icr_min = 1e4 for jant in range(nant): if np.max(picr[:, jant]) <= icr_min: picr[:, jant] = np.zeros(len(t_icr)) # Ufile output xlbl = 'Channel number' dlbl = 'ICRH power'.ljust(20) + 'W' x_icr = 1. + np.arange(nant) if np.max(picr) > icr_min: uf_d = { 'pre': 'P', 'ext': 'ICH', 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': t_icr}, \ 'Y': {'lbl': xlbl, 'arr': x_icr}}, \ 'data': {'lbl': dlbl, 'arr': picr} } ufiles.WU(uf_d) t_av = np.atleast_1d(np.nanmean(tim)) ptmp[ptmp < icr_min] = 0. picr_av = np.atleast_2d(np.nanmean(ptmp, axis=0)).reshape((1, nant)) ufa_d = { 'pre': 'P', 'ext': 'ICH_AVG', 'shot': nshot, \ 'grid': {'X':{'lbl': tlbl, 'arr': t_av}, \ 'Y':{'lbl': xlbl, 'arr': x_icr}}, \ 'data': {'lbl': dlbl, 'arr': picr_av} } ufiles.WU(ufa_d) # Plots if plot: fig_plot(icrframe, t_icr, picr, nshot, y_ticks=[0, 2.5e5, 5e5, 7.5e5, 1e6], col=col[2], ylbl='Ant ') # Minority concentration diag = 'CXF' dlbl = 'Minority concentration' for sig in ('cHavR','cHavL'): if sf.Open(diag,nshot): t_cxf = sf.GetTimebase(sig) c_min = sf.GetSignal(sig) sf.Close() else: return nt_cxf = len(t_cxf) if (nt_cxf > 0) : uf_d={ 'pre':diag, 'ext':sig, 'shot':nshot, \ 'grid': {'X':{'lbl':tlbl, 'arr':t_cxf}}, \ 'data': {'lbl':dlbl, 'arr':c_min} } ufiles.WU(uf_d)
class MediaPanel(wx.Panel): """" clase llamada por MediaFrame (padre)""" # ---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) # Para el menu de archivos y el modelo a usar por defecto sp = wx.StandardPaths.Get() self.currentFolder = sp.GetDocumentsDir() self.currentFile = '' self.s = '' # modelo de reconocimiento self.currentModel = 'C:\Users\Mario\Desktop\hito1\modelos\ExtraTreesClassifier_Apr0816\ExtraTreesClassifier_Apr0816.pkl' # cantidad de segundos de inicio self.ventana = 120 # control de offset para la grafica self.t = 0 self.bloqueo = False # contador de tiempo inicial self.marcador = '00:00:00' self.inicio_grabacion = datetime.datetime(2000, 1, 1, 0, 0) # parent y creacion de menu y apariencia self.frame = parent self.SetBackgroundColour("white") self.currentVolume = 50 self.createMenu() self.layoutControls() self.Bind(wx.EVT_SIZE, self.onSize) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.onTimer) self.timer.Start(100) # ---------------------------------------------------------------------- def layoutControls(self): """ Creacion de dispositivos de la aplicacion """ try: self.mediaPlayer = wx.media.MediaCtrl(self, style=wx.RAISED_BORDER) except NotImplementedError: self.Destroy() raise # barra de reproduccion ################ sliderSizer = wx.BoxSizer(wx.HORIZONTAL) self.playbackSlider = wx.Slider(self, size=wx.DefaultSize) self.Bind(wx.EVT_SLIDER, self.onSeek, self.playbackSlider) sliderSizer.Add(self.playbackSlider, 3, wx.ALL | wx.EXPAND, 5) # CANVAS (figura) y barra de herramientas ##################### self.figure = Figure(facecolor='white') self.axes = self.figure.add_subplot(111) self.axes.get_yaxis().set_visible(False) self.figure.text(0.5, 0.04, 'tiempo', ha='center', va='center') self.axes.grid() self.canvas = FigureCanvas(self, -1, self.figure) self.chart_toolbar = MyCustomToolbar(self.canvas) self.chart_toolbar.Realize() # self.finapp = wx.Button(self, label="FINALIZAR") # self.finapp.SetInitialSize() # self.finapp.Bind(wx.EVT_BUTTON, self.onFinalizar) ###### SIZERS ################################### mainSizer = wx.BoxSizer(wx.VERTICAL) self.barra_1h_hora_sizer = wx.BoxSizer(wx.VERTICAL) self.barra_1h_hora_sizer1 = wx.BoxSizer(wx.HORIZONTAL) self.barra_1h_hora_sizer2 = wx.BoxSizer(wx.HORIZONTAL) self.barra_1h_hora_sizer.Add(self.barra_1h_hora_sizer1, 0, wx.EXPAND) self.barra_1h_hora_sizer.Add(self.barra_1h_hora_sizer2, 0, wx.EXPAND) self.audioSizer = self.buildAudioBar() # Espacio para mostrar anuncios detectados por huella self.th = wx.TextCtrl(self, 0, style=wx.TE_MULTILINE | wx.TE_READONLY, size=(860, 200)) font2 = wx.Font(12, wx.ROMAN, wx.NORMAL, wx.BOLD) self.th.SetFont(font2) self.th.SetBackgroundColour('green') # widgets--COLOCACION DE BARRA DE REPRODUCCION, CONTROLADORES Y GRAFICA mainSizer.Add(self.barra_1h_hora_sizer, 0, wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND, 50) mainSizer.Add(self.audioSizer, 0, wx.CENTER, 1) mainSizer.Add(self.th, 0, wx.LEFT | wx.CENTER, 20) # mainSizer.Add(self.finapp, 1, wx.CENTER, 0) mainSizer.Add(sliderSizer, 0, wx.ALL | wx.EXPAND, 50) mainSizer.Add(self.canvas, 1, wx.ALL | wx.EXPAND, 0) mainSizer.Add(self.chart_toolbar, 1, flag=wx.ALIGN_CENTER, border=1) self.SetSizerAndFit(mainSizer) mainSizer.Fit(self) self.Layout() def resultProducer(self, audio, djv): """Pretend to be a complex worker function or something that takes long time to run due to network access etc. GUI will freeze if this method is not called in separate thread.""" # import time # count = 0 # while not abortEvent() and count < 50: # time.sleep(0.1) # count += 1 # return jobID global lista_anuncios message = "Analizando el archivo %s en busca de anuncios" % str(self.currentFile) busy = PBI.PyBusyInfo(message, parent=None, title="Procesando") time.sleep(5) del busy lista_aux = reconocedor_mayo.reconocedor(audio, djv) print "lista_aux:{}".format(lista_aux) for i in lista_aux: lista_anuncios.append(i) print "lista_anuncios:{}".format(lista_anuncios) return lista_anuncios def resultConsumer(self, delayedResult): try: result = delayedResult.get() except Exception, exc: # self.log("Result for job raised exception: %s" % (exc)) print exc return global lista_anuncios if lista_anuncios: self.actualizarAnuncios() print "lista_anuncios:{}".format(lista_anuncios)
class RadianceSampleViewer(QtGui.QMainWindow): def __init__(self, parent=None): super(RadianceSampleViewer, self).__init__(parent) self.setWindowTitle("Radiance Sample Viewer") self.setAcceptDrops(True) # Build the main plot canvas self.plot = Figure(facecolor=(0.933, 0.933, 0.933), edgecolor=(0, 0, 0)) self.plotCanvas = FigureCanvas(self.plot) self.setCentralWidget(self.plotCanvas) # Build the sample tree view self.sampleTreeDock = QtGui.QDockWidget("Open Samples", self) self.sampleTreeDock.setAllowedAreas(QtCore.Qt.RightDockWidgetArea) self.sampleTree = QtGui.QTreeWidget() self.sampleTree.setSortingEnabled(True) self.sampleTree.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) self.sampleTree.itemSelectionChanged.connect(self.SOCKET_handleSampleSelection) self.sampleTree.itemChanged.connect(self.SOCKET_handleSampleCheck) self.sampleTree.setHeaderLabels(["Date", "Time", "Azimuth", "Elevation"]) self.sampleTreeDock.setWidget(self.sampleTree) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.sampleTreeDock) # Build the fisheye view dock self.fisheyeDock = QtGui.QDockWidget("Fisheye Viewer", self) self.fisheyeDock.setAllowedAreas(QtCore.Qt.RightDockWidgetArea) self.fisheyeView = fisheye_view.FisheyeViewer() self.fisheyeDock.setWidget(self.fisheyeView) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.fisheyeDock) # Setup the file menu bar self.menubar = self.menuBar() fileMenu = self.menubar.addMenu("&File") loadRadianceAction = QtGui.QAction("&Load Radiance File", self) loadRadianceAction.triggered.connect(self.SOCKET_loadRadianceData) fileMenu.addAction(loadRadianceAction) loadFisheyeAction = QtGui.QAction("Load Fisheye Image", self) loadFisheyeAction.triggered.connect(self.SOCKET_loadFisheyeImage) fileMenu.addAction(loadFisheyeAction) clearDataAction = QtGui.QAction("&Clear Radiance Data", self) clearDataAction.triggered.connect(self.sampleTree.clear) fileMenu.addAction(clearDataAction) def SOCKET_handleSampleSelection(self): """ Redraw the graph when the user selection changes. """ self.plotRadianceData() def SOCKET_handleSampleCheck(self, item, column): """ Add or remove a sample plot from the radiance plotter bsed on if it is checked or not. """ self.plotRadianceData() def dragEnterEvent(self, event): """ Accept drag events concerning files. """ if event.mimeData().hasUrls(): event.accept() else: event.ignore() def addSampleItem(self, sampleData, sampleFile): """ Add a radiance sample to the tree widget and the radiance plot. """ # Add the file to the tree list treeWidgetItem = RadianceSampleItem(sampleData, self.sampleTree) treeWidgetItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable) treeWidgetItem.setCheckState(0, QtCore.Qt.Unchecked) fileInfo = self.parseRadianceFileName(sampleFile) # Add columns for each of the data fields treeWidgetItem.setText(0, fileInfo[0]) # Date treeWidgetItem.setText(1, fileInfo[1]) # Time treeWidgetItem.setText(2, fileInfo[4]) # Azimuth treeWidgetItem.setText(3, fileInfo[5]) # Elevation self.sampleTree.addTopLevelItem(treeWidgetItem) def dropEvent(self, event): """ Handle the file drop event and load the radiance file dropped on the window. """ files = event.mimeData().urls() self.sampleTree.blockSignals(True) for radianceFile in files: # Add the sample data to the file list radianceSample = self.loadRadianceDataFile(radianceFile.toLocalFile()) self.addSampleItem(radianceSample, radianceFile.toLocalFile()) self.sampleTree.blockSignals(False) self.plotRadianceData() def parseRadianceFileName(self, filename): """ Parses out the date, time, and angle information from a radiance file. """ fileComponents = os.path.split(filename) fullFile = fileComponents[1] if fullFile and fullFile.endswith(".asd.rad.txt"): noExt = fullFile[:-12] noExt = re.sub("_+", "_", noExt) fileInfo = noExt.split('_') return fileInfo def plotRadianceData(self): """ Plot the current radiance data loaded into memory. """ self.plot.clear() ax = self.plot.add_subplot(111) ax.axis([350, 800, 0.0, 0.3]) ax.set_ylabel("Radiance ($W/m^2$)") ax.set_xlabel("Wavelength ($nm$)") selectedSample = None selectedIndex = None for i in range(self.sampleTree.topLevelItemCount()): sampleItem = self.sampleTree.topLevelItem(i) sample = sampleItem.radianceData if sampleItem.isSelected(): selectedSample = [sample.keys(), sample.values()] selectedIndex = i # Update the fisheye view with the correct angle pair azimuth = float(sampleItem.text(2)) elevation = float(sampleItem.text(3)) self.fisheyeView.reset() self.fisheyeView.drawAnglePosition(azimuth, elevation, inRadians=False) if sampleItem.checkState(0) == QtCore.Qt.Checked: ax.plot(sample.keys(), sample.values(), color="#000000") # Redraw the selected sample in a thicker line if selectedSample: ax.plot(selectedSample[0], selectedSample[1], color="#4499FF", linewidth=3) self.plot.text(0.05, 0.95, "%d" % selectedIndex) self.plotCanvas.draw() if selectedSample: saveFilename = "C:/Users/dtk47/Desktop/THESIS/plot%05d.png" % selectedIndex self.plot.savefig(saveFilename) def SOCKET_loadRadianceData(self): """ Allow the user to open a new radiance file and display the file in the radiance plot. """ radianceFiles = QtGui.QFileDialog.getOpenFileNames(self, "Radiance File")[0] self.sampleTree.blockSignals(True) for radianceFile in radianceFiles: radianceSample = self.loadRadianceDataFile(radianceFile) self.addSampleItem(radianceSample, radianceFile) self.sampleTree.blockSignals(False) self.plotRadianceData() def SOCKET_loadFisheyeImage(self): """ Allow the user to load a fisheye image to display in conjunction with the radiance samples to display the angle associated with the selected sample. """ fisheyeFile = QtGui.QFileDialog.getOpenFileName(self, "Fisheye File") fisheyeFilename = fisheyeFile[0] self.fisheyeView.loadFisheyeFile(fisheyeFilename) def loadRadianceDataFile(self, filename): """ Read in a radiance file in txt format, and return a dictionary of wavelength to radiance. """ radianceFile = open(filename, 'r') radianceDict = {} for line in radianceFile: fileCols = line.split('\t') try: # Try to parse the first piece as in int wavelength wavelength = int(fileCols[0]) radiance = float(fileCols[1]) radianceDict[wavelength] = radiance except ValueError: # Catch the error on the first line, and continue print line continue radianceFile.close() return radianceDict def quit(self): self.close()
class MediaPanel(wx.Panel): """" clase llamada por MediaFrame (padre)""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) #parent y creacion de menu y apariencia self.frame = parent self.SetBackgroundColour("white") self.currentVolume = 50 self.createMenu() self.layoutControls() #Adjuntamos barra indicadora lo hacemos sensible a tamanho (?) #todo hay que poner eventos OnClick y eje de tiempos self.Bind(wx.EVT_SIZE, self.OnSize) #Para el menu de archivos y el modelo a usar por defecto sp = wx.StandardPaths.Get() self.currentFolder = sp.GetDocumentsDir() self.currentFile = '' #modelo de reconocimiento self.currentModel = 'D:\\archivos_captor\modelos\ExtraTreesClassifier_Apr0816.pkl' #cantidad de segundos de inicio self.ventana=60 #control de offset para la grafica self.t=0 self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.onTimer) self.timer.Start(100) #---------------------------------------------------------------------- def layoutControls(self): """ Creacion de dispositivos de la aplicacion """ try: self.mediaPlayer = wx.media.MediaCtrl(self, style=wx.RAISED_BORDER) except NotImplementedError: self.Destroy() raise self.Bind(wx.EVT_PAINT, self.OnDibujo) # barra de reproduccion ################ sliderSizer = wx.BoxSizer(wx.HORIZONTAL) self.playbackSlider = wx.Slider(self, size=wx.DefaultSize) self.Bind(wx.EVT_SLIDER, self.onSeek, self.playbackSlider) sliderSizer.Add(self.playbackSlider, 3, wx.ALL|wx.EXPAND, 5) #CANVAS (figura) y barra de herramientas ##################### self.figure = Figure(facecolor='white') self.axes = self.figure.add_subplot(111) self.axes.get_yaxis().set_visible(False) self.figure.text(0.5, 0.04, 'segundos', ha='center', va='center') self.axes.grid() self.canvas = FigureCanvas(self, -1, self.figure) self.chart_toolbar = MyCustomToolbar(self.canvas) self.chart_toolbar.Realize() ###### SIZERS ################################### mainSizer = wx.BoxSizer(wx.VERTICAL) audioSizer = self.buildAudioBar() #widgets--COLOCACION DE BARRA DE REPRODUCCION, CONTROLADORES Y GRAFICA mainSizer.Add(self.playbackSlider, 0, wx.ALL|wx.EXPAND, 50) mainSizer.Add(audioSizer, 0, wx.LEFT|wx.CENTER, 50) mainSizer.Add(self.canvas, 0, wx.LEFT|wx.EXPAND, 50) mainSizer.Add(self.chart_toolbar, 1, flag=wx.ALIGN_CENTER, border=2) self.SetSizer(mainSizer) self.Layout() #---------------------------------------------------------------------- def buildAudioBar(self): """ Construye los controladores de audio """ audioBarSizer = wx.BoxSizer(wx.HORIZONTAL) # contador self.trackCounter = wx.StaticText(self, label="00:00") font1 = wx.Font(22, wx.DECORATIVE, wx.ITALIC, wx.NORMAL) self.trackCounter.SetFont(font1) audioBarSizer.Add(self.trackCounter, 0,wx.LEFT | wx.CENTER, -430) # create play/pause toggle button img = wx.Bitmap(os.path.join(bitmapDir, "player_play.png")) self.playPauseBtn = buttons.GenBitmapToggleButton(self, bitmap=img, name="play") self.playPauseBtn.Enable(False) img = wx.Bitmap(os.path.join(bitmapDir, "player_pause.png")) self.playPauseBtn.SetBitmapSelected(img) self.playPauseBtn.SetInitialSize() self.playPauseBtn.Bind(wx.EVT_BUTTON, self.onPlay) audioBarSizer.Add(self.playPauseBtn, 0, wx.LEFT | wx.CENTER, -290) btnData = [{'bitmap':'player_prev.png', 'handler':self.onPrev, 'name':'prev'},{'bitmap':'player_stop.png', 'handler':self.onStop, 'name':'stop'}, {'bitmap':'player_next.png', 'handler':self.onNext, 'name':'next'}] for btn in btnData: self.buildBtn(btn, audioBarSizer) #Boton detector self.detector = GB.GradientButton(self, label="DETECTAR") self.detector.SetInitialSize() self.detector.Bind(wx.EVT_BUTTON, self.onDetector) audioBarSizer.Add(self.detector, 0,wx.LEFT | wx.CENTER, 40) #volumen de audio self.volumeCtrl = wx.Slider(self, style=wx.SL_HORIZONTAL, name='VOL') self.volumeCtrl.SetRange(0, 100) self.volumeCtrl.SetValue(self.currentVolume) self.volumeCtrl.Bind(wx.EVT_SLIDER, self.onSetVolume) audioBarSizer.Add(self.volumeCtrl, 0,wx.LEFT | wx.CENTER, 20) return audioBarSizer #---------------------------------------------------------------------- def buildBtn(self, btnDict, sizer): """""" bmp = btnDict['bitmap'] handler = btnDict['handler'] img = wx.Bitmap(os.path.join(bitmapDir, bmp)) btn = buttons.GenBitmapButton(self, bitmap=img, name=btnDict['name']) btn.SetInitialSize() btn.Bind(wx.EVT_BUTTON, handler) sizer.Add(btn, 0, wx.LEFT | wx.CENTER, 3) #---------------------------------------------------------------------- def createMenu(self): """ Crea el menu """ menubar = wx.MenuBar() fileMenu = wx.Menu() open_file_menu_item = fileMenu.Append(wx.NewId(), "&Abrir", "Abre un archivo") exitMenuItem = fileMenu.Append(wx.NewId(), "Salir","Sale de la aplicacion") menubar.Append(fileMenu, '&Archivo') self.frame.Bind(wx.EVT_MENU, self.onBrowse, open_file_menu_item) self.frame.Bind(wx.EVT_MENU, self.onClose, exitMenuItem) self.frame.SetMenuBar(menubar) #---------------------------------------------------------------------- def loadMusic(self, musicFile): """""" if not self.mediaPlayer.Load(musicFile): wx.MessageBox("No se puede abrir %s: Formato erroneo?" % musicFile, "ERROR", wx.ICON_ERROR | wx.OK) else: self.mediaPlayer.SetInitialSize() self.GetSizer().Layout() self.playbackSlider.SetRange(0, self.mediaPlayer.Length()) self.playPauseBtn.Enable(True) self.graficar_audio() def graficar_audio(self): ###puede estar asociado a un evento (onclick) y aparecer con un event-event.Skip() print 'graficamos' valorslide=self.playbackSlider.GetValue()/1000 try: s = wave.open(self.currentFile,'r') fs=s.getframerate() nc = s.getnchannels() s.setpos(valorslide*fs) segmento = s.readframes(int(((valorslide+self.ventana)-valorslide)*fs)) data = np.fromstring(segmento, np.int16) samples=data[::2] ejetiempo=np.linspace(valorslide, valorslide+len(samples)/fs, num=len(samples)) print 'try' except: ejetiempo=np.linspace(0, self.ventana, num=(self.ventana)*1000) samples=np.zeros(self.ventana*1000) print 'except' self.axes.plot(ejetiempo,samples) self.axes = self.figure.add_subplot(111) self.axes.plot(ejetiempo,samples)# linewidth=1, labelfontsize=5, autoscale=False, xmin=valorslide, xmax=valorslide+len(samples)/sampleRate) self.canvas.draw() self.canvas.Update() self.canvas.Refresh() #event.Skip() def OnSize(self, event): # self.Refresh() # MUST have this, else the rectangle gets rendered corruptly when resizing the window! event.Skip() def OnDibujo(self, event): """ BARRA INDICADORA --- configuramos posicion, longitud y color """ self.dc = wx.PaintDC(self) self.dc.BeginDrawing() self.dc.SetPen(wx.Pen("black")) self.dc.SetBrush(wx.Brush("green", wx.SOLID)) global anchura_ventana, altura_ventana anchura_ventana, altura_ventana = self.GetSizeTuple() print anchura_ventana, altura_ventana anchura_marco = anchura_ventana * 0.94 altura_marco = altura_ventana * 0.04 pos_x_marco = anchura_ventana * 0.03 pos_y_marco = altura_ventana * 0.01 # self.button = wx.Button(self, id=-1, label="", pos=(pos_x_marco, pos_y_marco), size=(anchura_marco, altura_marco)) # self.button.SetBackgroundColour("blue") # self.button.Bind(wx.EVT_BUTTON, self.OnButton()) self.dc.DrawRectangle(pos_x_marco, pos_y_marco, anchura_marco, altura_marco) event.Skip() #---------------------------------------------------------------------- # def OnButton(self): # # print "{} {} {}".format("onbutton", anchura_ventana, altura_ventana) def onBrowse(self, event): """ Dialogo de busqueda de audio """ wildcard = "WAV (*.wav)|*.wav|" \ "MP3 (*.mp3)|*.mp3" dlg = wx.FileDialog( self, message="Elija un archivo", defaultDir=self.currentFolder, defaultFile=self.currentFile, wildcard=wildcard, style=wx.OPEN | wx.CHANGE_DIR ) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.currentFolder = os.path.dirname(path) self.currentFile = path self.loadMusic(path) dlg.Destroy() #---------------------------------------------------------------------- def onDetector(self, event): if not self.currentFile: msg = "Debes abrir un audio en el menu 'Archivo' " self.showMessageDlg(msg, "Error", wx.OK|wx.ICON_INFORMATION) return menu = MyPopupMenu() self.PopupMenu(menu, (700,70)) menu.Destroy() #texto=self.trackDetector.GetLabel() # self.trackDetector.SetLabel(texto + ' - Procesando') bloques=detector_bloques.bloques_porvector(self.currentFile, rutamodelo=self.currentModel) limites='' for bloque in bloques: limites += bloque[0] + ' - ' + bloque[1] + '\n' #self.trackDetector.SetLabel(texto + ' - Resultados \n' + limites) #---------------------------------------------------------------------- def onNext(self, event): """ Avanzamos un valor fijo, incluso en pausa """ #offset siempre en milisegundos offset = self.playbackSlider.GetValue() try: #10000 = 10 segundos self.mediaPlayer.Seek(offset + 10000) except: #AQUI por lo visto nunca entra self.mediaPlayer.Seek(self.mediaPlayer.Length()) #---------------------------------------------------------------------- def onPause(self): """ Pauses the music """ self.mediaPlayer.Pause() #---------------------------------------------------------------------- def onPlay(self, event): """ Plays the music """ if not event.GetIsDown(): self.onPause() return if not self.mediaPlayer.Play(): wx.MessageBox("Unable to Play media : Unsupported format?", "ERROR", wx.ICON_ERROR | wx.OK) else: self.mediaPlayer.SetInitialSize() self.GetSizer().Layout() self.playbackSlider.SetRange(0, self.mediaPlayer.Length()) event.Skip() #---------------------------------------------------------------------- def onPrev(self, event): """ Retrocedemos un valor fijo, incluso en pausa """ #offset siempre en milisegundos offset = self.playbackSlider.GetValue() try: self.mediaPlayer.Seek(offset - 10000) except: self.mediaPlayer.Seek(0) #---------------------------------------------------------------------- def onSeek(self, event): """ Seeks the media file according to the amount the slider has been adjusted. """ offset = self.playbackSlider.GetValue() self.mediaPlayer.Seek(offset) #---------------------------------------------------------------------- def onSetVolume(self, event): """ Sets the volume of the music player """ self.currentVolume = self.volumeCtrl.GetValue() #print "setting volume to: %s" % int(self.currentVolume) self.mediaPlayer.SetVolume(self.currentVolume) #---------------------------------------------------------------------- def onStop(self, event): """ Stops the music and resets the play button """ self.mediaPlayer.Stop() self.playPauseBtn.SetToggle(False) def onPrint(self,event): ''' evento de recoger limites para hacer un fingerprint :param event: :return: ''' with open("D:\i+d\Captor\prototipo_2\docs\\basededatos.cnf") as f: config = json.load(f) djv = Dejavu(config) #---------------------------------------------------------------------- def onTimer(self,event): """ Keeps the player slider updated """ try: offset = self.mediaPlayer.Tell() except: return offset = int(offset) self.playbackSlider.SetValue(offset) secsPlayed = time.strftime('%M:%S', time.gmtime(offset/1000)) if offset == -1: self.trackCounter.SetLabel("00:00") else: self.trackCounter.SetLabel(secsPlayed) #if self.t != (abs(offset) / (self.ventana*1000) ): #print 'actualizacion' #self.graficar_audio() #self.t = abs(offset) / (self.ventana*1000) #---------------------------------------------------------------------- def showMessageDlg(self, msg, title, style): """""" dlg = wx.MessageDialog(parent=None, message=msg, caption=title, style=style) dlg.ShowModal() dlg.Destroy() #---------------------------------------------------------------------- def onClose(self, event): self.mediaPlayer.Stop() self.playPauseBtn.SetToggle(False) frame.Close() def valor_cociente(self, valor): ##hay que hacer una clase o algo que almacene mientras el valor de offset vc=valor return vc
class PlottingController(object): """ Plotting Controller This class controlls all the plotting related functionality. """ def __init__(self, parameters, defaults): """ Constructor """ v = ParameterValidator(parameters, defaults) self.parameters = v.validate() self.DPI = 100.0 self.bbox = BBox(parameters["bbox"]) # 1. Retrieve the data self.dset = self.__evaluate_datasource_type() ( self.parameters["source_url"], \ self.bbox, \ self.parameters["layers"][0], \ self.parameters["time"], \ self.parameters["time_index"], \ True ) self.lat = self.dset.get_lats() self.lon = self.dset.get_lons() self.var = self.dset.get_data() # 1.1 Normalise data self.bbox,self.lon,self.var = \ self.__transform_lons(self.bbox, \ self.lon, \ self.var) # 2. Set up figure self.bmapuclon = self.bbox.lon_max self.bmaplclon = self.bbox.lon_min self.bmapuclat = min(90, self.bbox.lat_max) self.bmaplclat = max(-90, self.bbox.lat_min) self.fig = Figure() self.canvas = FigureCanvas(self.fig) # 3. Set up basemap ax = self.fig.add_axes( (0,0,1,1), \ frame_on = False, \ axis_bgcolor = 'k', \ alpha = 0 , \ visible = False ) self.m = Basemap( projection = 'cyl', \ resolution = 'c' , \ llcrnrlon = self.bmaplclon, \ llcrnrlat = self.bmaplclat, \ urcrnrlon = self.bmapuclon, \ urcrnrlat = self.bmapuclat, \ suppress_ticks = True, \ fix_aspect = False, \ ax = ax) def get_legend(self): """ Responsible for wrapping the GetLegend request Returns an image. """ #FIXME: Ugly ... replace without having to print map first ax = self.fig.add_axes( (0,0,1,1), \ frame_on = False, \ axis_bgcolor = 'k') self.m.ax = ax self.__create_contours(pt.ContourPlot) self.fig = Figure(figsize=(64/self.DPI,256/self.DPI)) self.canvas = FigureCanvas(self.fig) self.__create_legend((0,0.1,0.2,0.8)) return self.__create_image() def get_contour(self): """ Responsible for wrapping the GetMap request. Returns an image. """ # Calculate offsets for stuff bmaplatmin, bmaplonmin = self.m(self.bbox.lat_min, self.bbox.lon_min) bmaplatmax, bmaplonmax = self.m(self.bbox.lat_max, self.bbox.lon_max) lon_offset1 = abs(self.bmaplclon - bmaplonmin) lat_offset1 = abs(self.bmaplclat - bmaplatmin) #lon_offset2 = abs(self.bmapuclon - bmaplonmax) #lat_offset2 = abs(self.bmapuclat - bmaplatmax) lon_normstart = lon_offset1 / abs(bmaplonmax - bmaplonmin) lat_normstart = lat_offset1 / abs(bmaplatmax - bmaplatmin) ax_xfrac = abs( self.bmapuclon - self.bmaplclon ) / \ abs( bmaplonmax - bmaplonmin ) ax_yfrac = abs( self.bmapuclat - self.bmaplclat ) / \ abs( bmaplatmax - bmaplatmin) coords = (lon_normstart, lat_normstart, ax_xfrac, ax_yfrac) ##### ax = self.fig.add_axes( coords, \ frame_on = False, \ axis_bgcolor = 'k') self.m.ax = ax self.__create_contours(self.__evaluate_plot_type()) return self.__create_image() def get_full_figure(self, n_merid = 5, n_para = 5): """ Responsibe for wrapping the GetFullFigure request. Returns an image. n_merid: Number of meridians we want to print as an overlay n_para: number of parallels we want printed as an overlay """ tick_font_size = 8 title_font_size = 9 plot_dims = self.__calc_plot_dims() ax = self.fig.add_axes( plot_dims, \ frame_on = False, \ axis_bgcolor = 'k') self.m.ax = ax self.__create_contours(self.__evaluate_plot_type()) self.__create_legend((0.8,0.1,0.02,plot_dims[3])) # Creating the overlay base = (self.bbox.lon_max - self.bbox.lon_min)/float(n_merid) meridians = [ self.bbox.lon_min + i*base for i in range(n_merid)] base = (self.bbox.lat_max - self.bbox.lat_min)/float(n_para) parallels = [ self.bbox.lat_min + i*base for i in range(1,n_para+1)] self.m.drawcoastlines() self.m.drawmeridians(meridians, \ labels = [0,1,0,1], \ fmt = "%3.1f", \ fontsize = tick_font_size) self.m.drawparallels(parallels, \ labels= [1,0,0,0], \ fmt = "%3.1f", \ fontsize = tick_font_size) self.m.drawparallels([0], \ linewidth = 1, \ dashes = [1,0], \ labels = [0,1,1,1], \ fontsize = tick_font_size) self.fig.text(0.05,0.98,self.__get_plot_title(), \ va='top', fontsize=title_font_size) return self.__create_image(transparent=False) def __create_image(self,transparent=True): """ Create image with the given format an returns it. If iamge type is not supported, an exception is raised: transparent: True/False for transparent background """ supported_formats = [ 'png', 'svg' ] img_format = self.parameters["format"] if not img_format in supported_formats: raise ex.InvalidFormatError(img_format) img_data = StringIO.StringIO() self.fig.savefig(img_data, \ format = img_format, \ transparent=transparent) value = img_data.getvalue() img_data.close() return value def __create_contours(self,style_type): """ This class does the actual work, but does not create images. Only manipulates the Basemap object. style_type: The class we have to create """ # Set size of the image self.fig.set_dpi(self.DPI) self.fig.set_size_inches(self.parameters["width"]/self.DPI, \ self.parameters["height"]/self.DPI) try: plot = style_type(self.parameters, \ self.m, \ self.lon, \ self.lat, \ self.var, \ self.fig ) except Exception, e: raise ex.InvalidParameterValueError(repr(e)) self.main_render = plot.plot()
class GEO_NEMEC: timeout = 1e-10 def __init__(self, nshot, fmframe=None): if fmframe is None: if __name__ == '__main__': fmframe = tk.Tk() import trgui_style else: fmframe = tk.Toplevel() fmframe.geometry('1300x950') # Widgets style # Menu bar menubar = tk.Menu(fmframe) filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label="Run NEMEC", command=self.surf) filemenu.add_command(label="Store u-files", command=self.store_u) filemenu.add_separator() filemenu.add_command(label="Close", command=fmframe.destroy) menubar.add_cascade(label = "File", menu=filemenu) fmframe.config(menu = menubar) canvframe = ttk.Frame(fmframe, height=850) entframe = ttk.Frame(fmframe) self.toolframe = ttk.Frame(fmframe) for frame in canvframe, entframe, self.toolframe: frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.nbplot = ttk.Notebook(canvframe) self.nbplot.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.nbplot.bind('<Button-1>', self.on_click) pol_frame = ttk.Frame(self.nbplot) mom_frame = ttk.Frame(self.nbplot) profframe = ttk.Frame(self.nbplot) self.nbplot.add(pol_frame, text='Poloidal plot') self.nbplot.add(mom_frame, text='Fourier moments') self.nbplot.add(profframe, text='EQuilibrium profiles') self.proffig = Figure(figsize=(4., 8.), dpi=100) self.pol_fig = Figure(figsize=(6., 8.), dpi=100) self.mom_fig = Figure(figsize=(6., 8.), dpi=100) self.proffig.subplots_adjust(left=0.2, bottom=0.1, right=0.8 , top=0.9) self.pol_fig.subplots_adjust(left=0.06, bottom=0.1, right=0.98, top=0.9) self.mom_fig.subplots_adjust(left=0.08, bottom=0.1, right=0.98, top=0.9) self.profcanvas = FigureCanvasTkAgg(self.proffig, master=profframe) self.pol_canvas = FigureCanvasTkAgg(self.pol_fig, master=pol_frame) self.mom_canvas = FigureCanvasTkAgg(self.mom_fig, master=mom_frame) self.profcanvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.pol_canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.mom_canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) #----------------- # Initialise plots #----------------- self.pol_fig.text(.5, .99, r'NEMEC equilibrium, constant $\rho$ and constant $\theta$ contours', \ ha='center', va='top') self.mom_fig.text(.5, .99, 'NEMEC Fourier moments', ha='center', va='top') # Profiles fsize = 16 self.qsub = self.proffig.add_subplot(311) self.qsub.set_xlim(0,1) self.qsub.set_xlabel(r'$\rho_{tor}$',fontsize=fsize) self.qsub.set_ylabel('q profile') self.psub = self.proffig.add_subplot(312) self.psub.set_xlim((0, 1)) self.psub.set_xlabel(r'$\rho_{tor}$',fontsize=fsize) self.psub.set_ylabel('Pressure [Pa]') self.rbsub = self.proffig.add_subplot(313) self.rbsub.set_xlim(0,1) self.rbsub.set_xlabel(r'$\rho_{tor}$',fontsize=fsize) self.rbsub.set_ylabel('R*B$_\phi$') #--------------- # Player buttons locdir = os.path.dirname(os.path.realpath(__file__)) self.playfig = tk.PhotoImage(file='%s/play.gif' %locdir) self.pausefig = tk.PhotoImage(file='%s/pause.gif' %locdir) self.forwardfig = tk.PhotoImage(file='%s/forward.gif' %locdir) self.backwardfig = tk.PhotoImage(file='%s/backward.gif' %locdir) backward_button = ttk.Button(self.toolframe, command=self.Backward,image=self.backwardfig) self.play_button = ttk.Button(self.toolframe, command=self.Play, image=self.playfig) forward_button = ttk.Button(self.toolframe, command=self.Forward, image=self.forwardfig) createToolTip(forward_button , 'Go to next timestep') createToolTip(backward_button , 'Go backward by one timestep') createToolTip(self.play_button, 'Forward animation/pause') for but in backward_button, self.play_button, forward_button: but.pack(side=tk.LEFT) # Entry frame geoinit = {'shot': nshot, 'Nmom': 7, 'ntheta': 101, 'nrho': 81, \ 'exp': 'AUGD', 'dia': 'EQH', 'ed': 0, \ 'tbeg': 4, 'tend': 6., 'DeltaT': 0.1} self.geodict = {} for key in ('shot', 'tbeg', 'tend', 'DeltaT', \ 'exp', 'dia', 'ed', \ 'Nmom', 'ntheta', 'nrho'): raw = ttk.Frame(entframe) raw.pack(side=tk.TOP) lbl = ttk.Label(entframe, text=key, width=5).pack(side=tk.LEFT) var = ttk.Entry(entframe, width=5) var.insert(0, geoinit[key]) var.pack(side=tk.LEFT, padx='2 7') self.geodict[key] = var self.psep = self.pol_fig.add_subplot(111, aspect='equal') self.psep.set_xlim((0.8, 3.0)) self.psep.set_ylim((-1.4, 1.4)) self.psep.set_xlabel('R [m]') self.psep.set_ylabel('z [m]') nshot_in = int(geoinit['shot']) gc_r, gc_z = map_equ_20180130.get_gc(nshot_in) for key in gc_r.keys(): self.psep.plot(gc_r[key], gc_z[key], 'b-') toolbar = NavigationToolbar2TkAgg(self.pol_canvas, pol_frame) toolbar.update() toolbar = NavigationToolbar2TkAgg(self.mom_canvas, mom_frame) toolbar.update() toolbar = NavigationToolbar2TkAgg(self.profcanvas, profframe) toolbar.update() if __name__ == '__main__': fmframe.mainloop() def surf(self): self.nshot = int(self.geodict['shot'].get()) dianam = self.geodict['dia'].get().strip() expnam = self.geodict['exp'].get().strip() ed = int(self.geodict['ed'].get().strip()) delta_t = float(self.geodict['DeltaT'].get().strip()) # Parameters for kk npfm = 1001 mpfm = 1001 nrzmax = 1000 mom_type = len(momtyp) self.mom_order = int(self.geodict['Nmom'].get().strip()) n_the_u = int(self.geodict['ntheta'].get().strip()) n_rho_u = int(self.geodict['nrho'].get().strip()) tbeg = float(self.geodict['tbeg'].get().strip()) tend = float(self.geodict['tend'].get().strip()) #============== # kk-time grid #============== if eqm.Open(self.nshot, diag=dianam, exp=expnam, ed=ed): eqm._read_profiles() ind_ok = [] tim_old = -np.infty # Allow delta_t for jt, tim in enumerate(eqm.t_eq): if (tim >= tbeg) and (tim <= tend) and (tim > tim_old + delta_t): ind_ok.append(jt) tim_old = tim self.tarr = eqm.t_eq[ind_ok] self.nt = len(self.tarr) self.rho_u = np.linspace(0, 1, n_rho_u) self.q_u = np.zeros((n_rho_u, self.nt)) self.pres_u = np.zeros((n_rho_u, self.nt)) self.rbphi_u = np.zeros((n_rho_u, self.nt)) vmec_dic = { 'nshot':self.nshot, 'mdescur':self.mom_order, \ 'exp':expnam, 'dia':dianam, 'ed':ed, \ 'nrho_nem': 101, 'nthe_nem': 60} self.rsurf = np.zeros((self.nt, n_rho_u, n_the_u)) self.zsurf = np.zeros((self.nt, n_rho_u, n_the_u)) #=========== # Time loop #=========== tf = eqm.tf[ ::-1, ind_ok] q = - eqm.q[ ::-1, ind_ok] pres = eqm.pres[ ::-1, ind_ok] ffs = - 2e-7*eqm.jpol[::-1, ind_ok] q[-1, :] = 2.*q[-2, :] - q[-3, :] nmod = self.mom_order n_mom = nmod*mom_type self.mom_u = np.zeros((self.nt, n_rho_u, n_mom)) self.rc = np.zeros((self.nt, n_rho_u, nmod)) self.rs = np.zeros((self.nt, n_rho_u, nmod)) self.zc = np.zeros((self.nt, n_rho_u, nmod)) self.zs = np.zeros((self.nt, n_rho_u, nmod)) for jt in range(self.nt): rhot = np.sqrt((tf[:, jt] - tf[0, jt])/(tf[-1, jt] - tf[0, jt])) # Profiles: q, pressure, R*Bphi self.q_u[:, jt] = np.interp(self.rho_u, rhot, q[:, jt]) self.pres_u[:, jt] = np.interp(self.rho_u, rhot, pres[:, jt]) self.rbphi_u[:, jt] = np.interp(self.rho_u, rhot, ffs[:, jt]) # NEMEC for magnetic moments pool = Pool(cpu_count()) out = pool.map(nemec.nemec, [(vmec_dic, self.tarr[jt], '%d' %jt) for jt in range(self.nt)]) pool.close() pool.join() for jt in range(self.nt): rho_nem = out[jt][4] for jord in range(nmod): # rho_nem is a grid equispaced in tor. flux, not in rho_tor self.rc[jt, :, jord] = np.interp(self.rho_u, rho_nem, out[jt][0][:, jord]) self.rs[jt, :, jord] = np.interp(self.rho_u, rho_nem, out[jt][1][:, jord]) self.zc[jt, :, jord] = np.interp(self.rho_u, rho_nem, out[jt][2][:, jord]) self.zs[jt, :, jord] = np.interp(self.rho_u, rho_nem, out[jt][3][:, jord]) for jord in range(nmod): fac = 1./(self.rho_u[1:]**jord) self.mom_u[..., 1:, jord] = fac[:]*self.rc[..., 1:, jord] self.mom_u[..., 1:, jord + nmod] = fac[:]*self.rs[..., 1:, jord] self.mom_u[..., 1:, jord + 2*nmod] = fac[:]*self.zc[..., 1:, jord] self.mom_u[..., 1:, jord + 3*nmod] = fac[:]*self.zs[..., 1:, jord] self.mom_u[..., 0, jord] = self.rc[..., 0, jord] self.mom_u[..., 0, jord + nmod] = 0. self.mom_u[..., 0, jord + 2*nmod] = self.zc[..., 0, jord] self.mom_u[..., 0, jord + 3*nmod] = 0. self.mom_u *= 100. self.rsurf, self.zsurf = mom2rz.mom2rz( self.rc, self.rs, \ self.zc, self.zs, nthe=n_the_u) # End of time loop self.begin() def store_u(self): tlbl = 'Time'.ljust(20) + 'Seconds' mlbl = 'MOMENT INDEX' dlbl = 'FOURIER MOMENTS'.ljust(20) + 'CM' rholbl = 'RHO_TOR' thlbl = 'THETA'.ljust(20) + 'RAD' rlbl = 'MAJOR RADIUS'.ljust(20) + 'M' zlbl = 'VERTICAL POSITION'.ljust(20) + 'M' n_the_u = self.rsurf.shape[2] theta = np.linspace(0, 2*np.pi, n_the_u) # NUBEAM R,z=f(t,rho,theta) uf_d = { 'pre': 'R', 'ext': 'SURF', 'shot': self.nshot, \ 'grid': {'X': {'lbl': tlbl , 'arr': self.tarr}, \ 'Y': {'lbl': rholbl, 'arr': self.rho_u}, \ 'Z': {'lbl': thlbl , 'arr': theta} }, \ 'data': {'lbl': rlbl, 'arr': self.rsurf} } ufiles.WU(uf_d) uf_d = { 'pre': 'Z', 'ext': 'SURF', 'shot': self.nshot, \ 'grid': {'X': {'lbl': tlbl , 'arr': self.tarr}, \ 'Y': {'lbl': rholbl, 'arr': self.rho_u}, \ 'Z': {'lbl': thlbl , 'arr': theta} }, \ 'data': {'lbl': zlbl, 'arr': self.zsurf} } ufiles.WU(uf_d) # q profile qlbl = 'Q' uf_d = { 'pre': 'Q', 'ext': 'EQ', 'shot': self.nshot, \ 'grid': {'X': {'lbl': tlbl , 'arr': self.tarr}, \ 'Y': {'lbl': rholbl, 'arr': self.rho_u} }, \ 'data': {'lbl': qlbl, 'arr': self.q_u} } ufiles.WU(uf_d) # Pressure profile plbl = 'P'.ljust(20) + '[Pa]' uf_d={ 'pre': 'P', 'ext': 'EQ', 'shot': self.nshot, \ 'grid': {'X': {'lbl': tlbl , 'arr': self.tarr}, \ 'Y': {'lbl': rholbl, 'arr': self.rho_u} }, \ 'data': {'lbl': plbl, 'arr': self.pres_u} } ufiles.WU(uf_d) # R*Bphi rblbl = 'R*Bphi'.ljust(20) + '[T*m]' uf_d={ 'pre': 'F', 'ext': 'EQ', 'shot': self.nshot, \ 'grid': {'X': {'lbl': tlbl , 'arr': self.tarr}, \ 'Y': {'lbl': rholbl, 'arr': self.rho_u} }, 'data': {'lbl': rblbl, 'arr': self.rbphi_u} } ufiles.WU(uf_d) # Fourier moments n_mom = self.mom_u.shape[-1] marr = 1 + np.arange(n_mom) uf_d={ 'pre': 'M', 'ext': 'MMX', 'shot': self.nshot, \ 'grid': {'X': {'lbl': tlbl , 'arr': self.tarr}, \ 'Y': {'lbl': rholbl, 'arr': self.rho_u}, \ 'Z': {'lbl': mlbl , 'arr': marr} }, \ 'data': {'lbl': dlbl, 'arr': self.mom_u} } ufiles.WU(uf_d) #------------ # Animation #------------ def on_click(self, event): if event.widget.identify(event.x, event.y) == 'label': self.jtab = event.widget.index('@%d,%d' % (event.x, event.y)) self.update_plot() def begin(self): self.stop = True self.jtab = 0 self.jt = 0 self.set_plots() def Pause(self): self.stop = True self.play_button['image'] = self.playfig self.play_button['command'] = self.Play def Forward(self): self.stop = True self.play_button['image'] = self.playfig self.play_button['command'] = self.Play self.jt += 1 self.jt = self.jt%self.nt self.update_plot() def Backward(self): self.stop = True self.play_button['image'] = self.playfig self.play_button['command'] = self.Play self.jt -= 1 self.jt = self.jt%self.nt self.update_plot() def Play(self): self.stop = False self.play_button['image'] = self.pausefig self.play_button['command'] = self.Pause while self.jt < self.nt-1 and not self.stop: self.jt += 1 self.update_plot() self.pol_canvas.start_event_loop(self.timeout) def set_plots(self): # Scale bar self.crntsc = tk.Scale(self.toolframe, command=self.jump, \ orient=tk.HORIZONTAL, length=300) self.crntsc.pack(side=tk.LEFT) # Poloidal plot self.tim0 = self.pol_fig.text(.5, .96, '', ha='center', va='top') self.scat = self.pol_fig.add_subplot(111, aspect='equal') self.scat.set_xlim((0.8, 3.0)) self.scat.set_ylim((-1.4, 1.4)) self.scat.set_xlabel('R [m]') self.scat.set_ylabel('z [m]') gc_r, gc_z = map_equ_20180130.get_gc() for key in gc_r.keys(): self.scat.plot(gc_r[key], gc_z[key], 'b-') self.rhoplot = {} self.theplot = {} self.theplot2 = {} nt, n_rho_u, n_the_u = self.rsurf.shape for jrho in range(n_rho_u): self.theplot[jrho], = self.scat.plot([], [], 'g-') self.theplot2[jrho], = self.scat.plot([], [], 'g-') for jthe in range(n_the_u): self.rhoplot[jthe], = self.scat.plot([], [], 'r-') # Moments self.tim1 = self.mom_fig.text(.5, .96, '', ha='center', va='top') mom_type = len(momtyp) ncols = self.mom_order nrows = mom_type self.rcp = {} self.rsp = {} self.zcp = {} self.zsp = {} for jm in range(self.mom_order): jplot = jm + 1 xtext = 0.1 + (float(jm)*0.94)/float(self.mom_order) self.mom_fig.text(xtext, 0.93, '%dth moment' %jm, ha='center', va='top') momp = self.mom_fig.add_subplot(nrows, ncols, jplot) momp.set_xlabel(r'$\rho_{tor}$') self.rcp[jm], = momp.plot(self.rho_u, self.rc[0, :, jm]) if jm == 0: momp.set_ylabel('R cos') momp = self.mom_fig.add_subplot(nrows, ncols, jplot + self.mom_order) self.rsp[jm], = momp.plot(self.rho_u, self.rs[0, :, jm]) if jm == 0: momp.set_ylabel('R sin') momp = self.mom_fig.add_subplot(nrows, ncols, jplot + 2*self.mom_order) self.zcp[jm], = momp.plot(self.rho_u, self.zc[0, :, jm]) if jm == 0: momp.set_ylabel('z cos') momp = self.mom_fig.add_subplot(nrows, ncols, jplot + 3*self.mom_order) self.zsp[jm], = momp.plot(self.rho_u, self.zs[0, :, jm]) if jm == 0: momp.set_ylabel('z sin') # Profiles self.tim2 = self.proffig.text(.5, .97, '', ha='center', va='top') self.qplot, = self.qsub.plot( self.rho_u, self.q_u[:, 0]) self.pplot, = self.psub.plot( self.rho_u, self.pres_u[:, 0]) self.rbplot, = self.rbsub.plot(self.rho_u, self.rbphi_u[:, 0]) # Update self.update_plot() def jump(self, arg): self.jt = int(float(arg)/100. * (self.nt-1)) self.update_plot(reset=False) def update_plot(self, reset=True): if reset: self.crntsc.set(float(self.jt)/(self.nt - 1)*100.) # return tstr = '# %d, Time:%6.3f s' %(self.nshot, self.tarr[self.jt]) if self.jtab == 0: # Poloidal nt, n_rho_u, n_the_u = self.rsurf.shape for jrho in range(n_rho_u): self.theplot[jrho].set_data(self.rsurf[self.jt, jrho, :], self.zsurf[self.jt, jrho, :]) self.theplot2[jrho].set_data(self.rsurf[self.jt, jrho, [-1, 0]], self.zsurf[self.jt, jrho, [-1, 0]]) for jthe in range(n_the_u): self.rhoplot[jthe].set_data(self.rsurf[self.jt, :, jthe], self.zsurf[self.jt, :, jthe]) self.tim0.set_text(tstr) self.pol_canvas.draw() elif self.jtab == 1: # Moments for jm in range(self.mom_order): self.rcp[jm].set_ydata(self.rc[self.jt][:, jm]) self.rsp[jm].set_ydata(self.rs[self.jt][:, jm]) self.zcp[jm].set_ydata(self.zc[self.jt][:, jm]) self.zsp[jm].set_ydata(self.zs[self.jt][:, jm]) self.tim1.set_text(tstr) self.mom_canvas.draw() elif self.jtab == 2: # Profiles self.qsub.set_ylim((0, 1.1*np.max(self.q_u[:, self.jt]))) self.qplot.set_ydata(self.q_u[:, self.jt]) self.psub.set_ylim((0, 1.1*np.max(self.pres_u[:, self.jt]))) self.pplot.set_ydata(self.pres_u[:, self.jt]) self.rbsub.set_ylim((0, 1.1*np.max(self.rbphi_u[:, self.jt]))) self.rbplot.set_ydata(self.rbphi_u[:, self.jt]) self.tim2.set_text(tstr) self.profcanvas.draw()
def DDA1(nshot, signals, topframe=None): if topframe is None: topframe = tk.Toplevel() topframe.title('Several signals') topframe.geometry('1200x960') topframe.configure(bg=bgc) nb = ttk.Notebook(topframe, name='nb') nb.pack(side=tk.TOP, fill=tk.X) sigframe = tk.Frame(nb) nbiframe = tk.Frame(nb) lhframe = tk.Frame(nb) icrframe = tk.Frame(nb) txt = {sigframe: 'Time traces', nbiframe: 'NBI sources', \ lhframe: 'Lower hybrid', icrframe: 'ICRF antennas'} for frame in sigframe, nbiframe, lhframe, icrframe: tk.Label(frame, text=txt[frame]).pack(side=tk.TOP) nb.add(frame, text=txt[frame]) udb = '%s/udb/%d' %(os.getenv('HOME'), nshot) os.system('mkdir -p %s' %udb) #================ # Ipl, Bt, Uloop #================ sfigframe = tk.Frame(sigframe) sfigframe.pack(side=tk.TOP, fill=tk.X) sigfig = Figure(figsize=(8., 8.7), dpi=100) sig_can = FigureCanvasTkAgg(sigfig, master=sfigframe) sig_can._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) sigfig.subplots_adjust(left=0.1, bottom=0.06, right=0.95, top=0.92, hspace=0) sigfig.text(.5, .95, '#%d time traces' %nshot, ha='center') n_ct = 1 n_sub = 3 for dda, val in signals.iteritems(): for dtype, par in val.iteritems(): dlbl = par['lbl'] fac = par['fac'] ylab = par['yl'] y_tick = par['ytk'] print dda, dtype, fac mds = rmds(nshot, dda, dtype) tim = mds.time dat = mds.data ntim = len(tim) print('ntlen is %d' %ntim) # Plot index = np.where(tim>0) tarr = tim[index] darr = fac*dat[index] print darr.shape darr[0] = np.abs(darr[0]) # TRANSP determines sign(Ipl) from 1st entry ax = sigfig.add_subplot(n_sub, 1, n_ct) ax.plot(tarr, darr) ax.set_ylabel(ylab, fontsize=fsize) ax.set_yticks(y_tick) n_ct += 1 uf_d = { 'pre': dda, 'ext': dtype.strip(), 'shot': nshot, \ 'grid': {'X': {'lbl': tlbl, 'arr': tarr}}, \ 'data': {'lbl': dlbl, 'arr': darr} } ufiles.WU(uf_d) ax.set_xlabel('Time [s]', fontsize=fsize) sig_can.mpl_connect('button_press_event', fconf.on_click) toolbar = NavigationToolbar2TkAgg(sig_can, sigframe) toolbar.update()
class DGSPlannerGUI(QtGui.QWidget): def __init__(self,ol=None,parent=None): # pylint: disable=unused-argument,super-on-old-class super(DGSPlannerGUI,self).__init__(parent) #OrientedLattice if ValidateOL(ol): self.ol=ol else: self.ol=mantid.geometry.OrientedLattice() self.masterDict=dict() #holds info about instrument and ranges self.updatedInstrument=False self.updatedOL=False self.wg=None #workspace group self.instrumentWidget=InstrumentSetupWidget.InstrumentSetupWidget(self) self.setLayout(QtGui.QHBoxLayout()) controlLayout=QtGui.QVBoxLayout() controlLayout.addWidget(self.instrumentWidget) self.ublayout=QtGui.QHBoxLayout() self.classic=ClassicUBInputWidget.ClassicUBInputWidget(self.ol) self.ublayout.addWidget(self.classic,alignment=QtCore.Qt.AlignTop,stretch=1) self.matrix=MatrixUBInputWidget.MatrixUBInputWidget(self.ol) self.ublayout.addWidget(self.matrix,alignment=QtCore.Qt.AlignTop,stretch=1) controlLayout.addLayout(self.ublayout) self.dimensionWidget=DimensionSelectorWidget.DimensionSelectorWidget(self) controlLayout.addWidget(self.dimensionWidget) plotControlLayout=QtGui.QGridLayout() self.plotButton=QtGui.QPushButton("Plot",self) self.oplotButton=QtGui.QPushButton("Overplot",self) self.helpButton=QtGui.QPushButton("?",self) self.colorLabel=QtGui.QLabel('Color by angle',self) self.colorButton=QtGui.QCheckBox(self) self.colorButton.toggle() self.aspectLabel=QtGui.QLabel('Aspect ratio 1:1',self) self.aspectButton=QtGui.QCheckBox(self) self.saveButton=QtGui.QPushButton("Save Figure",self) plotControlLayout.addWidget(self.plotButton,0,0) plotControlLayout.addWidget(self.oplotButton,0,1) plotControlLayout.addWidget(self.colorLabel,0,2,QtCore.Qt.AlignRight) plotControlLayout.addWidget(self.colorButton,0,3) plotControlLayout.addWidget(self.aspectLabel,0,4,QtCore.Qt.AlignRight) plotControlLayout.addWidget(self.aspectButton,0,5) plotControlLayout.addWidget(self.helpButton,0,6) plotControlLayout.addWidget(self.saveButton,0,7) controlLayout.addLayout(plotControlLayout) self.layout().addLayout(controlLayout) #figure self.figure=Figure() self.figure.patch.set_facecolor('white') self.canvas=FigureCanvas(self.figure) self.grid_helper = GridHelperCurveLinear((self.tr, self.inv_tr)) self.trajfig = Subplot(self.figure, 1, 1, 1, grid_helper=self.grid_helper) self.trajfig.hold(True) self.figure.add_subplot(self.trajfig) self.layout().addWidget(self.canvas) self.needToClear=False self.saveDir='' #connections self.matrix.UBmodel.changed.connect(self.updateUB) self.matrix.UBmodel.changed.connect(self.classic.updateOL) self.classic.changed.connect(self.matrix.UBmodel.updateOL) self.classic.changed.connect(self.updateUB) self.instrumentWidget.changed.connect(self.updateParams) self.dimensionWidget.changed.connect(self.updateParams) self.plotButton.clicked.connect(self.updateFigure) self.oplotButton.clicked.connect(self.updateFigure) self.helpButton.clicked.connect(self.help) self.saveButton.clicked.connect(self.save) #force an update of values self.instrumentWidget.updateAll() self.dimensionWidget.updateChanges() #help self.assistantProcess = QtCore.QProcess(self) # pylint: disable=protected-access self.collectionFile=os.path.join(mantid._bindir,'../docs/qthelp/MantidProject.qhc') version = ".".join(mantid.__version__.split(".")[:2]) self.qtUrl='qthelp://org.sphinx.mantidproject.'+version+'/doc/interfaces/DGSPlanner.html' self.externalUrl='http://docs.mantidproject.org/nightly/interfaces/DGSPlanner.html' #control for cancel button self.iterations=0 self.progress_canceled=False #register startup mantid.UsageService.registerFeatureUsage("Interface","DGSPlanner",False) @QtCore.pyqtSlot(mantid.geometry.OrientedLattice) def updateUB(self,ol): self.ol=ol self.updatedOL=True self.trajfig.clear() @QtCore.pyqtSlot(dict) def updateParams(self,d): if self.sender() is self.instrumentWidget: self.updatedInstrument=True if 'dimBasis' in d and 'dimBasis' in self.masterDict and d['dimBasis']!=self.masterDict['dimBasis']: self.needToClear=True if 'dimIndex' in d and 'dimIndex' in self.masterDict and d['dimIndex']!=self.masterDict['dimIndex']: self.needToClear=True self.masterDict.update(copy.deepcopy(d)) def help(self): try: import pymantidplot pymantidplot.proxies.showCustomInterfaceHelp('DGSPlanner') except ImportError: self.assistantProcess.close() self.assistantProcess.waitForFinished() helpapp = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.BinariesPath) + QtCore.QDir.separator() helpapp += 'assistant' args = ['-enableRemoteControl', '-collectionFile',self.collectionFile,'-showUrl',self.qtUrl] if os.path.isfile(helpapp) and os.path.isfile(self.collectionFile): self.assistantProcess.close() self.assistantProcess.waitForFinished() self.assistantProcess.start(helpapp, args) else: mqt.MantidQt.API.MantidDesktopServices.openUrl(QtCore.QUrl(self.externalUrl)) def closeEvent(self,event): self.assistantProcess.close() self.assistantProcess.waitForFinished() event.accept() # pylint: disable=too-many-locals def updateFigure(self): # pylint: disable=too-many-branches if self.updatedInstrument or self.progress_canceled: self.progress_canceled=False #get goniometer settings first gonioAxis0values=numpy.arange(self.masterDict['gonioMinvals'][0],self.masterDict['gonioMaxvals'][0] +0.1*self.masterDict['gonioSteps'][0],self.masterDict['gonioSteps'][0]) gonioAxis1values=numpy.arange(self.masterDict['gonioMinvals'][1],self.masterDict['gonioMaxvals'][1] +0.1*self.masterDict['gonioSteps'][1],self.masterDict['gonioSteps'][1]) gonioAxis2values=numpy.arange(self.masterDict['gonioMinvals'][2],self.masterDict['gonioMaxvals'][2] +0.1*self.masterDict['gonioSteps'][2],self.masterDict['gonioSteps'][2]) self.iterations=len(gonioAxis0values)*len(gonioAxis1values)*len(gonioAxis2values) if self.iterations>10: reply = QtGui.QMessageBox.warning(self, 'Goniometer',"More than 10 goniometer settings. This might be long.\n" "Are you sure you want to proceed?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply==QtGui.QMessageBox.No: return if self.wg is not None: mantid.simpleapi.DeleteWorkspace(self.wg) mantid.simpleapi.LoadEmptyInstrument(mantid.api.ExperimentInfo.getInstrumentFilename(self.masterDict['instrument']), OutputWorkspace="__temp_instrument") if self.masterDict['instrument']=='HYSPEC': mantid.simpleapi.AddSampleLog(Workspace="__temp_instrument",LogName='msd',LogText='1798.5',LogType='Number Series') mantid.simpleapi.AddSampleLog(Workspace="__temp_instrument",LogName='s2', LogText=str(self.masterDict['S2']),LogType='Number Series') mantid.simpleapi.LoadInstrument(Workspace="__temp_instrument", RewriteSpectraMap=True, InstrumentName="HYSPEC") #masking if 'maskFilename' in self.masterDict and len(self.masterDict['maskFilename'].strip())>0: try: __maskWS=mantid.simpleapi.Load(self.masterDict['maskFilename']) mantid.simpleapi.MaskDetectors(Workspace="__temp_instrument",MaskedWorkspace=__maskWS) except (ValueError,RuntimeError) as e: reply = QtGui.QMessageBox.critical(self, 'Error',"The following error has occured in loading the mask:\n"+ str(e)+"\nDo you want to continue without mask?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply==QtGui.QMessageBox.No: return if self.masterDict['makeFast']: sp=range(mantid.mtd["__temp_instrument"].getNumberHistograms()) tomask=sp[::4]+sp[1::4]+sp[2::4] mantid.simpleapi.MaskDetectors("__temp_instrument",SpectraList=tomask) i=0 groupingStrings=[] progressDialog = QtGui.QProgressDialog(self) progressDialog.setMinimumDuration(0) progressDialog.setCancelButtonText("&Cancel") progressDialog.setRange(0, self.iterations) progressDialog.setWindowTitle("DGSPlanner progress") for g0 in gonioAxis0values: for g1 in gonioAxis1values: for g2 in gonioAxis2values: name="__temp_instrument"+str(i) i+=1 progressDialog.setValue(i) progressDialog.setLabelText("Creating workspace %d of %d..." % (i, self.iterations)) QtGui.qApp.processEvents() if progressDialog.wasCanceled(): self.progress_canceled=True progressDialog.close() return groupingStrings.append(name) mantid.simpleapi.CloneWorkspace("__temp_instrument",OutputWorkspace=name) mantid.simpleapi.SetGoniometer(Workspace=name, Axis0=str(g0)+","+self.masterDict['gonioDirs'][0]+ ","+str(self.masterDict['gonioSenses'][0]), Axis1=str(g1)+","+self.masterDict['gonioDirs'][1]+ ","+str(self.masterDict['gonioSenses'][1]), Axis2=str(g2)+","+self.masterDict['gonioDirs'][2]+ ","+str(self.masterDict['gonioSenses'][2])) progressDialog.close() mantid.simpleapi.DeleteWorkspace("__temp_instrument") self.wg=mantid.simpleapi.GroupWorkspaces(groupingStrings,OutputWorkspace="__temp_instrument") self.updatedInstrument=False #set the UB if self.updatedOL or not self.wg[0].sample().hasOrientedLattice(): mantid.simpleapi.SetUB(self.wg,UB=self.ol.getUB()) self.updatedOL=False #calculate coverage dimensions=['Q1','Q2','Q3','DeltaE'] progressDialog = QtGui.QProgressDialog(self) progressDialog.setMinimumDuration(0) progressDialog.setCancelButtonText("&Cancel") progressDialog.setRange(0, self.iterations) progressDialog.setWindowTitle("DGSPlanner progress") for i in range(self.iterations): progressDialog.setValue(i) progressDialog.setLabelText("Calculating orientation %d of %d..." % (i, self.iterations)) QtGui.qApp.processEvents() if progressDialog.wasCanceled(): self.progress_canceled=True progressDialog.close() return __mdws=mantid.simpleapi.CalculateCoverageDGS(self.wg[i], Q1Basis=self.masterDict['dimBasis'][0], Q2Basis=self.masterDict['dimBasis'][1], Q3Basis=self.masterDict['dimBasis'][2], IncidentEnergy=self.masterDict['Ei'], Dimension1=dimensions[self.masterDict['dimIndex'][0]], Dimension1Min=float2Input(self.masterDict['dimMin'][0]), Dimension1Max=float2Input(self.masterDict['dimMax'][0]), Dimension1Step=float2Input(self.masterDict['dimStep'][0]), Dimension2=dimensions[self.masterDict['dimIndex'][1]], Dimension2Min=float2Input(self.masterDict['dimMin'][1]), Dimension2Max=float2Input(self.masterDict['dimMax'][1]), Dimension2Step=float2Input(self.masterDict['dimStep'][1]), Dimension3=dimensions[self.masterDict['dimIndex'][2]], Dimension3Min=float2Input(self.masterDict['dimMin'][2]), Dimension3Max=float2Input(self.masterDict['dimMax'][2]), Dimension4=dimensions[self.masterDict['dimIndex'][3]], Dimension4Min=float2Input(self.masterDict['dimMin'][3]), Dimension4Max=float2Input(self.masterDict['dimMax'][3])) if i==0: intensity=__mdws.getSignalArray()[:,:,0,0]*1. #to make it writeable else: if self.colorButton.isChecked(): tempintensity= __mdws.getSignalArray()[:,:,0,0] intensity[numpy.where( tempintensity>0)]=i+1. else: tempintensity= __mdws.getSignalArray()[:,:,0,0] intensity[numpy.where( tempintensity>0)]=1. progressDialog.close() x = numpy.linspace(__mdws.getDimension(0).getMinimum(), __mdws.getDimension(0).getMaximum(),intensity.shape[0] ) y = numpy.linspace(__mdws.getDimension(1).getMinimum(), __mdws.getDimension(1).getMaximum(),intensity.shape[1] ) Y,X = numpy.meshgrid(y,x) xx, yy = self.tr(X, Y) Z=numpy.ma.masked_array(intensity,intensity==0) Z = Z[:-1, :-1] #plotting if self.sender() is self.plotButton or self.needToClear: self.figure.clear() self.trajfig.clear() self.figure.add_subplot(self.trajfig) self.needToClear=False self.trajfig.pcolorfast(xx,yy,Z) if self.aspectButton.isChecked(): self.trajfig.set_aspect(1.) else: self.trajfig.set_aspect('auto') self.trajfig.set_xlabel(self.masterDict['dimNames'][0]) self.trajfig.set_ylabel(self.masterDict['dimNames'][1]) self.trajfig.grid(True) self.canvas.draw() mantid.simpleapi.DeleteWorkspace(__mdws) def save(self): fileName = str(QtGui.QFileDialog.getSaveFileName(self, 'Save Plot', self.saveDir,'*.png')) data = "Instrument "+self.masterDict['instrument']+'\n' if self.masterDict['instrument']=='HYSPEC': data+= "S2 = "+str(self.masterDict['S2'])+'\n' data+= "Ei = "+str(self.masterDict['Ei'])+' meV\n' data+= "Goniometer values:\n" gonioAxis0values=numpy.arange(self.masterDict['gonioMinvals'][0],self.masterDict['gonioMaxvals'][0] +0.1*self.masterDict['gonioSteps'][0],self.masterDict['gonioSteps'][0]) gonioAxis1values=numpy.arange(self.masterDict['gonioMinvals'][1],self.masterDict['gonioMaxvals'][1] +0.1*self.masterDict['gonioSteps'][1],self.masterDict['gonioSteps'][1]) gonioAxis2values=numpy.arange(self.masterDict['gonioMinvals'][2],self.masterDict['gonioMaxvals'][2] +0.1*self.masterDict['gonioSteps'][2],self.masterDict['gonioSteps'][2]) for g0 in gonioAxis0values: for g1 in gonioAxis1values: for g2 in gonioAxis2values: data+=" "+self.masterDict['gonioLabels'][0]+" = "+str(g0) data+=" "+self.masterDict['gonioLabels'][1]+" = "+str(g1) data+=" "+self.masterDict['gonioLabels'][2]+" = "+str(g2)+'\n' data+= "Lattice parameters:\n" data+=" a = "+str(self.ol.a())+" b = "+str(self.ol.b())+" c = "+str(self.ol.c())+'\n' data+=" alpha = "+str(self.ol.alpha())+" beta = "+str(self.ol.beta())+" gamma = "+str(self.ol.gamma())+'\n' data+= "Orientation vectors:\n" data+=" u = "+str(self.ol.getuVector())+'\n' data+=" v = "+str(self.ol.getvVector())+'\n' data+="Integrated "+self.masterDict['dimNames'][2]+" between "+\ str(self.masterDict['dimMin'][2])+" and "+str(self.masterDict['dimMax'][2])+'\n' data+="Integrated "+self.masterDict['dimNames'][3]+" between "+\ str(self.masterDict['dimMin'][3])+" and "+str(self.masterDict['dimMax'][3])+'\n' info=self.figure.text(0.2,0,data,verticalalignment='top') self.figure.savefig(fileName,bbox_inches='tight',additional_artists=info) self.saveDir=os.path.dirname(fileName) def tr(self,x, y): x, y = numpy.asarray(x), numpy.asarray(y) #one of the axes is energy if self.masterDict['dimIndex'][0]==3 or self.masterDict['dimIndex'][1]==3: return x,y else: h1,k1,l1=(float(temp) for temp in self.masterDict['dimBasis'][self.masterDict['dimIndex'][0]].split(',')) h2,k2,l2=(float(temp) for temp in self.masterDict['dimBasis'][self.masterDict['dimIndex'][1]].split(',')) angle=numpy.radians(self.ol.recAngle(h1,k1,l1,h2,k2,l2)) return 1.*x+numpy.cos(angle)*y, numpy.sin(angle)*y def inv_tr(self,x,y): x, y = numpy.asarray(x), numpy.asarray(y) #one of the axes is energy if self.masterDict['dimIndex'][0]==3 or self.masterDict['dimIndex'][1]==3: return x,y else: h1,k1,l1=(float(temp) for temp in self.masterDict['dimBasis'][self.masterDict['dimIndex'][0]].split(',')) h2,k2,l2=(float(temp) for temp in self.masterDict['dimBasis'][self.masterDict['dimIndex'][1]].split(',')) angle=numpy.radians(self.ol.recAngle(h1,k1,l1,h2,k2,l2)) return 1.*x-y/numpy.tan(angle), y/numpy.sin(angle)
def make_movie(args): rng = galsim.BaseDeviate(args.seed) u = galsim.UniformDeviate(rng) # Generate 1D Gaussian random fields for each aberration. t = np.arange(-args.n/2, args.n/2) corr = np.exp(-0.5*t**2/args.ell**2) pk = np.fft.fft(np.fft.fftshift(corr)) ak = np.sqrt(2*pk) phi = np.random.uniform(size=(args.n, args.jmax)) zk = ak[:, None]*np.exp(2j*np.pi*phi) aberrations = args.n/2*np.fft.ifft(zk, axis=0).real measured_std = np.mean(np.std(aberrations, axis=0)) aberrations *= args.sigma/measured_std aberrations -= np.mean(aberrations, axis=0) if args.nlayers > 0: # For the atmosphere screens, we first estimates weights, so that the turbulence is dominated by # the lower layers consistent with direct measurements. The specific values we use are from # SCIDAR measurements on Cerro Pachon as part of the 1998 Gemini site selection process # (Ellerbroek 2002, JOSA Vol 19 No 9). Ellerbroek_alts = [0.0, 2.58, 5.16, 7.73, 12.89, 15.46] # km Ellerbroek_weights = [0.652, 0.172, 0.055, 0.025, 0.074, 0.022] Ellerbroek_interp = galsim.LookupTable(Ellerbroek_alts, Ellerbroek_weights, interpolant='linear') alts = np.max(Ellerbroek_alts)*np.arange(args.nlayers)/(args.nlayers-1) weights = Ellerbroek_interp(alts) # interpolate the weights weights /= sum(weights) # and renormalize spd = [] # Wind speed in m/s dirn = [] # Wind direction in radians r0_500 = [] # Fried parameter in m at a wavelength of 500 nm. for i in range(args.nlayers): spd.append(u()*args.max_speed) # Use a random speed between 0 and args.max_speed dirn.append(u()*360*galsim.degrees) # And an isotropically distributed wind direction. r0_500.append(args.r0_500*weights[i]**(-3./5)) print("Adding layer at altitude {:5.2f} km with velocity ({:5.2f}, {:5.2f}) m/s, " "and r0_500 {:5.3f} m." .format(alts[i], spd[i]*dirn[i].cos(), spd[i]*dirn[i].sin(), r0_500[i])) # Make two identical Atmospheres. They will diverge when one gets drawn using Fourier # optics and the other gets drawn with geometric optics. fft_atm = galsim.Atmosphere(r0_500=r0_500, speed=spd, direction=dirn, altitude=alts, rng=rng.duplicate(), screen_size=args.screen_size, screen_scale=args.screen_scale) geom_atm = galsim.Atmosphere(r0_500=r0_500, speed=spd, direction=dirn, altitude=alts, rng=rng.duplicate(), screen_size=args.screen_size, screen_scale=args.screen_scale) else: fft_atm = galsim.PhaseScreenList() geom_atm = galsim.PhaseScreenList() # Before either of this has been instantiated, they are identical assert fft_atm == geom_atm # If any AtmosphericScreens are included, we manually instantiate here so we can have a # uniformly updating ProgressBar both here and below when actually drawing PSFs. Normally, it's # okay to let the atms automatically instantiate, which happens when the first PSF is drawn, or # the first wavefront is queried. if args.nlayers > 0: print("Instantiating screens") with ProgressBar(2*args.nlayers) as bar: if args.do_fft: fft_atm.instantiate(_bar=bar) if args.do_geom: r0 = args.r0_500*(args.lam/500)**1.2 geom_atm.instantiate(kmax=0.2/r0, _bar=bar) # After instantiation, they're only equal if there's no atmosphere. assert fft_atm != geom_atm # Setup Fourier and geometric apertures fft_aper = galsim.Aperture(args.diam, args.lam, obscuration=args.obscuration, pad_factor=args.pad_factor, oversampling=args.oversampling, nstruts=args.nstruts, strut_thick=args.strut_thick, strut_angle=args.strut_angle*galsim.degrees) geom_aper = galsim.Aperture(args.diam, args.lam, obscuration=args.obscuration, pad_factor=args.geom_oversampling, oversampling=0.5, nstruts=args.nstruts, strut_thick=args.strut_thick, strut_angle=args.strut_angle*galsim.degrees) scale = args.size/args.nx extent = np.r_[-1,1,-1,1]*args.size/2 fft_img_sum = galsim.ImageD(args.nx, args.nx, scale=scale) geom_img_sum = galsim.ImageD(args.nx, args.nx, scale=scale) # Code to setup the Matplotlib animation. metadata = dict(title="FFT vs geom movie", artist='Matplotlib') if args.make_movie: writer = anim.FFMpegWriter(fps=15, bitrate=10000, metadata=metadata) fig = Figure(facecolor='k', figsize=(16, 9)) FigureCanvasAgg(fig) fft_ax = fig.add_axes([0.07, 0.08, 0.36, 0.9]) fft_ax.set_xlabel("Arcsec") fft_ax.set_ylabel("Arcsec") fft_ax.set_title("Fourier Optics") fft_im = fft_ax.imshow(np.ones((args.nx, args.nx), dtype=float), animated=True, extent=extent, vmin=0.0, vmax=args.vmax) # Axis for the wavefront image on the right. geom_ax = fig.add_axes([0.50, 0.08, 0.36, 0.9]) geom_ax.set_xlabel("Arcsec") geom_ax.set_ylabel("Arcsec") geom_ax.set_title("Geometric Optics") geom_im = geom_ax.imshow(np.ones((args.nx, args.nx), dtype=float), animated=True, extent=extent, vmin=0.0, vmax=args.vmax) # Color items white to show up on black background for ax in [fft_ax, geom_ax]: for _, spine in ax.spines.items(): spine.set_color('w') ax.title.set_color('w') ax.xaxis.label.set_color('w') ax.yaxis.label.set_color('w') ax.tick_params(axis='both', colors='w') ztext = [] for i in range(2, args.jmax+1): x = 0.88 y = 0.1 + (args.jmax-i)/args.jmax*0.8 ztext.append(fig.text(x, y, "Z{:d} = {:5.3f}".format(i, 0.0))) ztext[-1].set_color('w') M_fft = fft_ax.text(0.02, 0.955, '', transform=fft_ax.transAxes) M_fft.set_color('w') M_geom = geom_ax.text(0.02, 0.955, '', transform=geom_ax.transAxes) M_geom.set_color('w') etext_fft = fft_ax.text(0.02, 0.91, '', transform=fft_ax.transAxes) etext_fft.set_color('w') etext_geom = geom_ax.text(0.02, 0.91, '', transform=geom_ax.transAxes) etext_geom.set_color('w') fft_mom = np.empty((args.n, 8), dtype=float) geom_mom = np.empty((args.n, 8), dtype=float) fullpath = args.out+"movie.mp4" subdir, filename = os.path.split(fullpath) if subdir and not os.path.isdir(subdir): os.makedirs(subdir) print("Drawing PSFs") with ProgressBar(args.n) as bar: with writer.saving(fig, fullpath, 100) if args.make_movie else ExitStack(): t0 = 0.0 for i, aberration in enumerate(aberrations): optics = galsim.OpticalScreen(args.diam, obscuration=args.obscuration, aberrations=[0]+aberration.tolist(), annular_zernike=True) if args.do_fft: fft_psl = galsim.PhaseScreenList(fft_atm._layers+[optics]) fft_psf = fft_psl.makePSF( lam=args.lam, aper=fft_aper, t0=t0, exptime=args.time_step) fft_img0 = fft_psf.drawImage(nx=args.nx, ny=args.nx, scale=scale) if args.do_geom: geom_psl = galsim.PhaseScreenList(geom_atm._layers+[optics]) geom_psf = geom_psl.makePSF( lam=args.lam, aper=geom_aper, t0=t0, exptime=args.time_step) geom_img0 = geom_psf.drawImage(nx=args.nx, ny=args.nx, scale=scale, method='phot', n_photons=args.geom_nphot, rng=rng) t0 += args.time_step if args.accumulate: if args.do_fft: fft_img_sum += fft_img0 fft_img = fft_img_sum/(i+1) if args.do_geom: geom_img_sum += geom_img0 geom_img = geom_img_sum/(i+1) else: if args.do_fft: fft_img = fft_img0 if args.do_geom: geom_img = geom_img0 for j, ab in enumerate(aberration): if j == 0: continue ztext[j-1].set_text("Z{:d} = {:5.3f}".format(j+1, ab)) # Calculate simple estimate of ellipticity Is = ("$M_x$={: 6.4f}, $M_y$={: 6.4f}, $M_{{xx}}$={:6.4f}," " $M_{{yy}}$={:6.4f}, $M_{{xy}}$={: 6.4f}") if args.do_fft and (args.make_movie or args.make_plots): fft_im.set_array(fft_img.array) mom_fft = galsim.utilities.unweighted_moments(fft_img, origin=fft_img.true_center) e_fft = galsim.utilities.unweighted_shape(mom_fft) M_fft.set_text(Is.format(mom_fft['Mx']*fft_img.scale, mom_fft['My']*fft_img.scale, mom_fft['Mxx']*fft_img.scale**2, mom_fft['Myy']*fft_img.scale**2, mom_fft['Mxy']*fft_img.scale**2)) etext_fft.set_text("$e_1$={: 6.4f}, $e_2$={: 6.4f}, $r^2$={:6.4f}".format( e_fft['e1'], e_fft['e2'], e_fft['rsqr']*fft_img.scale**2)) fft_mom[i] = (mom_fft['Mx']*fft_img.scale, mom_fft['My']*fft_img.scale, mom_fft['Mxx']*fft_img.scale**2, mom_fft['Myy']*fft_img.scale**2, mom_fft['Mxy']*fft_img.scale**2, e_fft['e1'], e_fft['e2'], e_fft['rsqr']*fft_img.scale**2) if args.do_geom and (args.make_movie or args.make_plots): geom_im.set_array(geom_img.array) mom_geom = galsim.utilities.unweighted_moments(geom_img, origin=geom_img.true_center) e_geom = galsim.utilities.unweighted_shape(mom_geom) M_geom.set_text(Is.format(mom_geom['Mx']*geom_img.scale, mom_geom['My']*geom_img.scale, mom_geom['Mxx']*geom_img.scale**2, mom_geom['Myy']*geom_img.scale**2, mom_geom['Mxy']*geom_img.scale**2)) etext_geom.set_text("$e_1$={: 6.4f}, $e_2$={: 6.4f}, $r^2$={:6.4f}".format( e_geom['e1'], e_geom['e2'], e_geom['rsqr']*geom_img.scale**2)) geom_mom[i] = (mom_geom['Mx']*geom_img.scale, mom_geom['My']*geom_img.scale, mom_geom['Mxx']*geom_img.scale**2, mom_geom['Myy']*geom_img.scale**2, mom_geom['Mxy']*geom_img.scale**2, e_geom['e1'], e_geom['e2'], e_geom['rsqr']*geom_img.scale**2) if args.make_movie: writer.grab_frame(facecolor=fig.get_facecolor()) bar.update() def symmetrize_axis(ax): xlim = ax.get_xlim() ylim = ax.get_ylim() lim = min(xlim[0], ylim[0]), max(xlim[1], ylim[1]) ax.set_xlim(lim) ax.set_ylim(lim) ax.plot(lim, lim) if args.make_plots: # Centroid plot fig = Figure(figsize=(10, 6)) FigureCanvasAgg(fig) axes = [] axes.append(fig.add_subplot(1, 2, 1)) axes.append(fig.add_subplot(1, 2, 2)) axes[0].scatter(fft_mom[:, 0], geom_mom[:, 0]) axes[1].scatter(fft_mom[:, 1], geom_mom[:, 1]) axes[0].set_title("Mx") axes[1].set_title("My") for ax in axes: ax.set_xlabel("Fourier Optics") ax.set_ylabel("Geometric Optics") symmetrize_axis(ax) fig.tight_layout() fig.savefig(args.out+"centroid.png", dpi=300) # Second moment plot fig = Figure(figsize=(16, 6)) FigureCanvasAgg(fig) axes = [] axes.append(fig.add_subplot(1, 3, 1)) axes.append(fig.add_subplot(1, 3, 2)) axes.append(fig.add_subplot(1, 3, 3)) axes[0].scatter(fft_mom[:, 2], geom_mom[:, 2]) axes[1].scatter(fft_mom[:, 3], geom_mom[:, 3]) axes[2].scatter(fft_mom[:, 4], geom_mom[:, 4]) axes[0].set_title("Mxx") axes[1].set_title("Myy") axes[2].set_title("Mxy") for ax in axes: ax.set_xlabel("Fourier Optics") ax.set_ylabel("Geometric Optics") symmetrize_axis(ax) fig.tight_layout() fig.savefig(args.out+"2ndMoment.png", dpi=300) # Ellipticity plot fig = Figure(figsize=(16, 6)) FigureCanvasAgg(fig) axes = [] axes.append(fig.add_subplot(1, 3, 1)) axes.append(fig.add_subplot(1, 3, 2)) axes.append(fig.add_subplot(1, 3, 3)) axes[0].scatter(fft_mom[:, 5], geom_mom[:, 5]) axes[1].scatter(fft_mom[:, 6], geom_mom[:, 6]) axes[2].scatter(fft_mom[:, 7], geom_mom[:, 7]) axes[0].set_title("e1") axes[1].set_title("e2") axes[2].set_title("rsqr") for ax in axes: ax.set_xlabel("Fourier Optics") ax.set_ylabel("Geometric Optics") symmetrize_axis(ax) fig.tight_layout() fig.savefig(args.out+"ellipticity.png", dpi=300)
class SpatialDecisionDockWidget(QtGui.QDockWidget, FORM_CLASS): closingPlugin = QtCore.pyqtSignal() # custom signals updateAttribute = QtCore.pyqtSignal(str) 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() self.canvas.setSelectionColor(QtGui.QColor(255, 0, 0)) # set up GUI operation signals # data self.iface.projectRead.connect(self.updateLayers) self.iface.newProjectCreated.connect(self.updateLayers) self.selectLayerCombo.activated.connect(self.setSelectedLayer) self.selectAttributeCombo.activated.connect(self.setSelectedAttribute) self.showButton.clicked.connect(self.updateValueWidget) # signals self.canvas.renderStarting.connect(self.loadSymbols) self.canvas.selectionChanged.connect(self.updateValueWidget) # analysis self.graph = QgsGraph() self.tied_points = [] self.shortestRouteButton.clicked.connect(self.calculateRoute) self.clearRouteButton.clicked.connect(self.deleteRoutes) self.assignButton.clicked.connect(self.assignFacility) self.clearAssignmentButton.clicked.connect(self.clearAssignment) self.changeStatusButton.clicked.connect(self.changeEventStatus) # visualisation # set current UI restrictions # initialisation self.eventlayer = uf.getLegendLayerByName(self.iface, 'Reports') self.hospitalLayer = uf.getLegendLayerByName(self.iface, 'Hospital') self.firestationLayer = uf.getLegendLayerByName(self.iface, 'Firestation') self.hospital_name='' self.firestation_name='' self.event_source=self.eventlayer.selectedFeatures() # example_chart # add matplotlib Figure to chartFrame self.chart_figure = Figure() self.chart_subplot_radar = self.chart_figure.add_subplot(211, projection='polar') self.chart_subplot_bar = self.chart_figure.add_subplot(212) self.chart_figure.tight_layout() self.chart_figure.text(0.05, 0.955, 'Data from:', fontsize = 12, horizontalalignment = 'left') self.chart_figure.text(0.05, 0.93, self.getWindDate(), fontsize = 12, fontweight='bold', horizontalalignment = 'left') self.chart_canvas = FigureCanvas(self.chart_figure) self.chartLayout.addWidget(self.chart_canvas) self.updateLayers() # run simple tests def closeEvent(self, event): # disconnect interface signals self.iface.projectRead.disconnect(self.updateLayers) self.iface.newProjectCreated.disconnect(self.updateLayers) self.closingPlugin.emit() event.accept() ####### # Data functions ####### def updateLayers(self): layers = uf.getLegendLayers(self.iface, 'all', 'all') self.selectLayerCombo.clear() if layers: layer_names = uf.getLayersListNames(layers) self.selectLayerCombo.addItems(layer_names) self.setSelectedLayer() self.plotChart() #else: # self.clearChart() # example_chart def setSelectedLayer(self): layer_name = self.selectLayerCombo.currentText() layer = uf.getLegendLayerByName(self.iface, layer_name) self.updateAttributes(layer) def getSelectedLayer(self): layer_name = self.selectLayerCombo.currentText() layer = uf.getLegendLayerByName(self.iface, layer_name) return layer def updateAttributes(self, layer): self.selectAttributeCombo.clear() if layer: fields = uf.getFieldNames(layer) # self.clearChart() self.selectAttributeCombo.addItems(fields) # send list to the report list window # self.clearReport() # self.updateReport(fields) def setSelectedAttribute(self): field_name = self.selectAttributeCombo.currentText() self.updateAttribute.emit(field_name) def getSelectedAttribute(self): field_name = self.selectAttributeCombo.currentText() return field_name def getAllFeatures(self, layer): layer.selectAll() allFeatures = layer.selectedFeatures() layer.removeSelection() return allFeatures def loadSymbols(self): if (self.eventlayer): filepath = os.path.join(os.path.dirname(__file__), 'svg', '') event_rules = ( ('fire_active_humanDmg', '"dmgType" LIKE fire AND "resolved" is\ "no" AND "civilDmg"> 0', filepath + 'fire_active_humanDmg.svg', None,10), ('building_active_humanDmg', '"dmgType" LIKE \'building\' AND "resolved" LIKE \'no\' AND "civilDmg"> 0 ', filepath + 'building_active_humanDmg.svg', None,10), ('tree_active_humanDmg', '"dmgType" LIKE \'tree\' AND "resolved" LIKE \'no\' AND "civilDmg"> 0 ', filepath + 'tree_active_humanDmg.svg', None,10), ('fire_active', '"dmgType" LIKE \'fire\' AND "resolved" LIKE \'no\' AND "civilDmg"= 0', filepath + 'fire_active.svg', None,8), ('building_active', '"dmgType" LIKE \'building\' AND "resolved" LIKE \'no\' AND "civilDmg"= 0 ', filepath + 'building_active.svg', None,8), ('tree_active', '"dmgType" LIKE \'tree\' AND "resolved" LIKE \'no\' AND "civilDmg"= 0', filepath + 'tree_active.svg', None,8), ('fire_resolved_humanDmg', '"dmgType" LIKE fire AND "resolved" LIKE yes AND "civilDmg"> 0', filepath + 'fire_resolved_humanDmg.svg', None,10), ('building_resolved_humanDmg', '"dmgType" LIKE \'building\' AND "resolved" LIKE \'yes\' AND "civilDmg"> 0 ', filepath + 'building_resolved_humanDmg.svg', None,10), ('tree_resolved_humanDmg', '"dmgType" LIKE \'tree\' AND "resolved" LIKE \'yes\' AND "civilDmg"> 0 ', filepath + 'tree_resolved_humanDmg.svg', None,10), ('fire_resolved', '"dmgType" LIKE \'fire\' AND "resolved" LIKE \'yes\' AND "civilDmg"= 0', filepath + 'fire_resolved.svg', None,8), ('building_resolved', '"dmgType" LIKE \'building\' AND "resolved" LIKE \'yes\' AND "civilDmg"= 0 ', filepath + 'building_resolved.svg', None,8), ('tree_resolved', '"dmgType" LIKE \'tree\' AND "resolved" LIKE \'yes\' AND "civilDmg"= 0', filepath + 'tree_resolved.svg', None,8) ) symbol = QgsSymbolV2.defaultSymbol(self.eventlayer.geometryType()) renderer = QgsRuleBasedRendererV2(symbol) root_rule = renderer.rootRule() for label, expression, path, scale, size in event_rules: # create a clone (i.e. a copy) of the default rule rule = root_rule.children()[0].clone() # set the label, expression and color rule.setLabel(label) rule.setFilterExpression(expression) symbol_layer = QgsSvgMarkerSymbolLayerV2() symbol_layer.setSize(size) symbol_layer.setPath(path) rule.symbol().appendSymbolLayer(symbol_layer) rule.symbol().deleteSymbolLayer(0) # set the scale limits if they have been specified if scale is not None: rule.setScaleMinDenom(scale[0]) rule.setScaleMaxDenom(scale[1]) # append the rule to the list of rules root_rule.appendChild(rule) # delete the default rule root_rule.removeChildAt(0) # apply the renderer to the layer self.eventlayer.setRendererV2(renderer) if (self.hospitalLayer): filepath = os.path.join(os.path.dirname(__file__), 'svg', '') hospital_rules = ('hospital', filepath + 'hospital.svg', None, 5) symbol = QgsSymbolV2.defaultSymbol(self.hospitalLayer.geometryType()) renderer = QgsRuleBasedRendererV2(symbol) root_rule = renderer.rootRule() label, path, scale, size = hospital_rules # create a clone (i.e. a copy) of the default rule rule = root_rule.children()[0].clone() # set the label, expression and color rule.setLabel(label) # rule.setFilterExpression(expression) symbol_layer = QgsSvgMarkerSymbolLayerV2() symbol_layer.setSize(size) symbol_layer.setPath(path) rule.symbol().appendSymbolLayer(symbol_layer) rule.symbol().deleteSymbolLayer(0) # set the scale limits if they have been specified if scale is not None: rule.setScaleMinDenom(scale[0]) rule.setScaleMaxDenom(scale[1]) # append the rule to the list of rules root_rule.appendChild(rule) # delete the default rule root_rule.removeChildAt(0) # apply the renderer to the layer self.hospitalLayer.setRendererV2(renderer) if (self.firestationLayer): filepath = os.path.join(os.path.dirname(__file__), 'svg', '') firestation_rules = ('firestation', filepath + 'firestation.svg', None, 5) symbol = QgsSymbolV2.defaultSymbol(self.firestationLayer.geometryType()) renderer = QgsRuleBasedRendererV2(symbol) root_rule = renderer.rootRule() label, path, scale, size = firestation_rules # create a clone (i.e. a copy) of the default rule rule = root_rule.children()[0].clone() # set the label, expression and color rule.setLabel(label) # rule.setFilterExpression(expression) symbol_layer = QgsSvgMarkerSymbolLayerV2() symbol_layer.setSize(size) symbol_layer.setPath(path) rule.symbol().appendSymbolLayer(symbol_layer) rule.symbol().deleteSymbolLayer(0) # set the scale limits if they have been specified if scale is not None: rule.setScaleMinDenom(scale[0]) rule.setScaleMaxDenom(scale[1]) # append the rule to the list of rules root_rule.appendChild(rule) # delete the default rule root_rule.removeChildAt(0) # apply the renderer to the layer self.firestationLayer.setRendererV2(renderer) ####### # Analysis functions ####### # route functions def getNetwork(self): roads_layer = uf.getLegendLayerByName(self.iface, 'Roads') if roads_layer: # see if there is an obstacles layer to subtract roads from the network obstacles_layer = uf.getLegendLayerByName(self.iface, "Obstacles") if obstacles_layer: # retrieve roads outside obstacles (inside = False) features = uf.getFeaturesByIntersection(roads_layer, obstacles_layer, False) # add these roads to a new temporary layer road_network = uf.createTempLayer('Temp_Network', 'LINESTRING', roads_layer.crs().postgisSrid(), [], []) road_network.dataProvider().addFeatures(features) else: road_network = roads_layer return road_network else: return def buildNetwork(self, eventFeature, facilityName): self.network_layer = self.getNetwork() if self.network_layer: # get the points to be used as origin and destination # in this case gets the centroid of the selected features facilitylayer = uf.getLegendLayerByName(self.iface, facilityName) self.selected_sources = self.getAllFeatures(facilitylayer) self.event_source = eventFeature source_points = [feature.geometry().centroid().asPoint() for feature in self.event_source] source_points.extend([feature.geometry().centroid().asPoint() for feature in self.selected_sources]) # build the graph including these points if len(source_points) > 1: self.graph, self.tied_points = uf.makeUndirectedGraph(self.network_layer, source_points) # the tied points are the new source_points on the graph if self.graph and self.tied_points: text = "network is built for %s points" % len(self.tied_points) #self.insertReport(text) return def shortestRoute(self, tied_points): options = len(tied_points) if options > 1: # origin and destination are given as an index in the tied_points list origin = 0 temp_lengh = 99999 shortest_route = QgsFeature() for destination in range(1, options): # calculate the shortest path for the given origin and destination path = uf.calculateRouteDijkstra(self.graph, self.tied_points, origin, destination) # Get length of the geometry QgsGeometry.fromPolyline(path).length() # store the route results in temporary layer called "Routes" routes_layer = uf.getLegendLayerByName(self.iface, "Routes") # create one if it doesn't exist if not routes_layer: attribs = ['length'] types = [QtCore.QVariant.Double] routes_layer = uf.createTempLayer('Routes', 'LINESTRING', self.network_layer.crs().postgisSrid(), attribs, types) uf.loadTempLayer(routes_layer) # insert route line provider = routes_layer.dataProvider() geometry_type = provider.geometryType() for i, geom in enumerate([path]): fet = QgsFeature() if geometry_type == 1: fet.setGeometry(QgsGeometry.fromPoint(geom)) elif geometry_type == 2: fet.setGeometry(QgsGeometry.fromPolyline(geom)) # in the case of polygons, instead of coordinates we insert the geometry elif geometry_type == 3: fet.setGeometry(geom) route_length = fet.geometry().length() if route_length < temp_lengh: temp_lengh = route_length shortest_route = fet facility_name = self.selected_sources[destination - 1].attribute('name') shortest_route.setAttributes([route_length]) provider.addFeatures([shortest_route]) provider.updateExtents() return facility_name def calculateRoute(self): event = self.eventlayer.selectedFeatures() self.hospital_name='' self.firestation_name='' if len(event)!=1: return else: civilDmg = event[0].attribute('civilDmg') if civilDmg ==0 : # origin and destination must be in the set of tied_points self.buildNetwork(event,'Firestation') self.firestation_name=self.shortestRoute(self.tied_points) else: self.buildNetwork(event,'Firestation') self.firestation_name=self.shortestRoute(self.tied_points) self.buildNetwork(event,'Hospital') self.hospital_name=self.shortestRoute(self.tied_points) routes_layer = uf.getLegendLayerByName(self.iface, "Routes") self.refreshCanvas(routes_layer) def deleteRoutes(self): routes_layer = uf.getLegendLayerByName(self.iface, "Routes") if routes_layer: ids = uf.getAllFeatureIds(routes_layer) routes_layer.startEditing() for id in ids: routes_layer.deleteFeature(id) routes_layer.commitChanges() def assignFacility(self): self.event_source=self.eventlayer.selectedFeatures() if len(self.event_source)!=1: return if isinstance(self.event_source[0]['unitOnSite'],QtCore.QPyNullVariant)==True: self.event_source[0]['unitOnSite']='' self.eventlayer.startEditing() firestationString='' hospitalString='' if self.event_source[0]['unitOnSite'].find('firestation:')!=-1 and self.event_source[0]['unitOnSite'].find('hospital:')!=-1: firestationString=self.event_source[0]['unitOnSite'].split(' hospital:')[0][12:] hospitalString=self.event_source[0]['unitOnSite'].split(' hospital:')[1] elif self.event_source[0]['unitOnSite'].find('firestation:')!=-1 and self.event_source[0]['unitOnSite'].find('hospital:')==-1: firestationString=self.event_source[0]['unitOnSite'].split('firestation:')[1] elif self.event_source[0]['unitOnSite'].find('firestation:')==-1 and self.event_source[0]['unitOnSite'].find('hospital:')!=-1: hospitalString=self.event_source[0]['unitOnSite'].split('hospital:')[1] firestationlist=[] hospitallist=[] for i in range(self.firestationLayer.selectedFeatureCount()): if firestationString.find(self.firestationLayer.selectedFeatures()[i].attribute('name'))==-1: firestationlist.append(self.firestationLayer.selectedFeatures()[i].attribute('name')) for i in range(self.hospitalLayer.selectedFeatureCount()): if hospitalString.find(self.hospitalLayer.selectedFeatures()[i].attribute('name'))==-1: hospitallist.append(self.hospitalLayer.selectedFeatures()[i].attribute('name')) delimiter=',' self.event_source[0]['unitOnSite']='' firestationresult=[] hospitalresult=[] if firestationString+delimiter.join(firestationlist)+self.firestation_name!='': firestationresult.extend([firestationString]) firestationresult.extend(firestationlist) if firestationString.find(self.firestation_name)==-1: firestationresult.extend([self.firestation_name]) if '' in firestationresult: firestationresult.remove('') self.event_source[0]['unitOnSite']+='firestation:'+delimiter.join(firestationresult) if hospitalString+delimiter.join(hospitallist)+self.hospital_name!='': hospitalresult.extend([hospitalString]) hospitalresult.extend(hospitallist) if hospitalString.find(self.hospital_name)==-1: hospitalresult.extend([self.hospital_name]) if '' in hospitalresult: hospitalresult.remove('') self.event_source[0]['unitOnSite']+=' hospital:'+delimiter.join(hospitalresult) self.eventlayer.updateFeature(self.event_source[0]) self.eventlayer.commitChanges() self.hospital_name='' self.firestation_name='' def clearAssignment(self): features = self.eventlayer.selectedFeatures() self.eventlayer.startEditing() for feature in features: feature.setAttribute('unitOnSite',QtCore.QPyNullVariant) self.eventlayer.updateFeature(feature) self.eventlayer.commitChanges() def changeEventStatus(self): self.event_source=self.eventlayer.selectedFeatures() if len(self.event_source)!=1: return else: self.eventlayer.startEditing() if self.event_source[0]['resolved']=='yes': self.event_source[0]['resolved']='no' else: self.event_source[0]['resolved']='yes' self.eventlayer.updateFeature(self.event_source[0]) self.eventlayer.commitChanges() self.loadSymbols() self.canvas.refresh() # after adding features to layers needs a refresh (sometimes) def refreshCanvas(self, layer): if self.canvas.isCachingEnabled(): layer.setCacheImage(None) else: self.canvas.refresh() # feature selection def selectFeaturesBuffer(self): layer = self.getSelectedLayer() buffer_layer = uf.getLegendLayerByName(self.iface, "Buffers") if buffer_layer and layer: uf.selectFeaturesByIntersection(layer, buffer_layer, True) def selectFeaturesRange(self): layer = self.getSelectedLayer() # for the range takes values from the service area (max) and buffer (min) text edits max = self.getServiceAreaCutoff() min = self.getBufferCutoff() if layer and max and min: # gets list of numeric fields in layer fields = uf.getNumericFields(layer) if fields: # selects features with values in the range uf.selectFeaturesByRangeValues(layer, fields[0].name(), min, max) ####### # Visualisation functions ####### def updateValueWidget(self): """Retrieves selected feature attribute values and sends them to valueWidget""" self.valueWidget.clear() layer = self.getSelectedLayer() field_name = self.getSelectedAttribute() vals = uf.getFieldValues(layer, field_name, selection=True) attribute = map(str, vals[0]) # if not attribute: # attribute = 'NULL' self.valueWidget.addItems(attribute) def plotChart(self): """ Adapted from Jorge Gil. Returns ------- Draws the maplotlib figures. The wind rose plot and the wind speed bar plot. """ plot_layer = uf.getLegendLayerByName(self.iface, 'Wind') # in my case it is fixed to the wind layer if plot_layer: starttime = uf.getAllFeatureValues(plot_layer, 'starttime') starttime = [dt.datetime.strptime(date, "%Y-%m-%d %H:%M:%S") for date in starttime] direction = uf.getAllFeatureValues(plot_layer, 'direction') speed = uf.getAllFeatureValues(plot_layer, 'speed') # ====================== # From: https://github.com/phobson/python-metar/blob/master/metar/graphics.py # prepare and create the wind direction plot # ''' # Plots a Wind Rose. Feed it a dataframe with 'speed'(kmh) and # 'direction' degrees clockwise from north (columns) # ''' self.chart_subplot_radar.cla() total = np.float(len(direction)) units = 'kmh' def _get_wind_counts(direction, speed, maxSpeed): speed_a = np.array(speed) dir_a = np.array(direction) group = dir_a[speed_a < maxSpeed] counts = dict((key, len(list(group))) for key, group in groupby(sorted(group))) return counts def _convert_dir_to_left_radian(direction): dir_a = np.array(direction) N = len(dir_a) barDir = dir_a * np.pi/180. - np.pi/N barWidth = [2 * np.pi / N]*N return barDir, barWidth def _pct_fmt(x, pos=0): return '%0.1f%%' % (100*x) def _roundup(x): return int(math.ceil(x / 10.0)) * 10 # set up the axis self.chart_subplot_radar.xaxis.grid(True, which='major', linestyle='-', alpha='0.125', zorder=0) self.chart_subplot_radar.yaxis.grid(True, which='major', linestyle='-', alpha='0.125', zorder=0) self.chart_subplot_radar.set_theta_zero_location("N") self.chart_subplot_radar.set_theta_direction('clockwise') # speed bins and colors speedBins = list(sorted(set([_roundup(n) for n in speed])).__reversed__()) norm = colors.Normalize(vmin=min(speedBins), vmax=max(speedBins)) # normalize the colors to the range of windspeed for spd in speedBins: degree_counts = _get_wind_counts(direction, speed, spd) counts = np.array(degree_counts.values())/total degrees = np.array(degree_counts.keys()) barDir, barWidth = _convert_dir_to_left_radian(degrees) self.chart_subplot_radar.bar(barDir, counts, width=barWidth, linewidth=0.50, edgecolor=(0.25, 0.25, 0.25), color=cm.jet(norm(spd)), alpha=0.8, label=r"<%d %s" % (spd, units)) # format the plot's axes self.chart_subplot_radar.legend(loc='lower right', bbox_to_anchor=(1.25, -0.13), fontsize=8) self.chart_subplot_radar.set_xticklabels(['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']) self.chart_subplot_radar.xaxis.grid(True, which='major', color='k', alpha=0.5) self.chart_subplot_radar.yaxis.grid(True, which='major', color='k', alpha=0.5) self.chart_subplot_radar.yaxis.set_major_formatter(FuncFormatter(_pct_fmt)) # self.chart_subplot_radar.text(0.05, 0.95, 'Calm Winds: %0.1f%%' % calm) # if calm >= 0.1: # self.chart_subplot_radar.set_ylim(ymin=np.floor(calm*10)/10.) # ====================== # draw windspeed bar plot # x = time, y = wind speed self.chart_subplot_bar.cla() # loop through the speed bins norm = colors.Normalize(min(speed), max(speed)) for spd, time in zip(speed, starttime): self.chart_subplot_bar.bar(time, spd, width=0.03, align = 'center', edgecolor=(0.25, 0.25, 0.25), color=cm.jet(norm(spd)), alpha=0.8) self.chart_subplot_bar.set_ylim(bottom=0, top=150) # dangerous windspeed self.chart_subplot_bar.hlines(120, xmin=min(starttime), xmax=max(starttime), colors='r') self.chart_subplot_bar.annotate('safety hazard', xy=(.85, .82), xycoords='axes fraction', horizontalalignment='center', verticalalignment='center', color = 'r') self.chart_subplot_bar.annotate('[kmh]', xy=(-0, 1), xycoords='axes fraction', horizontalalignment='right', verticalalignment='bottom') # set x-axis labels labels = [time.strftime('%H:%M') for time in starttime] self.chart_subplot_bar.set_xticks(starttime) self.chart_subplot_bar.set_xticklabels(labels, rotation = 'vertical') # # Mark the current time with a vertical line — not implemented due to differring time between # # datetime.datetime.now().time() and the date range used in the simulation data. It would work with # # real-time dataset. # current_time = dt.datetime.now().time() # self.chart_subplot_bar.vlines(current_time, ymin=0, ymax=140, linestyles = 'dotted') # draw all the plots self.chart_canvas.draw() def clearChart(self): self.chart_subplot_radar.cla() self.chart_subplot_bar.cla() self.chart_canvas.draw() def getWindDate(self): """ Returns ------- String. The date part of the first timestamp in the wind data. """ layer = uf.getLegendLayerByName(self.iface, 'Wind') starttime = uf.getAllFeatureValues(layer, 'starttime') starttime = [dt.datetime.strptime(date, "%Y-%m-%d %H:%M:%S") for date in starttime] date = starttime[0].strftime('%Y-%m-%d') return date
class FigureTab: cursors = [15000, 45000] colors = ['orange', 'violet'] def __init__(self, layout, vna): # create figure self.figure = Figure() if sys.platform != 'win32': self.figure.set_facecolor('none') self.canvas = FigureCanvas(self.figure) layout.addWidget(self.canvas) # create navigation toolbar self.toolbar = NavigationToolbar(self.canvas, None, False) self.toolbar.layout().setSpacing(6) # remove subplots action actions = self.toolbar.actions() if int(matplotlib.__version__[0]) < 2: self.toolbar.removeAction(actions[7]) else: self.toolbar.removeAction(actions[6]) self.toolbar.addSeparator() self.cursorLabels = {} self.cursorValues = {} self.cursorMarkers = {} self.cursorPressed = {} for i in range(len(self.cursors)): self.cursorMarkers[i] = None self.cursorPressed[i] = False self.cursorLabels[i] = QLabel('Cursor %d, kHz' % (i + 1)) self.cursorLabels[i].setStyleSheet('color: %s' % self.colors[i]) self.cursorValues[i] = QSpinBox() self.cursorValues[i].setMinimumSize(90, 0) self.cursorValues[i].setSingleStep(10) self.cursorValues[i].setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.toolbar.addWidget(self.cursorLabels[i]) self.toolbar.addWidget(self.cursorValues[i]) self.cursorValues[i].valueChanged.connect(partial(self.set_cursor, i)) self.canvas.mpl_connect('button_press_event', partial(self.press_marker, i)) self.canvas.mpl_connect('motion_notify_event', partial(self.move_marker, i)) self.canvas.mpl_connect('button_release_event', partial(self.release_marker, i)) self.toolbar.addSeparator() self.plotButton = QPushButton('Rescale') self.toolbar.addWidget(self.plotButton) layout.addWidget(self.toolbar) self.plotButton.clicked.connect(self.plot) self.mode = None self.vna = vna def add_cursors(self, axes): if self.mode == 'gain_short' or self.mode == 'gain_open': columns = ['Freq., kHz', 'G, dB', r'$\angle$ G, deg'] else: columns = ['Freq., kHz', 'Re(Z), \u03A9', 'Im(Z), \u03A9', '|Z|, \u03A9', r'$\angle$ Z, deg', 'SWR', r'|$\Gamma$|', r'$\angle$ $\Gamma$, deg', 'RL, dB'] y = len(self.cursors) * 0.04 + 0.01 for i in range(len(columns)): self.figure.text(0.19 + 0.1 * i, y, columns[i], horizontalalignment = 'right') self.cursorRows = {} for i in range(len(self.cursors)): y = len(self.cursors) * 0.04 - 0.03 - 0.04 * i self.figure.text(0.01, y, 'Cursor %d' % (i + 1), color = self.colors[i]) self.cursorRows[i] = {} for j in range(len(columns)): self.cursorRows[i][j] = self.figure.text(0.19 + 0.1 * j, y, '', horizontalalignment = 'right') if self.mode == 'smith': self.cursorMarkers[i], = axes.plot(0.0, 0.0, marker = 'o', color = self.colors[i]) else: self.cursorMarkers[i] = axes.axvline(0.0, color = self.colors[i], linewidth = 2) self.set_cursor(i, self.cursorValues[i].value()) def set_cursor(self, index, value): FigureTab.cursors[index] = value marker = self.cursorMarkers[index] if marker is None: return row = self.cursorRows[index] freq = value gamma = self.vna.gamma(freq) if self.mode == 'smith': marker.set_xdata(gamma.real) marker.set_ydata(gamma.imag) else: marker.set_xdata(freq) row[0].set_text('%d' % freq) if self.mode == 'gain_short': gain = self.vna.gain_short(freq) magnitude = 20.0 * np.log10(np.absolute(gain)) angle = np.angle(gain, deg = True) row[1].set_text(unicode_minus('%.1f' % magnitude)) row[2].set_text(unicode_minus('%.1f' % angle)) elif self.mode == 'gain_open': gain = self.vna.gain_open(freq) magnitude = 20.0 * np.log10(np.absolute(gain)) angle = np.angle(gain, deg = True) row[1].set_text(unicode_minus('%.1f' % magnitude)) row[2].set_text(unicode_minus('%.1f' % angle)) else: swr = self.vna.swr(freq) z = self.vna.impedance(freq) rl = 20.0 * np.log10(np.absolute(gamma)) if rl > -0.01: rl = 0.0 row[1].set_text(metric_prefix(z.real)) row[2].set_text(metric_prefix(z.imag)) row[3].set_text(metric_prefix(np.absolute(z))) angle = np.angle(z, deg = True) if np.abs(angle) < 0.1: angle = 0.0 row[4].set_text(unicode_minus('%.1f' % angle)) row[5].set_text(unicode_minus('%.2f' % swr)) row[6].set_text(unicode_minus('%.2f' % np.absolute(gamma))) angle = np.angle(gamma, deg = True) if np.abs(angle) < 0.1: angle = 0.0 row[7].set_text(unicode_minus('%.1f' % angle)) row[8].set_text(unicode_minus('%.2f' % rl)) self.canvas.draw() def press_marker(self, index, event): if not event.inaxes: return if self.mode == 'smith': return marker = self.cursorMarkers[index] if marker is None: return contains, misc = marker.contains(event) if not contains: return self.cursorPressed[index] = True def move_marker(self, index, event): if not event.inaxes: return if self.mode == 'smith': return if not self.cursorPressed[index]: return self.cursorValues[index].setValue(event.xdata) def release_marker(self, index, event): self.cursorPressed[index] = False def xlim(self, freq): start = freq[0] stop = freq[-1] min = np.minimum(start, stop) max = np.maximum(start, stop) margin = (max - min) / 50 return (min - margin, max + margin) def plot(self): getattr(self, 'plot_%s' % self.mode)() def update(self, mode): start = self.vna.dut.freq[0] stop = self.vna.dut.freq[-1] min = np.minimum(start, stop) max = np.maximum(start, stop) for i in range(len(self.cursors)): value = self.cursors[i] self.cursorValues[i].setRange(min, max) self.cursorValues[i].setValue(value) self.set_cursor(i, value) getattr(self, 'update_%s' % mode)() def plot_curves(self, freq, data1, label1, limit1, data2, label2, limit2): matplotlib.rcdefaults() matplotlib.rcParams['axes.formatter.use_mathtext'] = True self.figure.clf() bottom = len(self.cursors) * 0.04 + 0.13 self.figure.subplots_adjust(left = 0.16, bottom = bottom, right = 0.84, top = 0.96) axes1 = self.figure.add_subplot(111) axes1.cla() axes1.xaxis.grid() axes1.set_xlabel('kHz') axes1.set_ylabel(label1) xlim = self.xlim(freq) axes1.set_xlim(xlim) if limit1 is not None: axes1.set_ylim(limit1) self.curve1, = axes1.plot(freq, data1, color = 'blue', label = label1) self.add_cursors(axes1) if data2 is None: self.canvas.draw() return axes1.tick_params('y', color = 'blue', labelcolor = 'blue') axes1.yaxis.label.set_color('blue') axes2 = axes1.twinx() axes2.spines['left'].set_color('blue') axes2.spines['right'].set_color('red') axes2.set_ylabel(label2) axes2.set_xlim(xlim) if limit2 is not None: axes2.set_ylim(limit2) axes2.tick_params('y', color = 'red', labelcolor = 'red') axes2.yaxis.label.set_color('red') self.curve2, = axes2.plot(freq, data2, color = 'red', label = label2) self.canvas.draw() def plot_gain(self, gain): freq = self.vna.dut.freq data1 = 20.0 * np.log10(np.absolute(gain)) data2 = np.angle(gain, deg = True) self.plot_curves(freq, data1, 'G, dB', (-110, 110.0), data2, r'$\angle$ G, deg', (-198, 198)) def plot_gain_short(self): self.mode = 'gain_short' self.plot_gain(self.vna.gain_short(self.vna.dut.freq)) def plot_gain_open(self): self.mode = 'gain_open' self.plot_gain(self.vna.gain_open(self.vna.dut.freq)) def update_gain(self, gain, mode): if self.mode == mode: self.curve1.set_xdata(self.vna.dut.freq) self.curve1.set_ydata(20.0 * np.log10(np.absolute(gain))) self.curve2.set_xdata(self.vna.dut.freq) self.curve2.set_ydata(np.angle(gain, deg = True)) self.canvas.draw() else: self.mode = mode self.plot_gain(gain) def update_gain_short(self): self.update_gain(self.vna.gain_short(self.vna.dut.freq), 'gain_short') def update_gain_open(self): self.update_gain(self.vna.gain_open(self.vna.dut.freq), 'gain_open') def plot_magphase(self, freq, data, label, mode): self.mode = mode data1 = np.absolute(data) data2 = np.angle(data, deg = True) max = np.fmax(0.01, data1.max()) label1 = r'|%s|' % label label2 = r'$\angle$ %s, deg' % label self.plot_curves(freq, data1, label1, (-0.05 * max, 1.05 * max), data2, label2, (-198, 198)) def update_magphase(self, freq, data, label, mode): if self.mode == mode: self.curve1.set_xdata(freq) self.curve1.set_ydata(np.absolute(data)) self.curve2.set_xdata(freq) self.curve2.set_ydata(np.angle(data, deg = True)) self.canvas.draw() else: self.plot_magphase(freq, data, label, mode) def plot_open(self): self.plot_magphase(self.vna.open.freq, self.vna.open.data, 'open', 'open') def update_open(self): self.update_magphase(self.vna.open.freq, self.vna.open.data, 'open', 'open') def plot_short(self): self.plot_magphase(self.vna.short.freq, self.vna.short.data, 'short', 'short') def update_short(self): self.update_magphase(self.vna.short.freq, self.vna.short.data, 'short', 'short') def plot_load(self): self.plot_magphase(self.vna.load.freq, self.vna.load.data, 'load', 'load') def update_load(self): self.update_magphase(self.vna.load.freq, self.vna.load.data, 'load', 'load') def plot_dut(self): self.plot_magphase(self.vna.dut.freq, self.vna.dut.data, 'dut', 'dut') def update_dut(self): self.update_magphase(self.vna.dut.freq, self.vna.dut.data, 'dut', 'dut') def plot_smith_grid(self, axes, color): load = 50.0 ticks = np.array([0.0, 0.2, 0.5, 1.0, 2.0, 5.0]) for tick in ticks * load: axis = np.logspace(-4, np.log10(1.0e3), 200) * load z = tick + 1.0j * axis gamma = (z - load)/(z + load) axes.plot(gamma.real, gamma.imag, color = color, linewidth = 0.4, alpha = 0.3) axes.plot(gamma.real, -gamma.imag, color = color, linewidth = 0.4, alpha = 0.3) z = axis + 1.0j * tick gamma = (z - load)/(z + load) axes.plot(gamma.real, gamma.imag, color = color, linewidth = 0.4, alpha = 0.3) axes.plot(gamma.real, -gamma.imag, color = color, linewidth = 0.4, alpha = 0.3) if tick == 0.0: axes.text(1.0, 0.0, u'\u221E', color = color, ha = 'left', va = 'center', clip_on = True, fontsize = 'x-large') axes.text(-1.0, 0.0, u'0\u03A9', color = color, ha = 'left', va = 'bottom', clip_on = True) continue lab = u'%d\u03A9' % tick x = (tick - load) / (tick + load) axes.text(x, 0.0, lab, color = color, ha = 'left', va = 'bottom', clip_on = True) lab = u'j%d\u03A9' % tick z = 1.0j * tick gamma = (z - load)/(z + load) * 1.05 x = gamma.real y = gamma.imag angle = np.angle(gamma) * 180.0 / np.pi - 90.0 axes.text(x, y, lab, color = color, ha = 'center', va = 'center', clip_on = True, rotation = angle) lab = u'\u2212j%d\u03A9' % tick axes.text(x, -y, lab, color = color, ha = 'center', va = 'center', clip_on = True, rotation = -angle) def plot_smith(self): self.mode = 'smith' matplotlib.rcdefaults() self.figure.clf() bottom = len(self.cursors) * 0.04 + 0.05 self.figure.subplots_adjust(left = 0.0, bottom = bottom, right = 1.0, top = 1.0) axes1 = self.figure.add_subplot(111) self.plot_smith_grid(axes1, 'blue') gamma = self.vna.gamma(self.vna.dut.freq) self.curve1, = axes1.plot(gamma.real, gamma.imag, color = 'red') axes1.axis('equal') axes1.set_xlim(-1.12, 1.12) axes1.set_ylim(-1.12, 1.12) axes1.xaxis.set_visible(False) axes1.yaxis.set_visible(False) for loc, spine in axes1.spines.items(): spine.set_visible(False) self.add_cursors(axes1) self.canvas.draw() def update_smith(self): if self.mode == 'smith': gamma = self.vna.gamma(self.vna.dut.freq) self.curve1.set_xdata(gamma.real) self.curve1.set_ydata(gamma.imag) self.canvas.draw() else: self.plot_smith() def plot_imp(self): self.mode = 'imp' freq = self.vna.dut.freq z = self.vna.impedance(freq) data1 = np.fmin(9.99e4, np.absolute(z)) data2 = np.angle(z, deg = True) max = np.fmax(0.01, data1.max()) self.plot_curves(freq, data1, '|Z|, \u03A9', (-0.05 * max, 1.05 * max), data2, r'$\angle$ Z, deg', (-198, 198)) def update_imp(self): if self.mode == 'imp': freq = self.vna.dut.freq z = self.vna.impedance(freq) data1 = np.fmin(9.99e4, np.absolute(z)) data2 = np.angle(z, deg = True) self.curve1.set_xdata(freq) self.curve1.set_ydata(data1) self.curve2.set_xdata(freq) self.curve2.set_ydata(data2) self.canvas.draw() else: self.plot_imp() def plot_swr(self): self.mode = 'swr' freq = self.vna.dut.freq data1 = self.vna.swr(freq) self.plot_curves(freq, data1, 'SWR', (0.9, 3.1), None, None, None) def update_swr(self): if self.mode == 'swr': self.curve1.set_xdata(self.vna.dut.freq) self.curve1.set_ydata(self.vna.swr(self.vna.dut.freq)) self.canvas.draw() else: self.plot_swr() def plot_gamma(self): self.plot_magphase(self.vna.dut.freq, self.vna.gamma(self.vna.dut.freq), r'$\Gamma$', 'gamma') def update_gamma(self): self.update_magphase(self.vna.dut.freq, self.vna.gamma(self.vna.dut.freq), r'$\Gamma$', 'gamma') def plot_rl(self): self.mode = 'rl' freq = self.vna.dut.freq gamma = self.vna.gamma(freq) data1 = 20.0 * np.log10(np.absolute(gamma)) self.plot_curves(freq, data1, 'RL, dB', (-105, 5.0), None, None, None) def update_rl(self): if self.mode == 'rl': freq = self.vna.dut.freq gamma = self.vna.gamma(freq) data1 = 20.0 * np.log10(np.absolute(gamma)) self.curve1.set_xdata(freq) self.curve1.set_ydata(data1) self.canvas.draw() else: self.plot_rl()
class Plot_RFs(Tk.Tk): def __init__(self, root, folder): Tk.Tk.__init__(self) self.root = root self.folder = folder self.title('RFs - ' + folder) self.protocol('WM_DELETE_WINDOW', self.closeGUI) self.createRFsGUI() def createRFsGUI(self): #declare button variables self.plotContent = Tk.StringVar() self.plotContent.set('color-coded') self.RFtime = Tk.StringVar() self.RFtime.set('0') #create plotframe widget mainFrame = Tk.Frame(self) mainFrame.grid(column=0, row=0) # mainFrame.columnconfigure(0, weight=1) #window resizing # mainFrame.rowconfigure(0, weight=1) #window resizing self.plotFrame = Tk.Frame(mainFrame, borderwidth=5, relief='sunken', width=500, height=500) self.plotFrame.grid(column=0, row=0, columnspan=3, rowspan=2, sticky=(N, W, E), padx=(10,10), pady=(10,10)) buttonFrame = Tk.Frame(mainFrame, borderwidth=5, relief='sunken', width=500, height=100) buttonFrame.grid(column=0, row=3, columnspan=3, rowspan=1, sticky=(W, E, S), padx=(10,10), pady=(10,10)) #create main figure self.mainFig = Figure() #create main plot canvas self.canvas = FigureCanvasTkAgg(self.mainFig, master=self.plotFrame) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #create radio buttons self.color_coded = Tk.Radiobutton(buttonFrame, text='color-coded', command=self.codedMap, variable=self.plotContent, value='color-coded', width=12) self.color_coded.grid(column=0, row=0, sticky=(W, E), padx=(0,20)) self.color_coded.select() self.detailed = Tk.Radiobutton(buttonFrame, text='detailed', command=self.detailedMap, variable=self.plotContent, value='detailed', width=12) self.detailed.grid(column=1, row=0, sticky=(W, E), padx=(0,20)) self.detailed.deselect() self.individual = Tk.Radiobutton(buttonFrame, text='individual', command=self.individualRF, variable=self.plotContent, value='individual', width=12) self.individual.grid(column=2, row=0, sticky=(W, E), padx=(0,20)) self.individual.deselect() #create time entry field self.timeInput = Tk.Entry(buttonFrame, textvariable=self.RFtime, width=12) self.timeInput.grid(column=0, row=1, sticky=(W)) self.timeInput.insert(0,'0') self.timeInput.bind('<Return>', self.roundTime) #create scale widget for time selection self.timeScale = Tk.Scale(buttonFrame, orient=HORIZONTAL, from_=0, to=self.root.genParam[self.folder]['trialDuration'], resolution=self.root.genParam[self.folder]['RF_sampleTime'], command=self.timeScale_C, length=500, showvalue=0) self.timeScale.grid(column=1, row=1, columnspan=5, sticky=(E,W)) self.allCommand = {'color-coded':self.color_coded, 'detailed':self.detailed, 'individual':self.individual} self.codedMap() self.timeInput.focus_set() def timeScale_C(self, event): self.timeInput.delete(0, END) self.timeInput.insert(0,str(self.timeScale.get())) self.RFtime.set(str(self.timeScale.get())) self.allCommand[self.plotContent.get()].invoke() def roundTime(self, event): ''' executed on <Return>; rounds the requested time and executes command associated with radio button''' #find the closest saved weight snapshot to requested time self.RFtime.set(self.timeInput.get()) m = np.mod(float(self.RFtime.get()),self.root.genParam[self.folder]['RF_sampleTime']) round_t = np.floor(float(self.RFtime.get())/self.root.genParam[self.folder]['RF_sampleTime'])*self.root.genParam[self.folder]['RF_sampleTime'] + np.round(m*2,-2)/2 if round_t/self.root.genParam[self.folder]['RF_sampleTime']>=np.size(self.root.weights[self.folder]['w'],2): #checks for out of bound requested time round_t = (np.size(self.root.weights[self.folder]['w'],2)-1)*self.root.genParam[self.folder]['RF_sampleTime'] self.mainFig.text(0.5,0.5,'time out-of-bound',bbox=dict(facecolor='red', alpha=0.8), horizontalalignment='center', verticalalignment='center') self.canvas.show() self.RFtime.set(str(int(round_t))) self.timeScale.set(int(round_t)) self.timeInput.delete(0, END) self.timeInput.insert(0, str(int(round_t))) #execute the command associated with the current check radiobutton if event: self.allCommand[self.plotContent.get()].invoke() def codedMap(self): #plot color-coded receptive fields self.plotContent.set('color-coded') self.mainFig.clf() #clear existing figure self.plt = self.mainFig.add_subplot(111) #creates subplot #retrieve time self.roundTime(False) t = int(self.RFtime.get()) i = int(t/self.root.genParam[self.folder]['RF_sampleTime']) squareW = self.root.weights[self.folder]['w'][:,:,i] rootSize = np.sqrt(self.root.neurons[self.folder]['RS'].size) ODC_mat = np.zeros(self.root.neurons[self.folder]['RS'].size) alpha_mat = np.zeros(self.root.neurons[self.folder]['RS'].size) #create white color map with transparency gradient cmap_trans = mpl.colors.LinearSegmentedColormap.from_list('my_cmap',['black','black'],256) cmap_trans._init() alphas = np.linspace(1.0, 0, cmap_trans.N+3) cmap_trans._lut[:,-1] = alphas for RS in range(self.root.neurons[self.folder]['RS'].size): prefPattern = [np.sum(squareW[[0,4,8,12],RS]),np.sum(squareW[[1,5,9,13],RS]),np.sum(squareW[[2,6,10,14],RS]),np.sum(squareW[[3,7,11,15],RS])] ODC_mat[RS] = np.argmax(prefPattern) alpha_mat[RS] = np.max(prefPattern)-(np.sum(prefPattern)-np.max(prefPattern))/self.root.genParam[self.folder]['numPattern'] # ODC_mat[RS] = np.mean(self.TC_RS.g[[0,5,10,15],RS]) - np.mean(self.TC_RS.g[[3,6,9,12],RS]) self.plt.imshow(np.reshape(ODC_mat, [rootSize, rootSize]),interpolation='nearest', cmap='Spectral', vmin=0,vmax=3) #color self.plt.imshow(np.reshape(alpha_mat, [rootSize, rootSize]),interpolation='nearest', cmap=cmap_trans, vmin=-0.25,vmax=1.5) #transparency self.plt.set_xticks([]) self.plt.set_yticks([]) self.canvas.show() def detailedMap(self): #plot detailed receptive fields self.plotContent.set('detailed') self.mainFig.clf() #clear existing figure #retrieve time self.roundTime(False) t = int(self.RFtime.get()) i = t/self.root.genParam[self.folder]['RF_sampleTime'] rootSize = np.sqrt(self.root.neurons[self.folder]['TC'].size) squareW = self.root.weights[self.folder]['w'][:,:,i] for RS in range(self.root.neurons[self.folder]['RS'].size): subplt = self.mainFig.add_subplot(int(np.ceil(np.sqrt(self.root.neurons[self.folder]['RS'].size))),int(np.ceil(np.sqrt(self.root.neurons[self.folder]['RS'].size))), RS+1) subplt.imshow(np.reshape(squareW[:,RS],[rootSize, rootSize]), interpolation='nearest', vmin=0, vmax=self.root.synParam[self.folder]['TC_RS'].g_max, cmap='bwr') subplt.set_xticks([]) subplt.set_yticks([]) # self.plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9) # cax = self.plt.axes([0.85, 0.1, 0.075, 0.8]) # self.plt.colorbar(cax=cax) self.canvas.show() def individualRF(self): print '!!NOT IMPLEMENTED YET!!' def closeGUI(self, allGUI=False): if not allGUI: self.root.allGUI.remove(self) self.destroy()
class UILimit(wx.Frame): def __init__(self,parent): wx.Frame.__init__(self,parent,title=PICHI_STR,size=(400,300)) self.funpanel = wx.Panel(self, -1) self.initSizers() self.initCanvas() self.initCtrls() self.Centre(1) self.Show() def initSizers(self): self.mainsz = wx.BoxSizer(wx.VERTICAL) self.funsz = wx.BoxSizer(wx.HORIZONTAL) self.funpanel.SetSizer(self.funsz) self.SetSizer(self.mainsz) def initCtrls(self): self.funlabel = wx.StaticText(self.funpanel, -1, " f(x) ") self.fun = wx.TextCtrl(self.funpanel, -1, "", style= wx.TE_PROCESS_ENTER) self.boton = wx.Button(self, -1, "Calcular limite") # Fonts font1 = self.funlabel.GetFont() font1.SetPointSize(12) self.funlabel.SetFont(font1) self.fun.SetFont(font1) self.fun.SetForegroundColour((0,0,255)) self.funsz.Add(self.funlabel, 1, wx.EXPAND|wx.ALL, 5) self.funsz.Add(self.fun, 7, wx.EXPAND|wx.ALL, 5) self.mainsz.Add(self.funpanel, 1, wx.EXPAND|wx.ALL, 5) self.mainsz.Add(self.boton, 1, wx.EXPAND|wx.ALL, 5) self.mainsz.Add(self.canvas, 6, wx.EXPAND|wx.ALL, 5) self.Bind(wx.EVT_BUTTON, self.limite, self.boton) self.Bind(wx.EVT_TEXT_ENTER, self.limite) def initCanvas(self): self.figure = Figure() # FigureCanvas self.canvas = FigureCanvas(self, -1, self.figure) self.figure.set_facecolor((1,1,1)) self.string = self.figure.text(0.05, 0.5, "") self.string.set_fontsize(18) def limite(self,event): x = sympy.Symbol("x") so = self.fun.GetValue() # Función original if not(so): print "Función no definida" return False so = preproc(so) so = so.split(",") fx = so[0] val = float(so[1]) Fx = sympy.limit(eval(fx),x,val) # Función integrada str_Fx = r"$ \lim_{x \to %s} \, (%s) \,dx \,= \,%s$"%(val, sympy.latex(eval(fx)), sympy.latex(Fx)) self.string.set_text(str_Fx) self.canvas.draw()
def plot_service(results, target_stop_name, target_date, outfile): HOURS = 24 fig_format = outfile[-3:] fig = Figure(figsize=(12, 6), dpi=300) if fig_format == 'pdf': canvas = FigureCanvasPdf(fig) elif fig_format == 'svg': canvas = FigureCanvasSVG(fig) ax = fig.add_subplot(111, xlim=(0, 24)) fig.subplots_adjust(bottom=0.2, left=0.05, right=0.98) pos = np.arange(HOURS) width = 0.40 color_dups = Counter() hatch = ["/", ".", "x", "*", "+"] values_0 = np.array(np.zeros(HOURS)) values_1 = np.array(np.zeros(HOURS)) for route_id, route_data in results.items(): bar_args = {} if route_data['route_color'] and route_data['route_color'] != '': bar_args['color'] = '#' + route_data['route_color'] else: bar_args['color'] = '#000000' bar_args['edgecolor'] = '#444444' color_dups[bar_args['color']] += 1 if color_dups[bar_args['color']] > 1: (hatch_dup, hatch_id) = divmod(color_dups[bar_args['color']] - 2, len(hatch)) bar_args['hatch'] = hatch[hatch_id] * (hatch_dup + 1) route_data['plot_0'] = ax.bar(pos, route_data['bins_0'], width, bottom=values_0, **bar_args) route_data['plot_1'] = ax.bar(pos + width, route_data['bins_1'], width, bottom=values_1, **bar_args) make_labels(route_data['plot_0'], ax, '#' + contrasting_color(bar_args['color'][1:])) make_labels(route_data['plot_1'], ax, '#' + contrasting_color(bar_args['color'][1:])) values_0 += np.array(route_data['bins_0']) values_1 += np.array(route_data['bins_1']) if len(results) > 1: last_route_data = results.values()[-1] make_top_labels(last_route_data['plot_0'], ax, values_0) make_top_labels(last_route_data['plot_1'], ax, values_1) maxtph = (math.ceil(max(max(values_0), max(values_1)) / 10.0) * 10) + 5 ax.set_ylim(0, maxtph) ax.set_xlabel('Hour') ax.set_ylabel(mode_string( [route['route_type'] for route in results.values()])) ax.set_title('Service at %s on %s' % (target_stop_name, target_date.strftime("%Y-%m-%d"))) ax.set_yticks(np.arange(0, maxtph, 4)) ax.set_xticks(pos + width) ax.set_xticklabels([str(i) for i in range(0, HOURS)]) ax.legend([route_data['plot_0'][0] for route_data in results.values()], [route_data['route_name'] for route_data in results.values()], prop={'size': 'small'}, ncol=2) headsigns_0 = set() headsigns_1 = set() for route in results.values(): headsigns_0.update(route['headsigns_0'].keys()) headsigns_1.update(route['headsigns_1'].keys()) d0 = textwrap.fill("Direction 0 is: %s" % (", ".join(headsigns_0)), 150, subsequent_indent=' ') d1 = textwrap.fill("Direction 1 is: %s" % (", ".join(headsigns_1)), 150, subsequent_indent=' ') fig.text(0.05, 0.05, d0 + "\n" + d1, size="small") fig.savefig(outfile, format=fig_format)
class asaplotbase: """ ASAP plotting base class based on matplotlib. """ def __init__(self, rows=1, cols=0, title='', size=None, buffering=False): """ Create a new instance of the ASAPlot plotting class. If rows < 1 then a separate call to set_panels() is required to define the panel layout; refer to the doctext for set_panels(). """ self.is_dead = False self.figure = Figure(figsize=size, facecolor='#ddddee') self.canvas = None self.set_title(title) self.subplots = [] if rows > 0: self.set_panels(rows, cols) # Set matplotlib default colour sequence. self.colormap = "green red black cyan magenta orange blue purple yellow pink".split() c = asaprcParams['plotter.colours'] if isinstance(c,str) and len(c) > 0: self.colormap = c.split() # line styles need to be set as a list of numbers to use set_dashes self.lsalias = {"line": [1,0], "dashdot": [4,2,1,2], "dashed" : [4,2,4,2], "dotted" : [1,2], "dashdotdot": [4,2,1,2,1,2], "dashdashdot": [4,2,4,2,1,2] } styles = "line dashed dotted dashdot".split() c = asaprcParams['plotter.linestyles'] if isinstance(c,str) and len(c) > 0: styles = c.split() s = [] for ls in styles: if self.lsalias.has_key(ls): s.append(self.lsalias.get(ls)) else: s.append('-') self.linestyles = s self.color = 0; self.linestyle = 0; self.attributes = {} self.loc = 0 self.buffering = buffering self.events = {'button_press':None, 'button_release':None, 'motion_notify':None} def _alive(self): # Return True if the GUI alives. if (not self.is_dead) and \ self.figmgr and hasattr(self.figmgr, "num"): figid = self.figmgr.num # Make sure figid=0 is what asapplotter expects. # It might be already destroied/overridden by matplotlib # commands or other methods using asaplot. return _pylab_helpers.Gcf.has_fignum(figid) and \ (self.figmgr == _pylab_helpers.Gcf.get_fig_manager(figid)) return False def _subplotsOk(self, rows, cols, npanel=0): """ Check if the axes in subplots are actually the ones plotted on the figure. Returns a bool. This method is to detect manual layout changes using mpl methods. """ # compare with user defined layout if (rows is not None) and (rows != self.rows): return False if (cols is not None) and (cols != self.cols): return False # check number of subplots figaxes = self.figure.get_axes() np = self.rows*self.cols if npanel > np: return False if len(figaxes) != np: return False if len(self.subplots) != len(figaxes): return False # compare axes instance in this class and on the plotter ok = True for ip in range(np): if self.subplots[ip]['axes'] != figaxes[ip]: ok = False break return ok ### Delete artists ### def clear(self): """ Delete all lines from the current subplot. Line numbering will restart from 0. """ #for i in range(len(self.lines)): # self.delete(i) self.axes.clear() self.color = 0 self.linestyle = 0 self.lines = [] self.subplots[self.i]['lines'] = self.lines def delete(self, numbers=None): """ Delete the 0-relative line number, default is to delete the last. The remaining lines are NOT renumbered. """ if numbers is None: numbers = [len(self.lines)-1] if not hasattr(numbers, '__iter__'): numbers = [numbers] for number in numbers: if 0 <= number < len(self.lines): if self.lines[number] is not None: for line in self.lines[number]: line.set_linestyle('None') self.lines[number] = None self.show() ### Set plot parameters ### def hold(self, hold=True): """ Buffer graphics until subsequently released. """ self.buffering = hold def palette(self, color, colormap=None, linestyle=0, linestyles=None): if colormap: if isinstance(colormap,list): self.colormap = colormap elif isinstance(colormap,str): self.colormap = colormap.split() if 0 <= color < len(self.colormap): self.color = color if linestyles: self.linestyles = [] if isinstance(linestyles,list): styles = linestyles elif isinstance(linestyles,str): styles = linestyles.split() for ls in styles: if self.lsalias.has_key(ls): self.linestyles.append(self.lsalias.get(ls)) else: self.linestyles.append(self.lsalias.get('line')) if 0 <= linestyle < len(self.linestyles): self.linestyle = linestyle def legend(self, loc=None): """ Add a legend to the plot. Any other value for loc else disables the legend: 1: upper right 2: upper left 3: lower left 4: lower right 5: right 6: center left 7: center right 8: lower center 9: upper center 10: center """ if isinstance(loc, int): self.loc = None if 0 <= loc <= 10: self.loc = loc else: self.loc = None #self.show() #def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True): def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, margin=None,ganged=True): """ Set the panel layout. rows and cols, if cols != 0, specify the number of rows and columns in a regular layout. (Indexing of these panels in matplotlib is row- major, i.e. column varies fastest.) cols == 0 is interpreted as a retangular layout that accomodates 'rows' panels, e.g. rows == 6, cols == 0 is equivalent to rows == 2, cols == 3. 0 <= n < rows*cols is interpreted as the 0-relative panel number in the configuration specified by rows and cols to be added to the current figure as its next 0-relative panel number (i). This allows non-regular panel layouts to be constructed via multiple calls. Any other value of n clears the plot and produces a rectangular array of empty panels. The number of these may be limited by nplots. """ if n < 0 and len(self.subplots): self.figure.clear() self.set_title() if margin: lef, bot, rig, top, wsp, hsp = margin self.figure.subplots_adjust( left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp) del lef,bot,rig,top,wsp,hsp if rows < 1: rows = 1 if cols <= 0: i = int(sqrt(rows)) if i*i < rows: i += 1 cols = i if i*(i-1) >= rows: i -= 1 rows = i if 0 <= n < rows*cols: i = len(self.subplots) self.subplots.append({}) self.subplots[i]['axes'] = self.figure.add_subplot(rows, cols, n+1) self.subplots[i]['lines'] = [] if i == 0: self.subplot(0) self.rows = 0 self.cols = 0 else: self.subplots = [] if nplots < 1 or rows*cols < nplots: nplots = rows*cols if ganged: hsp,wsp = None,None if rows > 1: hsp = 0.0001 if cols > 1: wsp = 0.0001 self.figure.subplots_adjust(wspace=wsp,hspace=hsp) for i in range(nplots): self.subplots.append({}) self.subplots[i]['lines'] = [] if not ganged: self.subplots[i]['axes'] = self.figure.add_subplot(rows, cols, i+1) if asaprcParams['plotter.axesformatting'] != 'mpl': self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) else: if i == 0: self.subplots[i]['axes'] = self.figure.add_subplot(rows, cols, i+1) if asaprcParams['plotter.axesformatting'] != 'mpl': self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) else: self.subplots[i]['axes'] = self.figure.add_subplot(rows, cols, i+1, sharex=self.subplots[0]['axes'], sharey=self.subplots[0]['axes']) # Suppress tick labelling for interior subplots. if i <= (rows-1)*cols - 1: if i+cols < nplots: # Suppress x-labels for frames width # adjacent frames for tick in self.subplots[i]['axes'].xaxis.majorTicks: tick.label1On = False #self.subplots[i]['axes'].xaxis.label.set_visible(False) if i%cols: # Suppress y-labels for frames not in the left column. for tick in self.subplots[i]['axes'].yaxis.majorTicks: tick.label1On = False #self.subplots[i]['axes'].yaxis.label.set_visible(False) # disable the first tick of [1:ncol-1] of the last row #if i+1 < nplots: # self.subplots[i]['axes'].xaxis.majorTicks[0].label1On = False # set axes label state for interior subplots. if i%cols: self.subplots[i]['axes'].yaxis.label.set_visible(False) if (i <= (rows-1)*cols - 1) and (i+cols < nplots): self.subplots[i]['axes'].xaxis.label.set_visible(False) self.rows = rows self.cols = cols self.subplot(0) del rows,cols,n,nplots,margin,ganged,i def subplot(self, i=None, inc=None): """ Set the subplot to the 0-relative panel number as defined by one or more invokations of set_panels(). """ l = len(self.subplots) if l: if i is not None: self.i = i if inc is not None: self.i += inc self.i %= l self.axes = self.subplots[self.i]['axes'] self.lines = self.subplots[self.i]['lines'] def set_axes(self, what=None, *args, **kwargs): """ Set attributes for the axes by calling the relevant Axes.set_*() method. Colour translation is done as described in the doctext for palette(). """ if what is None: return if what[-6:] == 'colour': what = what[:-6] + 'color' key = "colour" if kwargs.has_key(key): val = kwargs.pop(key) kwargs["color"] = val getattr(self.axes, "set_%s"%what)(*args, **kwargs) self.show(hardrefresh=False) def set_figure(self, what=None, *args, **kwargs): """ Set attributes for the figure by calling the relevant Figure.set_*() method. Colour translation is done as described in the doctext for palette(). """ if what is None: return if what[-6:] == 'colour': what = what[:-6] + 'color' #if what[-5:] == 'color' and len(args): # args = (get_colour(args[0]),) newargs = {} for k, v in kwargs.iteritems(): k = k.lower() if k == 'colour': k = 'color' newargs[k] = v getattr(self.figure, "set_%s"%what)(*args, **newargs) self.show(hardrefresh=False) def set_limits(self, xlim=None, ylim=None): """ Set x-, and y-limits for each subplot. xlim = [xmin, xmax] as in axes.set_xlim(). ylim = [ymin, ymax] as in axes.set_ylim(). """ for s in self.subplots: self.axes = s['axes'] self.lines = s['lines'] oldxlim = list(self.axes.get_xlim()) oldylim = list(self.axes.get_ylim()) if xlim is not None: for i in range(len(xlim)): if xlim[i] is not None: oldxlim[i] = xlim[i] if ylim is not None: for i in range(len(ylim)): if ylim[i] is not None: oldylim[i] = ylim[i] self.axes.set_xlim(oldxlim) self.axes.set_ylim(oldylim) return def set_line(self, number=None, **kwargs): """ Set attributes for the specified line, or else the next line(s) to be plotted. number is the 0-relative number of a line that has already been plotted. If no such line exists, attributes are recorded and used for the next line(s) to be plotted. Keyword arguments specify Line2D attributes, e.g. color='r'. Do import matplotlib help(matplotlib.lines) The set_* methods of class Line2D define the attribute names and values. For non-US usage, 'colour' is recognized as synonymous with 'color'. Set the value to None to delete an attribute. Colour translation is done as described in the doctext for palette(). """ redraw = False for k, v in kwargs.iteritems(): k = k.lower() if k == 'colour': k = 'color' if 0 <= number < len(self.lines): if self.lines[number] is not None: for line in self.lines[number]: getattr(line, "set_%s"%k)(v) redraw = True else: if v is None: del self.attributes[k] else: self.attributes[k] = v if redraw: self.show(hardrefresh=False) def get_line(self): """ Get the current default line attributes. """ return self.attributes ### Actual plot methods ### def hist(self, x=None, y=None, fmt=None, add=None): """ Plot a histogram. N.B. the x values refer to the start of the histogram bin. fmt is the line style as in plot(). """ from numpy import array from numpy.ma import MaskedArray if x is None: if y is None: return x = range(len(y)) if len(x) != len(y): return l2 = 2*len(x) x2 = range(l2) y2 = range(12) y2 = range(l2) m2 = range(l2) ymsk = None ydat = None if hasattr(y, "raw_mask"): # numpy < 1.1 ymsk = y.raw_mask() ydat = y.raw_data() else: ymsk = y.mask ydat = y.data for i in range(l2): x2[i] = x[i/2] m2[i] = ymsk[i/2] y2[0] = 0.0 for i in range(1,l2): y2[i] = ydat[(i-1)/2] self.plot(x2, MaskedArray(y2,mask=m2,copy=0), fmt, add) def plot(self, x=None, y=None, fmt=None, add=None): """ Plot the next line in the current frame using the current line attributes. The ASAPlot graphics window will be mapped and raised. The argument list works a bit like the matlab plot() function. """ if x is None: if y is None: return x = range(len(y)) elif y is None: y = x x = range(len(y)) if fmt is None: line = self.axes.plot(x, y) else: line = self.axes.plot(x, y, fmt) # add a picker to lines for spectral value mode. # matplotlib.axes.plot returns a list of line object (1 element) line[0].set_picker(5.0) # Add to an existing line? i = None if add is None or len(self.lines) < add < 0: # Don't add. self.lines.append(line) i = len(self.lines) - 1 else: if add == 0: add = len(self.lines) i = add - 1 self.lines[i].extend(line) # Set/reset attributes for the line. gotcolour = False for k, v in self.attributes.iteritems(): if k == 'color': gotcolour = True for segment in self.lines[i]: getattr(segment, "set_%s"%k)(v) if not gotcolour and len(self.colormap): for segment in self.lines[i]: getattr(segment, "set_color")(self.colormap[self.color]) if len(self.colormap) == 1: getattr(segment, "set_dashes")(self.linestyles[self.linestyle]) self.color += 1 if self.color >= len(self.colormap): self.color = 0 if len(self.colormap) == 1: self.linestyle += 1 if self.linestyle >= len(self.linestyles): self.linestyle = 0 self.show() def tidy(self): # this needs to be exceuted after the first "refresh" nplots = len(self.subplots) if nplots == 1: return for i in xrange(nplots): ax = self.subplots[i]['axes'] if i%self.cols: ax.xaxis.majorTicks[0].label1On = False else: if i != 0: ax.yaxis.majorTicks[-1].label1On = False ## set axes label state for interior subplots. #innerax=False #if i%self.cols: # ax.yaxis.label.set_visible(innerax) #if (i <= (self.rows-1)*self.cols - 1) and (i+self.cols < nplots): # ax.xaxis.label.set_visible(innerax) def set_title(self, title=None): """ Set the title of the plot window. Use the previous title if title is omitted. """ if title is not None: self.title = title self.figure.text(0.5, 0.95, self.title, horizontalalignment='center') def text(self, *args, **kwargs): """ Add text to the figure. """ self.figure.text(*args, **kwargs) self.show() def vline_with_label(self, x, y, label, location='bottom', rotate=0.0, **kwargs): """ Plot a vertical line with label. It takes 'world' values fo x and y. """ ax = self.axes # need this to suppress autoscaling during this function self.axes.set_autoscale_on(False) ymin = 0.0 ymax = 1.0 valign = 'center' if location.lower() == 'top': y = max(0.0, y) elif location.lower() == 'bottom': y = min(0.0, y) lbloffset = 0.06 # a rough estimate for the bb of the text if rotate > 0.0: lbloffset = 0.03*len(label) peakoffset = 0.01 xy = None xy0 = None # matplotlib api change 0.98 is using transform now if hasattr(ax.transData, "inverse_xy_tup"): # get relative coords xy0 = ax.transData.xy_tup((x,y)) xy = ax.transAxes.inverse_xy_tup(xy0) else: xy0 = ax.transData.transform((x,y)) # get relative coords xy = ax.transAxes.inverted().transform(xy0) if location.lower() == 'top': ymax = 1.0-lbloffset ymin = xy[1]+peakoffset valign = 'bottom' ylbl = ymax+0.01 elif location.lower() == 'bottom': ymin = lbloffset ymax = xy[1]-peakoffset valign = 'top' ylbl = ymin-0.01 trans = blended_transform_factory(ax.transData, ax.transAxes) l = ax.axvline(x, ymin, ymax, color='black', **kwargs) t = ax.text(x, ylbl ,label, verticalalignment=valign, horizontalalignment='center', rotation=rotate,transform = trans) self.axes.set_autoscale_on(True) def release(self): """ Release buffered graphics. """ self.buffering = False self.show() def show(self, hardrefresh=True): """ Show graphics dependent on the current buffering state. """ if not hardrefresh: return if not self.buffering: if self.loc is not None: for sp in self.subplots: lines = [] labels = [] i = 0 for line in sp['lines']: i += 1 if line is not None: lines.append(line[0]) lbl = line[0].get_label() if lbl == '': lbl = str(i) labels.append(lbl) if len(lines): fp = FP(size=rcParams['legend.fontsize']) #fsz = fp.get_size_in_points() - len(lines) fsz = fp.get_size_in_points() - max(len(lines),self.cols) #fp.set_size(max(fsz,6)) fp.set_size(max(fsz,8)) sp['axes'].legend(tuple(lines), tuple(labels), self.loc, prop=fp) #else: # sp['axes'].legend((' ')) from matplotlib.artist import setp fpx = FP(size=rcParams['xtick.labelsize']) xts = fpx.get_size_in_points()- (self.cols)/2 fpy = FP(size=rcParams['ytick.labelsize']) yts = fpy.get_size_in_points() - (self.rows)/2 fpa = FP(size=rcParams['axes.labelsize']) fpat = FP(size=rcParams['axes.titlesize']) axsize = fpa.get_size_in_points() tsize = fpat.get_size_in_points()-(self.cols)/2 for sp in self.subplots: ax = sp['axes'] ax.title.set_size(tsize) setp(ax.get_xticklabels(), fontsize=xts) setp(ax.get_yticklabels(), fontsize=yts) off = 0 if self.cols > 1: off = self.cols ax.xaxis.label.set_size(axsize-off) off = 0 if self.rows > 1: off = self.rows ax.yaxis.label.set_size(axsize-off) def save(self, fname=None, orientation=None, dpi=None, papertype=None): """ Save the plot to a file. fname is the name of the output file. The image format is determined from the file suffix; 'png', 'ps', and 'eps' are recognized. If no file name is specified 'yyyymmdd_hhmmss.png' is created in the current directory. """ from asap import rcParams if papertype is None: papertype = rcParams['plotter.papertype'] if fname is None: from datetime import datetime dstr = datetime.now().strftime('%Y%m%d_%H%M%S') fname = 'asap'+dstr+'.png' d = ['png','.ps','eps', 'svg'] from os.path import expandvars fname = expandvars(fname) if fname[-3:].lower() in d: try: if fname[-3:].lower() == ".ps": from matplotlib import __version__ as mv w = self.figure.get_figwidth() h = self.figure.get_figheight() if orientation is None: # oriented if w > h: orientation = 'landscape' else: orientation = 'portrait' from matplotlib.backends.backend_ps import papersize pw,ph = papersize[papertype.lower()] ds = None if orientation == 'landscape': ds = min(ph/w, pw/h) else: ds = min(pw/w, ph/h) ow = ds * w oh = ds * h self.figure.set_size_inches((ow, oh)) self.figure.savefig(fname, orientation=orientation, papertype=papertype.lower()) self.figure.set_size_inches((w, h)) print 'Written file %s' % (fname) else: if dpi is None: dpi =150 self.figure.savefig(fname,dpi=dpi) print 'Written file %s' % (fname) except IOError, msg: #print 'Failed to save %s: Error msg was\n\n%s' % (fname, err) asaplog.post() asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg))) asaplog.post( 'ERROR' ) return else:
class MultipanelMovie(object): def __init__(self, title='', frame_duration=40.0): self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.panels = [] self.title = title self.frame_duration = frame_duration def add_panel(self, obj, bottomleft_corner, width, height): """ obj must be an object that has a string attribute `plot_function` and a method `next_frame()`. """ panel = self.fig.add_axes([bottomleft_corner[0], bottomleft_corner[1], width, height]) self.panels.append((panel, obj)) return panel def get_panel(self, obj): for panel,_obj in self.panels: if obj_ == obj: return panel return None def add_text(self, bottomleft_corner, text, **kwargs): x, y = bottomleft_corner self.fig.text(x, y, text, **kwargs) def write_frames(self, nframes): if nframes >= 1e6: raise Exception("Cannot handle movies with 1 million frames or more.") self.frame_directory = tempfile.mkdtemp(prefix='tmp_neurotools_visualization_') time_label = self.fig.text(0.01, 0.01, "t = 0 ms", horizontalalignment='left') for i in range(int(nframes)): for panel,obj in self.panels: assert self.frame_duration == obj.frame_duration, "%s != %s" % (self.frame_duration, obj.frame_duration) panel.lines = []; panel.images = [] plot = getattr(panel, obj.plot_function) plot(*obj.next_frame(), **obj.kwargs) if obj.plot_function == "imshow" and i==0: pos = panel.get_position() try: l,b,w,h = pos # older versions of Matplotlib except TypeError: l,b,w,h = pos.bounds # newer versions return a Bbox object cb_panel = self.fig.add_axes([l+w, b, 0.05*w, h]) self.fig.colorbar(panel.images[0], cb_panel) time_label.set_text("t = %g ms" % (i*self.frame_duration,)) self.canvas.print_figure(os.path.join(self.frame_directory, "frame%06d.png" % i)) progress_bar(float(i)/nframes) def __del__(self): # when the object is deleted, delete temp directory if hasattr(self, 'frame_directory'): shutil.rmtree(self.frame_directory, ignore_errors=False) def render(self, filename, fps=25): command = "mencoder 'mf://%s/frame*.png' -mf type=png:fps=%d -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s" % (self.frame_directory, fps, filename) print command os.system(command)
class MediaPanel(wx.Panel): """" clase llamada por MediaFrame (padre)""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) #Para el menu de archivos y el modelo a usar por defecto sp = wx.StandardPaths.Get() self.currentFolder = sp.GetDocumentsDir() self.currentFile = '' self.s='' #modelo de reconocimiento self.currentModel = 'C:\Users\Mario\Desktop\hito1\modelos\ExtraTreesClassifier_Apr0816\ExtraTreesClassifier_Apr0816.pkl' #cantidad de segundos de inicio self.ventana=180 #control de offset para la grafica self.t=0 self.bloqueo=False #contador de tiempo inicial self.marcador='00:00:00' self.inicio_grabacion = datetime.datetime(2000, 1, 1, 0, 0) #parent y creacion de menu y apariencia self.frame = parent self.SetBackgroundColour("white") self.currentVolume = 50 self.createMenu() self.layoutControls() self.Bind(wx.EVT_SIZE, self.onSize) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.onTimer) self.timer.Start(100) #---------------------------------------------------------------------- def layoutControls(self): """ Creacion de dispositivos de la aplicacion """ try: self.mediaPlayer = wx.media.MediaCtrl(self, style=wx.RAISED_BORDER) except NotImplementedError: self.Destroy() raise #self.Bind(wx.EVT_PAINT, self.OnDibujo) # barra de reproduccion ################ sliderSizer = wx.BoxSizer(wx.HORIZONTAL) self.playbackSlider = wx.Slider(self, size=wx.DefaultSize) self.Bind(wx.EVT_SLIDER, self.onSeek, self.playbackSlider) sliderSizer.Add(self.playbackSlider, 3, wx.ALL|wx.EXPAND, 5) #CANVAS (figura) y barra de herramientas ##################### self.figure = Figure(facecolor='white') self.axes = self.figure.add_subplot(111) self.axes.get_yaxis().set_visible(False) self.figure.text(0.5, 0.04, 'tiempo', ha='center', va='center') self.axes.grid() self.canvas = FigureCanvas(self, -1, self.figure) self.chart_toolbar = MyCustomToolbar(self.canvas) self.chart_toolbar.Realize() ###### SIZERS ################################### mainSizer = wx.BoxSizer(wx.VERTICAL) self.barra_1h_hora_sizer = wx.BoxSizer(wx.VERTICAL) self.barra_1h_hora_sizer1 = wx.BoxSizer(wx.HORIZONTAL) self.barra_1h_hora_sizer2 = wx.BoxSizer(wx.HORIZONTAL) self.barra_1h_hora_sizer.Add(self.barra_1h_hora_sizer1, 0, wx.EXPAND) self.barra_1h_hora_sizer.Add(self.barra_1h_hora_sizer2, 0, wx.EXPAND) self.audioSizer = self.buildAudioBar() #self.anuncios = wx.StaticText(self,1,"Anuncios",(200, 300) ) #widgets--COLOCACION DE BARRA DE REPRODUCCION, CONTROLADORES Y GRAFICA mainSizer.Add(self.barra_1h_hora_sizer, 0, wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND, 50) mainSizer.Add(sliderSizer, 0, wx.ALL|wx.EXPAND, 50) mainSizer.Add(self.audioSizer, 0, wx.CENTER, 1) mainSizer.Add(self.canvas, 1, wx.CENTER|wx.EXPAND, 0) mainSizer.Add(self.chart_toolbar, 1, flag=wx.ALIGN_CENTER, border=2) #mainSizer.Add(self.anuncios, 1, wx.EXPAND, 0) self.SetSizerAndFit(mainSizer) self.Layout() def resultProducer(self, audio,): """Pretend to be a complex worker function or something that takes long time to run due to network access etc. GUI will freeze if this method is not called in separate thread.""" # import time # count = 0 # while not abortEvent() and count < 50: # time.sleep(0.1) # count += 1 # return jobID global lista_anuncios lista_anuncios = reconocedor_mayo.reconocedor(audio) return lista_anuncios def resultConsumer(self, delayedResult): try: result = delayedResult.get() except Exception, exc: # self.log("Result for job raised exception: %s" % (exc)) print exc return # output result # self.log("Got result for job: %s" % (result)) # self.textCtrlResult.SetValue(str(result)) if result: for a in result: self.th.AppendText(a['nombre'] + ' - ' + str(a['inicio'].time()) + ' \n') self.th.AppendText('result\n') if lista_anuncios: for a in lista_anuncios: self.th.AppendText(a['nombre'] + ' - ' + str(a['inicio'].time()) + ' \n') self.th.AppendText('lista_anuncios\n')