def showModel3d(basedir,ptcode, ctcode, cropname='ring', showVol='MIP', showmodel=True, graphname='model', **kwargs): """ show model and vol in 3d by mip iso or 2D graphname 'all' draws all graph models stored in s, if multiple """ s = loadmodel(basedir, ptcode, ctcode, cropname, modelname='modelavgreg') vol = loadvol(basedir, ptcode, ctcode, cropname, what='avgreg').vol # figure f = vv.figure(); vv.clf() f.position = 0.00, 22.00, 1920.00, 1018.00 a = vv.gca() a.axis.axisColor = 1,1,1 a.axis.visible = False a.bgcolor = 0,0,0 a.daspect = 1, 1, -1 t = show_ctvolume(vol, axis=a, showVol=showVol, removeStent=False, climEditor=True, **kwargs) label = pick3d(a, vol) vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') if showmodel: if graphname == 'all': for key in dir(s): if key.startswith('model'): s[key].Draw(mc='b', mw = 5, lc='g', alpha = 0.5) else: s[graphname].Draw(mc='b', mw = 5, lc='g', alpha = 0.5) vv.title('Model for LSPEAS %s - %s' % (ptcode[8:], ctcode)) # f.eventKeyDown.Bind(lambda event: _utils_GUI.RotateView(event, [a], axishandling=False )) f.eventKeyDown.Bind(lambda event: _utils_GUI.ViewPresets(event, [a]) ) return f, a, label, s
def DoAction(self): """ This method is affiliated to the method <self.SartAction> """ #################################################### # # Zak add you code here # e.g., in what follows we just acquire spectra # #################################################### # If you want to apply some radom phase maske then uncomment the following: #amplitude_mask = self.PulseShaper.GetZeroMask() + 1 #phase_mask = np.random.rand(max_amplitude_mask.size) #self.PulseShaper.SetMasks(amplitude_mask, phase_mask) # Getting spectrum spectrum = self.Spectrometer.AcquiredData() # Plot the spectra visvis.gca().Clear() visvis.plot(self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") visvis.title("Spectrum from radom pulse shape") self.fig.DrawNow() # Going to the next iteration if self._continue_action: wx.CallAfter(self.DoAction)
def DisplayOptimization (self) : """ Display the progress of optimization """ wx.Yield() # abort, if requested if self.need_abort : return def GetValueColourIter (d) : return izip_longest( d.itervalues(), ['r', 'g', 'b', 'k'], fillvalue='y' ) visvis.cla(); visvis.clf() visvis.subplot(211) # Plot optimization statistics for values, colour in GetValueColourIter(self.optimization_log) : try : visvis.plot ( values, lc=colour ) except Exception : pass visvis.xlabel ('iteration') visvis.ylabel ('Objective function') visvis.legend( self.optimization_log.keys() ) # Display reference signal visvis.subplot(212) # Plot reference signal for values, colour in GetValueColourIter(self.log_reference_signal) : try : visvis.plot ( values, lc=colour ) except Exception : pass visvis.xlabel ('iteration') visvis.ylabel ("Signal from reference pulse") visvis.legend( ["channel %d" % x for x in self.log_reference_signal.keys()] )
def PlotReferencePhase(self, event): """ Plot reference phase """ visvis.cla() visvis.clf() # get actual amplitude and phased phase = self.GetReferencePhase()[0] ampl = np.ones(phase.size) ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase(ampl, phase) # Wrap the phase in radians phase %= (2 * np.pi) # Get the phase in unites of 2*pi phase /= (2 * np.pi) visvis.subplot(211) visvis.plot(phase) visvis.ylabel('Reference phase') visvis.xlabel('puls shaper pixel number') visvis.title('Current reference phase (in unites of 2*pi)') visvis.subplot(212) visvis.plot(self.corrections, lc='r', ms='*', mc='r') visvis.ylabel('Value of coefficients') visvis.xlabel('coefficient number') visvis.title('Value of corrections')
def vis2Dfit(fitted, ptcode, ctcode, showAxis): """Visualize ellipse fit in 2D in current axis input: fitted = _fit3D output = (pp3, plane, pp3_2, e3) """ from stentseg.utils import fitting import numpy as np plane,pp3_2,e3 = fitted[1],fitted[2],fitted[3] # endpoints axis x0,y0,res1,res2,phi = e3[0], e3[1], e3[2], e3[3], e3[4] dxax1 = np.cos(phi)*res1 dyax1 = np.sin(phi)*res1 dxax2 = np.cos(phi+0.5*np.pi)*res2 dyax2 = np.sin(phi+0.5*np.pi)*res2 p1ax1, p2ax1 = (x0+dxax1, y0+dyax1), (x0-dxax1, y0-dyax1) p1ax2, p2ax2 = (x0+dxax2, y0+dyax2), (x0-dxax2, y0-dyax2) a = vv.gca() vv.xlabel('x (mm)');vv.ylabel('y (mm)') vv.title('Ellipse fit for model %s - %s' % (ptcode[7:], ctcode)) a.axis.axisColor= 0,0,0 a.bgcolor= 0,0,0 a.axis.visible = showAxis a.daspectAuto = False a.axis.showGrid = True vv.plot(pp3_2, ls='', ms='.', mc='r', mw=9) vv.plot(fitting.sample_ellipse(e3), lc='b', lw=2) vv.plot(np.array([p1ax1, p2ax1]), lc='w', lw=2) # major axis vv.plot(np.array([p1ax2, p2ax2]), lc='w', lw=2) # minor axis vv.legend('3D points projected to plane', 'Ellipse fit on projected points')
def vis3Dfit(fitted, vol, model, ptcode, ctcode, showAxis, **kwargs): """Visualize ellipse fit in 3D with CT volume in current axis input: fitted = _fit3D output = (pp3, plane, pp3_2, e3) """ from stentseg.utils import fitting import numpy as np pp3,plane,pp3_2,e3 = fitted[0],fitted[1],fitted[2],fitted[3] a = vv.gca() # show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh) show_ctvolume(vol, model, **kwargs) vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') vv.title('Ellipse fit for model %s - %s' % (ptcode[7:], ctcode)) a.axis.axisColor= 1,1,1 a.bgcolor= 0,0,0 a.daspect= 1, 1, -1 # z-axis flipped a.axis.visible = showAxis # For visualization, calculate 4 points on rectangle that lies on the plane x1, x2 = pp3.min(0)[0]-0.3, pp3.max(0)[0]+0.3 y1, y2 = pp3.min(0)[1]-0.3, pp3.max(0)[1]+0.3 p1 = x1, y1, -(x1*plane[0] + y1*plane[1] + plane[3]) / plane[2] p2 = x2, y1, -(x2*plane[0] + y1*plane[1] + plane[3]) / plane[2] p3 = x2, y2, -(x2*plane[0] + y2*plane[1] + plane[3]) / plane[2] p4 = x1, y2, -(x1*plane[0] + y2*plane[1] + plane[3]) / plane[2] vv.plot(pp3, ls='', ms='.', mc='y', mw = 10) vv.plot(fitting.project_from_plane(pp3_2, plane), lc='r', ls='', ms='.', mc='r', mw=9) # vv.plot(fitting.project_from_plane(fitting.sample_circle(c3), plane), lc='r', lw=2) vv.plot(fitting.project_from_plane(fitting.sample_ellipse(e3), plane), lc='b', lw=2) vv.plot(np.array([p1, p2, p3, p4, p1]), lc='g', lw=2) # vv.legend('3D points', 'Projected points', 'Circle fit', 'Ellipse fit', 'Plane fit') vv.legend('3D points', 'Projected points', 'Ellipse fit', 'Plane fit')
def figparts(): """ Visualize ring parts """ fig = vv.figure(4); fig.position = 8.00, 30.00, 944.00, 1002.00 vv.clf() a0 = vv.subplot(121) show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh) modelR1, modelR2 = modelsR1R2[0][0], modelsR1R2[0][1] modelR1.Draw(mc='g', mw = 10, lc='g') # R1 = green modelR2.Draw(mc='c', mw = 10, lc='c') # R2 = cyan vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') vv.title('Analysis for model LSPEAS %s - %s' % (ptcode[7:], ctcode)) a0.axis.axisColor= 1,1,1 a0.bgcolor= 0,0,0 a0.daspect= 1, 1, -1 # z-axis flipped a0.axis.visible = showAxis a1 = vv.subplot(122) show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh) models[0][0].Draw(mc='y', mw = 10, lc='y') # struts = yellow models[0][1].Draw(mc='r', mw = 10, lc='r') # hooks = red vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') vv.title('Analysis for model LSPEAS %s - %s' % (ptcode[7:], ctcode)) a1.axis.axisColor= 1,1,1 a1.bgcolor= 0,0,0 a1.daspect= 1, 1, -1 # z-axis flipped a1.axis.visible = showAxis a0.camera = a1.camera
def plot(image): # ax = vv.gca() # ms = vv.Mesh(ax) logging.warning([image.shape, image.spacing]) vol = image[:, :, :, 0] logging.warning([vol.min(), vol.max()]) vol = util.normalize(vol, 'ADCm') logging.warning([vol.min(), vol.max()]) vol = vv.Aarray(vol, image.spacing) cmap = None # cmap = vv.CM_VIRIDIS render_style = 'mip' # render_style = 'iso' # render_style = 'ray' # render_style = 'edgeray' # render_style = 'litray' vv.figure() vv.xlabel('x axis') vv.ylabel('y axis') vv.zlabel('z axis') a1 = vv.subplot(111) t1 = vv.volshow(vol, cm=cmap, renderStyle=render_style) t1.isoThreshold = 0.7 vv.title(render_style) # a1.camera = a2.camera = a3.camera vv.ColormapEditor(a1)
def show_surface_and_vol(vol, pp_isosurface, showVol='MIP', clim=(-200, 1000), isoTh=300, climEditor=True): """ Show the generated isosurface in original volume """ f = vv.figure() ax = vv.gca() ax.daspect = 1, 1, -1 ax.axis.axisColor = 1, 1, 1 ax.bgcolor = 0, 0, 0 # show vol and iso vertices show_ctvolume(vol, showVol=showVol, isoTh=isoTh, clim=clim, climEditor=climEditor) label = pick3d(vv.gca(), vol) vv.plot(pp_isosurface, ms='.', ls='', mc='r', alpha=0.2, mw=4) a = vv.gca() f.eventKeyDown.Bind(lambda event: _utils_GUI.ViewPresets(event, [a])) print('------------------------') print('Use keys 1, 2, 3, 4 and 5 for preset anatomic views') print('Use v for a default zoomed view') print('Use x to show and hide axis') print('------------------------') vv.xlabel('x (mm)') vv.ylabel('y (mm)') vv.zlabel('z (mm)') return label
def PlotReferencePhase (self, event) : """ Plot reference phase """ visvis.cla(); visvis.clf(); # get actual amplitude and phased phase = self.GetReferencePhase()[0] ampl = np.ones(phase.size) ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase(ampl, phase) # Wrap the phase in radians phase %= (2*np.pi) # Get the phase in unites of 2*pi phase /= (2*np.pi) visvis.subplot(211) visvis.plot(phase) visvis.ylabel ('Reference phase') visvis.xlabel ('puls shaper pixel number') visvis.title ('Current reference phase (in unites of 2*pi)') visvis.subplot(212) visvis.plot( self.corrections, lc='r',ms='*', mc='r' ) visvis.ylabel ('Value of coefficients') visvis.xlabel ('coefficient number') visvis.title ('Value of corrections')
def drawmodelphasescycles(vol1, model1, modelori1, showVol, isoTh=300, removeStent=False, showmodelavgreg=False, showvol=True, phases=range(10), colors='cgmrcgywmb', meshWithColors=False, stripSizeZ=None, ax=None): """ draw model and volume (show optional) at different phases cycle """ if ax is None: ax = vv.gca() ax.daspect = 1, 1, -1 ax.axis.axisColor = 0, 0, 0 ax.bgcolor = 1, 1, 1 vv.xlabel('x (mm)') vv.ylabel('y (mm)') vv.zlabel('z (mm)') # draw t = show_ctvolume(vol1, modelori1, showVol=showVol, removeStent=removeStent, climEditor=True, isoTh=isoTh, clim=clim0, stripSizeZ=stripSizeZ) if showmodelavgreg: # show model and CT mid cycle mw = 5 for model in model1: model.Draw(mc='b', mw=mw, lc='b', alpha=0.5) label = pick3d(ax, vol1) if not showvol: t.visible = False # get models in different phases for model in model1: for phasenr in phases: model_phase = get_graph_in_phase(model, phasenr=phasenr) if meshWithColors: modelmesh1 = create_mesh_with_abs_displacement(model_phase, radius=radius, dim=dimensions) m = vv.mesh(modelmesh1, colormap=vv.CM_JET, clim=clim2) #todo: use colormap Viridis or Magma as JET is not linear (https://bids.github.io/colormap/) else: model_phase.Draw(mc=colors[phasenr], mw=10, lc=colors[phasenr]) # modelmesh1 = create_mesh(model_phase, radius = radius) # m = vv.mesh(modelmesh1); m.faceColor = colors[phasenr] if meshWithColors: vv.colorbar() return ax
def ScanVoltage(self): """ Using the iterator <self.scan_pixel_voltage_pair> record the spectral response by applying the voltages """ # Pause calibration, if user requested try: if self.pause_calibration: return except AttributeError: return try: param = self.scan_pixel_voltage_pair.next() self.PulseShaper.SetUniformMasks(*param) # Getting spectrum spectrum = self.Spectrometer.AcquiredData() # Save the spectrum try: self.SpectraGroup["voltages_%d_%d" % param] = spectrum except RuntimeError: print "There was RuntimeError while saving scan voltages_%d_%d" % param # Plot the spectra visvis.gca().Clear() visvis.plot(self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") # Scanning progress info self.scanned += 1. percentage_completed = 100. * self.scanned / self.scan_length seconds_left = (time.clock() - self.initial_time) * ( 100. / percentage_completed - 1.) # convert to hours:min:sec m, s = divmod(seconds_left, 60) h, m = divmod(m, 60) title_info = param + (percentage_completed, h, m, s) visvis.title( "Scanning spectrum by applying voltages %d/%d. Progress: %.1f%% completed. Time left: %d:%02d:%02d." % title_info) self.fig.DrawNow() # Measure the next pair wx.CallAfter(self.ScanVoltage) except StopIteration: # Perform processing of the measured data wx.CallAfter(self.ExtractPhaseFunc, filename=self.calibration_file.filename) # All voltages are scanned self.StopAllJobs() # Sop using the shaper self.PulseShaper.StopDevice()
def DrawSpectrum(self, event): """ Draw spectrum interactively """ spectrum = self.Spectrometer.AcquiredData() if spectrum == RETURN_FAIL: return # Display the spectrum if len(spectrum.shape) > 1: try: self.__interact_2d_spectrum__.SetData(spectrum) except AttributeError: visvis.cla() visvis.clf() # Spectrum is a 2D image visvis.subplot(211) self.__interact_2d_spectrum__ = visvis.imshow(spectrum, cm=visvis.CM_JET) visvis.subplot(212) # Plot a vertical binning spectrum = spectrum.sum(axis=0) # Linear spectrum try: self.__interact_1d_spectrum__.SetYdata(spectrum) except AttributeError: if self.wavelengths is None: self.__interact_1d_spectrum__ = visvis.plot(spectrum, lw=3) visvis.xlabel("pixels") else: self.__interact_1d_spectrum__ = visvis.plot(self.wavelengths, spectrum, lw=3) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") if self.is_autoscaled_spectrum: # Smart auto-scale linear plot try: self.spectrum_plot_limits = GetSmartAutoScaleRange( spectrum, self.spectrum_plot_limits) except AttributeError: self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum) visvis.gca().SetLimits(rangeY=self.spectrum_plot_limits) # Display the current temperature try: visvis.title("Temperature %d (C)" % self.Spectrometer.GetTemperature()) except AttributeError: pass
def AnalyzeTotalFluorescence (self, event=None) : """ `analyse_button` was clicked """ # Get current settings settings = self.GetSettings() # Apply peak finding filter signal = self.peak_finders[ settings["peak_finder"] ](self.total_fluorescence) # Scale to (0,1) signal -= signal.min() signal = signal / signal.max() ########################################################################## # Partition signal into segments that are above the background noise #signal = gaussian_filter(total_fluorescence, sigma=0.5) background_cutoff = settings["background_cutoff"] segments = [ [] ] for num, is_segment in enumerate( signal > background_cutoff ) : if is_segment : # this index is in the segment segments[-1].append( num ) elif len(segments[-1]) : # this condition is not to add empty segments # Start new segments segments.append( [] ) # Find peaks as weighted average of the segment peaks = [ np.average(self.positions[S], weights=self.total_fluorescence[S]) for S in segments if len(S) ] ########################################################################## # Saving the positions self.chanel_positions_ctrl.SetValue( ", ".join( "%2.4f" % p for p in peaks ) ) ########################################################################## # Plot acquired data visvis.cla(); visvis.clf() visvis.plot( self.positions, signal ) visvis.plot( peaks, background_cutoff*np.ones(len(peaks)), ls=None, ms='+', mc='r', mw=20) visvis.plot( [self.positions.min(), self.positions.max()], [background_cutoff, background_cutoff], lc='r', ls='--', ms=None) visvis.legend( ["measured signal", "peaks found", "background cut-off"] ) visvis.ylabel( "total fluorescence") visvis.xlabel( 'position (mm)')
def visVol(volData): """ This example demonstrates rendering a color volume. We demonstrate two renderers capable of rendering color data: the colormip and coloriso renderer. """ import visvis as vv app = vv.use() # Load volume vol = volData # set labels vv.xlabel("x axis") vv.ylabel("y axis") vv.zlabel("z axis") # # Create figure and make subplots with different renderers # vv.figure(1); vv.clf() # RS = ['mip', 'iso', 'edgeray', 'ray', 'litray'] # a0 = None # tt = [] # for i in range(5): # a = vv.subplot(3,2,i+2) # t = vv.volshow(vol) # vv.title('Renderstyle ' + RS[i]) # t.colormap = vv.CM_HOT # t.renderStyle = RS[i] # t.isoThreshold = 200 # Only used in iso render style # tt.append(t) # if a0 is None: # a0 = a # else: # a.camera = a0.camera t = vv.volshow(vol, renderStyle="edgeray") t.colormap = vv.CM_HOT # Get axes and set camera to orthographic mode (with a field of view of 70) a = vv.gca() a.camera.fov = 45 # Create colormap editor wibject. vv.ColormapEditor(a) # Create colormap editor in first axes # cme = vv.ColormapEditor(vv.gcf(), t) # Run app # app.Create() app.Run()
def DrawModelAxes(vol, graph=None, ax=None, axVis=False, meshColor=None, getLabel=False, mc='b', lc='g', mw=7, lw=0.6, **kwargs): """ Draw model with volume with axes set ax = axes to draw (a1 or a2 or a3); graph = sd._nodes1 or 2 or 3 meshColor = None or faceColor e.g. 'g' """ #todo: prevent TypeError: draw() got an unexpected keyword argument mc/lc when not given as required variable #todo: *args voor vol in drawModelAxes of **kwargs[key] in functies hieronder if ax is None: ax = vv.gca() ax.MakeCurrent() ax.daspect = 1, 1, -1 ax.axis.axisColor = 1, 1, 1 ax.bgcolor = 0, 0, 0 ax.axis.visible = axVis vv.xlabel('x (mm)') vv.ylabel('y (mm)') vv.zlabel('z (mm)') if graph is None: show_ctvolume(vol, graph, axis=ax, removeStent=False, **kwargs) label = pick3d(vv.gca(), vol) return label if hasattr(graph, 'number_of_edges'): if graph.number_of_edges( ) == 0: # get label from picked seeds sd._nodes1 show_ctvolume(vol, graph, axis=ax, **kwargs) label = pick3d(vv.gca(), vol) graph.Draw(mc=mc, lc=lc) return label if not meshColor is None: bm = create_mesh(graph, 0.5) # (argument is strut tickness) m = vv.mesh(bm) m.faceColor = meshColor # 'g' show_ctvolume(vol, graph, axis=ax, **kwargs) graph.Draw(mc=mc, lc=lc) if getLabel == True: label = pick3d(vv.gca(), vol) return label else: pick3d(vv.gca(), vol) return
def ScanVoltage (self) : """ Using the iterator <self.scan_pixel_voltage_pair> record the spectral response by applying the voltages """ # Pause calibration, if user requested try : if self.pause_calibration : return except AttributeError : return try : param = self.scan_pixel_voltage_pair.next() self.PulseShaper.SetUniformMasks(*param) # Getting spectrum spectrum = self.Spectrometer.AcquiredData() # Save the spectrum try : self.SpectraGroup["voltages_%d_%d" % param] = spectrum except RuntimeError : print "There was RuntimeError while saving scan voltages_%d_%d" % param # Plot the spectra visvis.gca().Clear() visvis.plot (self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") # Scanning progress info self.scanned += 1. percentage_completed = 100.*self.scanned/self.scan_length seconds_left = ( time.clock() - self.initial_time )*(100./percentage_completed - 1.) # convert to hours:min:sec m, s = divmod(seconds_left, 60) h, m = divmod(m, 60) title_info = param + (percentage_completed, h, m, s) visvis.title ("Scanning spectrum by applying voltages %d/%d. Progress: %.1f%% completed. Time left: %d:%02d:%02d." % title_info) self.fig.DrawNow() # Measure the next pair wx.CallAfter(self.ScanVoltage) except StopIteration : # Perform processing of the measured data wx.CallAfter(self.ExtractPhaseFunc, filename=self.calibration_file.filename) # All voltages are scanned self.StopAllJobs() # Sop using the shaper self.PulseShaper.StopDevice()
def __init__(self, sampleinterval=0.1, timewindow=10.0, size=(600, 350)): # Data stuff self._interval = int(sampleinterval * 1000) self._bufsize = int(timewindow / sampleinterval) self.databuffer = collections.deque([0.0] * self._bufsize, self._bufsize) self.x = np.linspace(-timewindow, 0.0, self._bufsize) self.y = np.zeros(self._bufsize, dtype=np.float) # Visvis stuff self.app = vv.use("qt4") vv.title("Dynamic Plotting with VisVis") self.line = vv.plot(self.x, self.y, lc="b", lw=3, ms="+") vv.xlabel("time") vv.ylabel("amplitude") self.ax = vv.gca() self.timer = vv.Timer(self.app, 50, oneshot=False) self.timer.Bind(self.updateplot) self.timer.Start()
def DrawSpectrum (self, event) : """ Draw spectrum interactively """ spectrum = self.Spectrometer.AcquiredData() if spectrum == RETURN_FAIL : return # Display the spectrum if len(spectrum.shape) > 1: try : self.__interact_2d_spectrum__.SetData(spectrum) except AttributeError : visvis.cla(); visvis.clf(); # Spectrum is a 2D image visvis.subplot(211) self.__interact_2d_spectrum__ = visvis.imshow(spectrum, cm=visvis.CM_JET) visvis.subplot(212) # Plot a vertical binning spectrum = spectrum.sum(axis=0) # Linear spectrum try : self.__interact_1d_spectrum__.SetYdata(spectrum) except AttributeError : if self.wavelengths is None : self.__interact_1d_spectrum__ = visvis.plot (spectrum, lw=3) visvis.xlabel ("pixels") else : self.__interact_1d_spectrum__ = visvis.plot (self.wavelengths, spectrum, lw=3) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") if self.is_autoscaled_spectrum : # Smart auto-scale linear plot try : self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum, self.spectrum_plot_limits) except AttributeError : self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum) visvis.gca().SetLimits ( rangeY=self.spectrum_plot_limits ) # Display the current temperature try : visvis.title ("Temperature %d (C)" % self.Spectrometer.GetTemperature() ) except AttributeError : pass
def show_vox(self, vfunc): """ Displays a 3-D rendering of a voxelized property. :param vfunc: function accepting this MasonView instance and returning a 3-D np.array of some voxelized property """ app = vv.use() vv.figure(1) vv.xlabel('Eastings (units)') vv.ylabel('Northings (units)') vv.zlabel('Depth (units)') a = vv.gca() a.camera.fov = 70 a.daspect = 1, 1, -1 vox = vfunc(self) t = vv.volshow(vox, cm=vv.CM_JET, renderStyle='ray') vv.ColormapEditor(a) app.Run()
def ShowSpectra_by_VaryingPixelBundle(self): """ This method is affiliated to the method <self.VaryPixelBundle> """ # Exit if the iterator is not defined try: self.pixel_bundel_value_iter except AttributeError: return try: voltage = self.pixel_bundel_value_iter.next() # Set the mask for pixel bundle width = self.SettingsNotebook.CalibrateShaper.pixel_bundle_width.GetValue( ) / 2 start_pixel_bundle = self.pixel_to_vary.GetValue() mask = np.copy(self.fixed_mask) if width: mask[max(start_pixel_bundle - width, 0):min(mask.size, start_pixel_bundle + width)] = voltage else: # Enforce single pixel width mask[min(max(start_pixel_bundle, 0), mask.size)] = voltage self.PulseShaper.SetMasks(mask, self.fixed_mask) # Getting spectrum spectrum = self.Spectrometer.AcquiredData() # Plot the spectra visvis.gca().Clear() visvis.plot(self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") visvis.title("Voltage %d / %d " % (voltage, self.fixed_mask[0])) self.fig.DrawNow() # Going to the next iteration wx.CallAfter(self.ShowSpectra_by_VaryingPixelBundle) except StopIteration: # Finish the job self.StopAllJobs()
def __init__(self, sampleinterval=0.1, timewindow=10., size=(600, 350)): # Data stuff self._interval = int(sampleinterval * 1000) self._bufsize = int(timewindow / sampleinterval) self.databuffer = collections.deque([0.0] * self._bufsize, self._bufsize) self.x = np.linspace(-timewindow, 0.0, self._bufsize) self.y = np.zeros(self._bufsize, dtype=np.float) # Visvis stuff self.app = vv.use('qt4') vv.title('Dynamic Plotting with VisVis') self.line = vv.plot(self.x, self.y, lc='b', lw=3, ms='+') vv.xlabel('time') vv.ylabel('amplitude') self.ax = vv.gca() self.timer = vv.Timer(self.app, 50, oneshot=False) self.timer.Bind(self.updateplot) self.timer.Start()
def draw_spectrum (event) : """Timer function """ spectrum = self.Spectrometer.AcquiredData() if spectrum == RETURN_FAIL : return # Display the spectrum ############### Take the log of spectrum ########## #spectrum = spectrum / float(spectrum.max()) #np.log10(spectrum, out=spectrum) ############################## ax = visvis.gca() ax.Clear() visvis.plot (self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") # Display the current temperature visvis.title ("Temperature %d (C)" % self.Spectrometer.GetTemperature() )
def psf_volume(stack, xyz_ratio, filepath): app = vv.use() # Init a figure with two axes a1 = vv.subplot(121) vv.title('PSF Volume') a2 = vv.subplot(122) vv.title('PSF XYZ Cross Sections') # show t1 = vv.volshow(stack, axes=a1) # volume t2 = vv.volshow2(stack, axes=a2) # cross-section interactive # set labels for both axes vv.xlabel('Pixel X', axes=a1) vv.ylabel('Pixel Y', axes=a1) vv.zlabel('Z-Slice', axes=a1) vv.xlabel('Pixel X', axes=a2) vv.ylabel('Pixel Y', axes=a2) vv.zlabel('Z-Slice', axes=a2) # set colormaps t1.colormap = vv.CM_JET t2.colormap = vv.CM_JET # set correct aspect ration corresponding to voxel size a1.daspect = 1, 1, xyz_ratio a2.daspect = 1, 1, xyz_ratio # show grid a1.axis.showGrid = 1 a2.axis.showGrid = 1 # run visvis and show results app.Run() # save screenshot if filepath != 'nosave': print 'Saving PSF volume.' savename = filepath[:-4] + '_PSF_3D.png' # sf: scale factor vv.screenshot(savename, sf=1, bg='w')
def draw_spectrum(event): """Timer function """ spectrum = self.Spectrometer.AcquiredData() if spectrum == RETURN_FAIL: return # Display the spectrum ############### Take the log of spectrum ########## #spectrum = spectrum / float(spectrum.max()) #np.log10(spectrum, out=spectrum) ############################## ax = visvis.gca() ax.Clear() visvis.plot(self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") # Display the current temperature visvis.title("Temperature %d (C)" % self.Spectrometer.GetTemperature())
def show_results(self, what='value'): """ show_results() Show the results. """ # Get params for x param_x, values_x = self.get_series_params(1) # Get results results = self.quantify_results(what) # Plot or show try: import visvis as vv vv.figure() vv.plot(values_x, results) vv.xlabel(param_x) vv.ylabel('values') except ImportError: print('param', param_x, ': values') for x, r in zip(values_x, results): print(x, ':', r)
def ShowSpectra_by_VaryingPixelBundle (self) : """ This method is affiliated to the method <self.VaryPixelBundle> """ # Exit if the iterator is not defined try : self.pixel_bundel_value_iter except AttributeError : return try : voltage = self.pixel_bundel_value_iter.next() # Set the mask for pixel bundle width = self.SettingsNotebook.CalibrateShaper.pixel_bundle_width.GetValue() / 2 start_pixel_bundle = self.pixel_to_vary.GetValue() mask = np.copy(self.fixed_mask) if width: mask[max(start_pixel_bundle-width, 0):min(mask.size, start_pixel_bundle+width)] = voltage else: # Enforce single pixel width mask[min(max(start_pixel_bundle,0),mask.size)] = voltage self.PulseShaper.SetMasks( mask, self.fixed_mask) # Getting spectrum spectrum = self.Spectrometer.AcquiredData() # Plot the spectra visvis.gca().Clear() visvis.plot (self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") visvis.title ("Voltage %d / %d " % (voltage, self.fixed_mask[0]) ) self.fig.DrawNow() # Going to the next iteration wx.CallAfter (self.ShowSpectra_by_VaryingPixelBundle) except StopIteration : # Finish the job self.StopAllJobs()
def show_layer_boundaries(self, sample): """ Displays a 3-D rendering of boundary surfaces. :param sample: index of sample for which to plot boundaries """ app = vv.use() vv.figure(1) X = np.linspace(self.xbounds[0], self.xbounds[1], self.xres) Y = np.linspace(self.ybounds[0], self.xbounds[1], self.yres) Z = np.linspace(self.zbounds[0], self.xbounds[1], self.zres) vv.xlabel('Eastings (m)') vv.ylabel('Northings (m)') vv.zlabel('Depth (m)') a = vv.gca() a.camera.fov = 70 a.daspect = 1, 1, -1 for i in range(len(self.layers)): C = plt.cm.jet(i / float(len(self.layers))) C = np.array([[[C[0], C[1], C[2]]]]) m = vv.surf(X, Y, self.fbounds[i][sample], C) vv.ColormapEditor(a) app.Run()
def FitSpectralScans (self, scans, voltages, pixels_edges) : """ Perform fitting to the pulse shaper's mask transmission coefficient """ def FitIndividualPixel (voltages, pixel, modulation, p0=None) : """ Find fit for individual pixel with initial guess for phase function given by `modulation`. `voltages` voltage values for which `pixel` was measured `pixel` measured transmission (to be fitted) `p0` is the initial guess for fitting parametres """ def GetVM (V0, V1, m0, m1) : """ Return voltage and phase modulation from parameters """ M = m0 + m1*modulation V = np.linspace(V0, V1, M.size) return V, M def FittedTransmission (voltages, offset, amplitude, *params) : """ Return the transmission function for a shaper """ V, M = GetVM(*params) return amplitude*np.cos( pchip_interpolate(V,M,voltages) )**2 + offset # Set fitting parameters to their default values if p0 is None : p0 = [0., 1., voltages.min(), voltages.max(), 0., 1.] # Fitting the transmission try : popt, _ = curve_fit(FittedTransmission, voltages, pixel, p0=p0) except RuntimeError : popt = p0 # Get fitting error fitting_error = np.sum( ( FittedTransmission(voltages, *popt) - pixel )**2 ) return fitting_error, GetVM(*popt[2:]), popt ############################################################################ # Selecting the voltage range V_min = max( voltages_trial.min(), voltages.min() ) V_max = min( voltages_trial.max(), voltages.max() ) indx = np.nonzero( (V_min <= voltages)&(voltages <= V_max) ) # Number of calibration points lying within the voltage region num_vol_trial = np.sum( (V_min <= voltages_trial)&(voltages_trial <= V_max) ) if num_vol_trial < 2 : num_vol_trial = 2 # Re-sample modulation provided by CRi so that the voltage is equidistantly spaced resampled_vis_modulation = pchip_interpolate(voltages_trial, vis_modulation, np.linspace(V_min, V_max, min(len(voltages), num_vol_trial) ) ) resampled_nir_modulation = pchip_interpolate(voltages_trial, nir_modulation, np.linspace(V_min, V_max, min(len(voltages), num_vol_trial) ) ) # Normalizing scans scans -= scans.min(axis=0); scans /= scans.max(axis=0) # Bin the spectrum into pixels spectral_slices = map( lambda begin,end : scans[:,begin:end].mean(axis=1), pixels_edges[:-1], pixels_edges[1:] ) # List containing calibration data for each pixel calibration = [] # Initial guesses for fitting vis_p0 = None; nir_p0 = None; # Fit individual pulse shaper pixels them for pixel_num, pixel in enumerate(spectral_slices) : # Smoothing and normalizing each pixel #pixel = gaussian_filter(pixel,sigma=1) pixel -= pixel.min(); pixel /= pixel.max() # Fit the pixel by using the vis calibration curve as the initial guess vis_err, vis_calibration, vis_p0 = FitIndividualPixel(voltages[indx], pixel[indx], resampled_vis_modulation, vis_p0) # Fit the pixel by using the nir calibration curve as the initial guess nir_err, nir_calibration, nir_p0 = FitIndividualPixel(voltages[indx], pixel[indx], resampled_nir_modulation, nir_p0) # Choose the best fit if nir_err > vis_err : calibation_voltage, calibration_phase = vis_calibration fit_err = vis_err else : calibation_voltage, calibration_phase = nir_calibration fit_err = nir_err ###################### Plot ######################## visvis.clf() # Plot measured data visvis.plot( voltages, pixel, lc='r',ms='*', mc='r') # Plot fitted data plot_voltages = np.linspace( calibation_voltage.min(), calibation_voltage.max(), 500) transmission_fit = np.cos( pchip_interpolate(calibation_voltage, calibration_phase, plot_voltages) )**2 visvis.plot( plot_voltages, transmission_fit, lc='b') visvis.title ('Calibrating pixel %d / %d' % (pixel_num, len(spectral_slices)-1) ) visvis.legend(['measured', 'fitted']) visvis.xlabel ('voltages') visvis.ylabel ('Transmission coefficient') self.fig.DrawNow() ############ Save the calibration data ################## calibration.append( ( calibation_voltage, calibration_phase, fit_err ) ) return calibration
def ExtractPhaseFunc (self, event=None, filename=None) : """ This function is the last stage of calibration, when measured data is mathematically processed to obtain the calibration curves. """ # If filename is not specified, open the file dialogue if filename is None : filename = self.LoadSettings (title="Load calibration file...") # Update the name of pulse shaper calibration file import os self.SettingsNotebook.PulseShaper.SetSettings({"calibration_file_name" : os.path.abspath(filename)}) visvis.clf() # Loading the file calibration file with h5py.File(filename, 'a') as calibration_file : ############### Loading data #################### wavelengths = calibration_file["calibration_settings/wavelengths"][...] fixed_voltage = calibration_file["calibration_settings/fixed_voltage"][...] pulse_shaper_pixel_num = calibration_file["calibration_settings/pulse_shaper_pixel_num"][...] initial_pixel = calibration_file["settings/CalibrateShaper/initial_pixel"][...] final_pixel = calibration_file["settings/CalibrateShaper/final_pixel"][...] pixel_bundle_width = calibration_file["settings/CalibrateShaper/pixel_bundle_width"][...] pixel_to_lamba = str(calibration_file["settings/CalibrateShaper/pixel_to_lamba"][...]) # Convert to dict pixel_to_lamba = eval( "{%s}" % pixel_to_lamba ) # Loading scans of slave and masker masks master_mask_scans = []; slave_mask_scans = [] for key, spectrum in calibration_file["spectra_from_uniform_masks"].items() : master_volt, slave_volt = map(int, key.split('_')[-2:]) if master_volt == fixed_voltage : slave_mask_scans.append( (slave_volt, spectrum[...]) ) if slave_volt == fixed_voltage : master_mask_scans.append( (master_volt, spectrum[...]) ) # Sort by voltage master_mask_scans.sort(); slave_mask_scans.sort() # Extract spectral scans and voltages for each mask master_mask_voltage, master_mask_scans = zip(*master_mask_scans) master_mask_voltage = np.array(master_mask_voltage); master_mask_scans = np.array(master_mask_scans) slave_mask_voltage, slave_mask_scans = zip(*slave_mask_scans) slave_mask_voltage = np.array(slave_mask_voltage); slave_mask_scans = np.array(slave_mask_scans) ################### Find the edges of pixels ################# # function that converts pixel number to pulse shaper # `pixel_to_lamba` is a dictionary with key = pixel, value = lambda deg = 1 #min(1,len(pixel_to_lamba)-1) print np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), 1 ) pixel2lambda_func = np.poly1d( np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), deg=deg ) ) #lambda2pixel_func = np.poly1d( np.polyfit(pixel_to_lamba.values(), pixel_to_lamba.keys(), deg=deg ) ) # Get pixels_edges in shaper pixels pixels_edges_num = np.arange(initial_pixel, final_pixel, pixel_bundle_width) if pixels_edges_num[-1] < final_pixel : pixels_edges_num = np.append( pixels_edges_num, [final_pixel]) # Get pixels_edges in logical_pixel_lambda pixels_edges = pixel2lambda_func(pixels_edges_num) # Get pixels_edges in positions of the spectrometer spectra pixels_edges = np.abs(wavelengths - pixels_edges[:,np.newaxis]).argmin(axis=1) # Sorting indx = np.argsort(pixels_edges) pixels_edges = pixels_edges[indx] pixels_edges_num = pixels_edges_num[indx] # Plot visvis.cla(); visvis.clf() visvis.plot( pixel_to_lamba.values(), pixel_to_lamba.keys(), ls=None, ms='*', mc='g', mw=15) visvis.plot ( wavelengths[pixels_edges], pixels_edges_num, ls='-',lc='r') visvis.xlabel('wavelength (nm)') visvis.ylabel ('pulse shaper pixel') visvis.legend( ['measured', 'interpolated']) self.fig.DrawNow() ################ Perform fitting of the phase masks ################# master_mask_fits = self.FitSpectralScans( master_mask_scans, master_mask_voltage, pixels_edges ) slave_mask_fits = self.FitSpectralScans( slave_mask_scans, slave_mask_voltage, pixels_edges ) ################# Perform fitting of dispersion and phase functions ################# master_mask_TC_fitted, master_mask_scans, master_mask_disp_ph_curves = \ self.GetDispersionPhaseCurves (wavelengths, master_mask_scans, master_mask_voltage, pixels_edges, master_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num ) slave_mask_TC_fitted, slave_mask_scans, slave_mask_disp_ph_curves = \ self.GetDispersionPhaseCurves (wavelengths, slave_mask_scans, slave_mask_voltage, pixels_edges, slave_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num ) ################ Saving fitting parameters #################### ################################################################# # Save surface calibration try : del calibration_file["calibrated_surface"] except KeyError : pass CalibratedSurfaceGroupe = calibration_file.create_group("calibrated_surface") master_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group("master_mask") for key, value in master_mask_disp_ph_curves.items() : master_mask_calibrated_surface[key] = value slave_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group("slave_mask") for key, value in slave_mask_disp_ph_curves.items() : slave_mask_calibrated_surface[key] = value ################################################################# # Clear the group, if it exits try : del calibration_file["calibrated_pixels"] except KeyError : pass # This group is self consistent, thus the redundancy in saved data (with respect to other group in the file) CalibratedPixelsGroupe = calibration_file.create_group ("calibrated_pixels") CalibratedPixelsGroupe["pixels_edges"] = pixels_edges # Finding spectral bounds for each pixel pixels_spectral_bounds = zip( wavelengths[pixels_edges[:-1]], wavelengths[pixels_edges[1:]] ) # Pulse shaper pixel bounds pixels_bounds = zip(pixels_edges_num[:-1], pixels_edges_num[1:]) PixelsGroup = CalibratedPixelsGroupe.create_group("pixels") for pixel_num, master_mask_calibration, slave_mask_calibration, \ spectral_bound, pixel_bound in zip( range(len(master_mask_fits)), \ master_mask_fits, slave_mask_fits, pixels_spectral_bounds, pixels_bounds ) : pixel = PixelsGroup.create_group("pixel_%d" % pixel_num) pixel["spectral_bound"] = spectral_bound pixel["pixel_bound"] = pixel_bound # Saving fitted calibration data in the tabular form pixel["voltage_master_mask"] = master_mask_calibration[0] pixel["phase_master_mask"] = master_mask_calibration[1] pixel["voltage_slave_mask"] = slave_mask_calibration[0] pixel["phase_slave_mask"] = slave_mask_calibration[1] ################ Plotting results of calibration #################### visvis.cla(); visvis.clf(); visvis.subplot(2,2,1) visvis.imshow( master_mask_scans, cm=visvis.CM_JET ) visvis.title ("Master mask (measured data)") visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)') visvis.subplot(2,2,3) visvis.imshow( master_mask_TC_fitted, cm=visvis.CM_JET ) visvis.title ("Master mask (fitted data)") visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)') visvis.subplot(2,2,2) visvis.imshow( slave_mask_scans, cm=visvis.CM_JET ) visvis.title ("Slave mask (measured data)") visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)') visvis.subplot(2,2,4) visvis.imshow( slave_mask_TC_fitted, cm=visvis.CM_JET ) visvis.title ("Slave mask (fitted data)") visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')
ringpart = True # True; False nstruts = 8 clim0 = (0,3000) # clim0 = -550,500 clim2 = (0,4) radius = 0.07 dimensions = 'xyz' isoTh = 250 ## Visualize with GUI f = vv.figure(3); vv.clf() f.position = 968.00, 30.00, 944.00, 1002.00 a = vv.gca() show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh) model.Draw(mc='b', mw = 10, lc='g') vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') vv.title('Analysis for model LSPEAS %s - %s' % (ptcode[7:], ctcode)) a.axis.axisColor= 1,1,1 a.bgcolor= 0,0,0 a.daspect= 1, 1, -1 # z-axis flipped a.axis.visible = showAxis # Initialize labels GUI from visvis import Pointset from stentseg.stentdirect import stentgraph t1 = vv.Label(a, 'Edge ctvalue: ', fontSize=11, color='c') t1.position = 0.1, 5, 0.5, 20 # x (frac w), y, w (frac), h t1.bgcolor = None t1.visible = False t2 = vv.Label(a, 'Edge cost: ', fontSize=11, color='c')
def AnalyzeTotalFluorescence(self, event=None): """ `analyse_button` was clicked """ # Get current settings settings = self.GetSettings() # Apply peak finding filter signal = self.peak_finders[settings["peak_finder"]]( self.total_fluorescence) # Scale to (0,1) signal -= signal.min() signal = signal / signal.max() ########################################################################## # Partition signal into segments that are above the background noise #signal = gaussian_filter(total_fluorescence, sigma=0.5) background_cutoff = settings["background_cutoff"] segments = [[]] for num, is_segment in enumerate(signal > background_cutoff): if is_segment: # this index is in the segment segments[-1].append(num) elif len(segments[-1] ): # this condition is not to add empty segments # Start new segments segments.append([]) # Find peaks as weighted average of the segment peaks = [ np.average(self.positions[S], weights=self.total_fluorescence[S]) for S in segments if len(S) ] ########################################################################## # Saving the positions self.chanel_positions_ctrl.SetValue(", ".join("%2.4f" % p for p in peaks)) ########################################################################## # Plot acquired data visvis.cla() visvis.clf() visvis.plot(self.positions, signal) visvis.plot(peaks, background_cutoff * np.ones(len(peaks)), ls=None, ms='+', mc='r', mw=20) visvis.plot( [self.positions.min(), self.positions.max()], [background_cutoff, background_cutoff], lc='r', ls='--', ms=None) visvis.legend(["measured signal", "peaks found", "background cut-off"]) visvis.ylabel("total fluorescence") visvis.xlabel('position (mm)')
def DoScannning (self, event) : """ Perform scanning of different phase mask """ # Create pseudonyms of necessary devices self.DevSpectrometer = self.parent.Spectrometer.dev self.DevPulseShaper = self.parent.PulseShaper.dev self.DevSampleSwitcher = self.parent.SampleSwitcher.dev # Save global settings and get the name of log file self.log_filename = SaveSettings(SettingsNotebook=self.parent, title="Select file to save phase mask scanning", filename="scanning_phase_mask.hdf5") if self.log_filename is None : return ####################### Initiate devices ############################# # Initiate spectrometer settings = self.parent.Spectrometer.GetSettings() if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL : return # Initiate pulse shaper settings = self.parent.PulseShaper.GetSettings() if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL : return # Get number of optimization variables self.num_pixels = self.DevPulseShaper.GetParamNumber() if self.num_pixels == RETURN_FAIL : raise RuntimeError ("Optimization cannot be started since calibration file was not loaded") # Initiate sample switcher settings = self.parent.SampleSwitcher.GetSettings() if self.DevSampleSwitcher.Initialize(settings) == RETURN_FAIL : return # Saving the name of channels odd_settings = self.GetSettings() self.channels = sorted(eval( "(%s,)" % odd_settings["channels"] )) if self.DevSampleSwitcher.GetChannelNum()-1 < max(self.channels) : raise ValueError ("Error: Some channels specified are not accessible by sample switcher.") # Check whether the background signal array is present self.CheckBackground() ##################################################################### # Get range of coefficient coeff_range = np.linspace( odd_settings["coeff_min"], odd_settings["coeff_max"], odd_settings["coeff_num"] ) # List all polynomial coefficients N = odd_settings["polynomial_order"] poly_coeffs = np.zeros( (coeff_range.size*N, N+1) ) for n in range(1,N+1) : poly_coeffs[(n-1)*coeff_range.size:n*coeff_range.size, n ] = coeff_range # Chose max amplitude max_ampl = odd_settings["max_ampl"]*np.ones(self.num_pixels) # Arguments of the basis X = np.linspace(-1., 1., self.num_pixels) # Retrieve the basis type polynomial_basis = self.polynomial_bases[ odd_settings["polynomial_basis"] ] # Adjusting button's settings button = event.GetEventObject() button.SetLabel (button._stop_label) button.SetBackgroundColour('red') button.Bind( wx.EVT_BUTTON, button._stop_method) self.need_abort = False ##################################################################### # Start scanning with h5py.File (self.log_filename, 'a') as log_file : for channel in self.channels : # Move to a selected channel self.DevSampleSwitcher.MoveToChannel(channel) # abort, if requested wx.Yield() if self.need_abort : break # Looping over pulse shapes for scan_num, coeff in enumerate(poly_coeffs) : # Calculate new phase phase = polynomial_basis(coeff)(X) # Set the pulse shape self.DevPulseShaper.SetAmplPhase(max_ampl, phase) # Save phase in radians ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase(max_ampl, phase) if scan_num == 0 : # Initialize the array phases_rad = np.zeros( (len(poly_coeffs), phase.size), dtype=phase.dtype ) amplitudes = np.zeros_like(phases_rad) amplitudes[:] = ampl.min() # Save phase phases_rad[scan_num] = phase amplitudes[scan_num] = ampl # abort, if requested wx.Yield() if self.need_abort : break # Get spectrum spectrum = self.GetSampleSpectrum(channel) # Vertical binning spectrum = ( spectrum.sum(axis=0) if len(spectrum.shape) == 2 else spectrum ) if scan_num == 0 : # Initialize the array spectra = np.zeros( (len(poly_coeffs), spectrum.size), dtype=spectrum.dtype ) spectra[:] = spectrum.min() # Save the spectrum spectra[scan_num] = spectrum # Display the currently acquired data try : spectra_2d_img.SetData(spectra) phases_rad_2d_img.SetData( phases_rad%(2*np.pi) ) #amplitudes_2d_img.SetData( amplitudes ) except NameError : visvis.cla(); visvis.clf() visvis.subplot(121) spectra_2d_img = visvis.imshow(spectra, cm=visvis.CM_JET) visvis.ylabel ('scans'); visvis.xlabel ('wavelegth') visvis.title("spectral scan") visvis.subplot(122) phases_rad_2d_img = visvis.imshow( phases_rad%(2*np.pi), cm=visvis.CM_JET) visvis.title("phase shapes") #visvis.subplot(133) #amplitudes_2d_img = visvis.imshow(amplitudes, cm=visvis.CM_JET) #visvis.title("amplitudes") # Save the data for the given channel try : del log_file[ str(channel) ] except KeyError : pass channel_grp = log_file.create_group( str(channel) ) channel_grp["spectra"] = spectra channel_grp["phases_rad"] = phases_rad channel_grp["amplitudes"] = amplitudes channel_grp["poly_coeffs"] = poly_coeffs # Readjust buttons settings self.StopScannning(event)
vv.plot([e[0] for e in c1_ends], [e[1] for e in c1_ends], [e[2] for e in c1_ends], ms='.', ls='', mc='b', mw=18, axes=a1) # ends vv.plot(centerline1, ms='.', ls='', mw=8, mc='y', axes=a1) vv.plot(renal1, ms='.', ls='', mc='m', mw=18, axes=a1) vv.plot(renal1_and_cl_point, ms='.', ls='-', mc='m', mw=18, axes=a1) # vv.plot(R1_left_and_cl_point, ms='.', ls='-', mc='c', mw=18, axes = a1) # vv.plot(R1_right_and_cl_point, ms='.', ls='-', mc='c', mw=18, axes = a1) # vv.plot(R1_ant_and_cl_point, ms='.', ls='-', mc='c', mw=18, axes = a1) # vv.plot(R1_post_and_cl_point, ms='.', ls='-', mc='c', mw=18, axes = a1) vv.xlabel('x (mm)') vv.ylabel('y (mm)') vv.zlabel('z (mm)') vv.title('Analysis for model LSPEAS %s - %s' % (ptcode[7:], ctcode1)) a1.axis.axisColor = 1, 1, 1 a1.bgcolor = 0, 0, 0 a1.daspect = 1, 1, -1 # z-axis flipped a1.axis.visible = showAxis if ctcode2: a2 = vv.subplot(122) show_ctvolume(vol2, model2, showVol=showVol, clim=clim0, isoTh=isoTh) pick3d(vv.gca(), vol2) model2.Draw(mc='b', mw=10, lc='g') vm = vv.mesh(modelmesh2) vm.faceColor = 'g'
def demo(*args, **kwargs): import math m = 80 # width of grid n = m ** 2 # number of points minVal = -2.0 maxVal = 2.0 delta = (maxVal - minVal) / (m - 1) X, Y = numpy.mgrid[minVal:maxVal + delta:delta, minVal:maxVal + delta:delta] X = X.flatten() Y = Y.flatten() Z = numpy.sin(X) * numpy.cos(Y) # Create the data point-matrix M = numpy.array([X, Y, Z]).T # Translation values (a.u.): Tx = 0.5 Ty = -0.3 Tz = 0.2 # Translation vector T = numpyTransform.translation(Tx, Ty, Tz) S = numpyTransform.scaling(1.0, N=4) # Rotation values (rad.): rx = 0.3 ry = -0.2 rz = 0.05 Rx = numpy.matrix([[1, 0, 0, 0], [0, math.cos(rx), -math.sin(rx), 0], [0, math.sin(rx), math.cos(rx), 0], [0, 0, 0, 1]]) Ry = numpy.matrix([[math.cos(ry), 0, math.sin(ry), 0], [0, 1, 0, 0], [-math.sin(ry), 0, math.cos(ry), 0], [0, 0, 0, 1]]) Rz = numpy.matrix([[math.cos(rz), -math.sin(rz), 0, 0], [math.sin(rz), math.cos(rz), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) # Rotation matrix R = Rx * Ry * Rz transformMat = numpy.matrix(numpy.identity(4)) transformMat *= T transformMat *= R transformMat *= S # Transform data-matrix plus noise into model-matrix D = numpyTransform.transformPoints(transformMat, M) # Add noise to model and data M = M + 0.01 * numpy.random.randn(n, 3) D = D + 0.01 * numpy.random.randn(n, 3) # Run ICP (standard settings) initialGuess = numpy.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) lowerBounds = numpy.array([-pi, -pi, -pi, -100.0, -100.0, -100.0]) upperBounds = numpy.array([pi, pi, pi, 100.0, 100.0, 100.0]) icp = ICP(M, D, maxIterations=15, dataDownsampleFactor=1, minimizeMethod='fmincon', **kwargs) # icp = ICP(M, D, maxIterations=15, dataDownsampleFactor=1, minimizeMethod='point', **kwargs) transform, err, t = icp.runICP(x0=initialGuess, lb=lowerBounds, ub=upperBounds) # Transform data-matrix using ICP result Dicp = numpyTransform.transformPoints(transform[-1], D) # Plot model points blue and transformed points red if False: import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(2, 2, 1, projection='3d') ax.scatter(M[:, 0], M[:, 1], M[:, 2], c='r', marker='o') ax.scatter(D[:, 0], D[:, 1], D[:, 2], c='b', marker='^') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') ax = fig.add_subplot(2, 2, 2, projection='3d') ax.scatter(M[:, 0], M[:, 1], M[:, 2], c='r', marker='o') ax.scatter(Dicp[:, 0], Dicp[:, 1], Dicp[:, 2], c='b', marker='^') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') ax = fig.add_subplot(2, 2, 3) ax.plot(t, err, 'x--') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') plt.show() else: import visvis as vv app = vv.use() vv.figure() vv.subplot(2, 2, 1) vv.plot(M[:, 0], M[:, 1], M[:, 2], lc='b', ls='', ms='o') vv.plot(D[:, 0], D[:, 1], D[:, 2], lc='r', ls='', ms='x') vv.xlabel('[0,0,1] axis') vv.ylabel('[0,1,0] axis') vv.zlabel('[1,0,0] axis') vv.title('Red: z=sin(x)*cos(y), blue: transformed point cloud') # Plot the results vv.subplot(2, 2, 2) vv.plot(M[:, 0], M[:, 1], M[:, 2], lc='b', ls='', ms='o') vv.plot(Dicp[:, 0], Dicp[:, 1], Dicp[:, 2], lc='r', ls='', ms='x') vv.xlabel('[0,0,1] axis') vv.ylabel('[0,1,0] axis') vv.zlabel('[1,0,0] axis') vv.title('ICP result') # Plot RMS curve vv.subplot(2, 2, 3) vv.plot(t, err, ls='--', ms='x') vv.xlabel('time [s]') vv.ylabel('d_{RMS}') vv.title('KD-Tree matching') if 'optAlg' in kwargs: opt2 = nlopt.opt(kwargs['optAlg'], 2) vv.title(opt2.get_algorithm_name()) del opt2 else: vv.title('KD-Tree matching') app.Run()
def __init__(self,ptcode,ctcode,basedir, seed_th=[600], show=True, normalize=False, modelname='model'): import os import numpy as np import visvis as vv from visvis import ssdf from stentseg.utils import PointSet, _utils_GUI from stentseg.utils.datahandling import select_dir, loadvol, loadmodel from stentseg.stentdirect.stentgraph import create_mesh from stentseg.stentdirect import stentgraph, StentDirect, getDefaultParams from stentseg.stentdirect import AnacondaDirect, EndurantDirect, NellixDirect from stentseg.utils.visualization import show_ctvolume from stentseg.utils.picker import pick3d, label2worldcoordinates, label2volindices import scipy from scipy import ndimage import copy # Select dataset to register cropname = 'prox' # phase = 10 #dataset = 'avgreg' #what = str(phase) + dataset # avgreg what = 'avgreg' # Load volumes s = loadvol(basedir, ptcode, ctcode, cropname, what) # sampling was not properly stored after registration for all cases: reset sampling vol_org = copy.deepcopy(s.vol) s.vol.sampling = [vol_org.sampling[1], vol_org.sampling[1], vol_org.sampling[2]] # z,y,x s.sampling = s.vol.sampling vol = s.vol ## Initialize segmentation parameters stentType = 'nellix' # 'zenith';'nellix' runs modified pruning algorithm in Step3 p = getDefaultParams(stentType) p.seed_threshold = seed_th # step 1 [lower th] or [lower th, higher th] # p.seedSampleRate = 7 # step 1, nellix p.whatphase = what ## Perform segmentation # Instantiate stentdirect segmenter object if stentType == 'anacondaRing': sd = AnacondaDirect(vol, p) # inherit _Step3_iter from AnacondaDirect class #runtime warning using anacondadirect due to mesh creation, ignore elif stentType == 'endurant': sd = EndurantDirect(vol, p) elif stentType == 'nellix': sd = NellixDirect(vol, p) else: sd = StentDirect(vol, p) ## show histogram and normalize # f = vv.figure(3) # a = vv.gca() # vv.hist(vol, drange=(300,vol.max())) # normalize vol to certain limit if normalize: sd.Step0(3071) vol = sd._vol # b= vv.hist(vol, drange=(300,3071)) # b.color = (1,0,0) ## Perform step 1 for seeds sd.Step1() ## Visualize if show: fig = vv.figure(2); vv.clf() fig.position = 0.00, 22.00, 1920.00, 1018.00 clim = (0,2000) # Show volume and model as graph a1 = vv.subplot(121) a1.daspect = 1,1,-1 # t = vv.volshow(vol, clim=clim) t = show_ctvolume(vol, axis=a1, showVol='MIP', clim =clim, isoTh=250, removeStent=False, climEditor=True) label = pick3d(vv.gca(), vol) sd._nodes1.Draw(mc='b', mw = 2) # draw seeded nodes #sd._nodes2.Draw(mc='b', lc = 'g') # draw seeded and MCP connected nodes vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') # Show volume and cleaned up graph a2 = vv.subplot(122) a2.daspect = 1,1,-1 sd._nodes1.Draw(mc='b', mw = 2) # draw seeded nodes # t = vv.volshow(vol, clim=clim) # label = pick3d(vv.gca(), vol) # sd._nodes2.Draw(mc='b', lc='g') # sd._nodes3.Draw(mc='b', lc='g') vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') # # Show the mesh #=============================================================================== # a3 = vv.subplot(133) # a3.daspect = 1,1,-1 # t = vv.volshow(vol, clim=clim) # pick3d(vv.gca(), vol) # #sd._nodes3.Draw(mc='b', lc='g') # m = vv.mesh(bm) # m.faceColor = 'g' # # _utils_GUI.vis_spared_edges(sd._nodes3) # vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') #=============================================================================== # Use same camera a1.camera = a2.camera #= a3.camera switch = True a1.axis.visible = switch a2.axis.visible = switch #a3.axis.visible = switch ## Store segmentation to disk # Get graph model model = sd._nodes1 # Build struct s2 = vv.ssdf.new() s2.sampling = s.sampling s2.origin = s.origin s2.stenttype = s.stenttype s2.croprange = s.croprange for key in dir(s): if key.startswith('meta'): suffix = key[4:] s2['meta'+suffix] = s['meta'+suffix] s2.what = what s2.params = p s2.stentType = stentType # Store model (not also volume) s2.model = model.pack() # Save filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, modelname+ what) ssdf.save(os.path.join(basedir, ptcode, filename), s2) print('saved to disk as {}.'.format(filename) ) ## Make model dynamic (and store/overwrite to disk) #=============================================================================== # # import pirt # from stentsegf.motion.dynamic import incorporate_motion_nodes, incorporate_motion_edges # # # Load deforms # s = loadvol(basedir, ptcode, ctcode, cropname, '10deforms') # deformkeys = [] # for key in dir(s): # if key.startswith('deform'): # deformkeys.append(key) # deforms = [s[key] for key in deformkeys] # deforms = [pirt.DeformationFieldBackward(*fields) for fields in deforms] # paramsreg = s.params # # # Load model # s = loadmodel(basedir, ptcode, ctcode, cropname, 'model'+what) # model = s.model # # # Combine ... # incorporate_motion_nodes(model, deforms, s.origin) # incorporate_motion_edges(model, deforms, s.origin) # # # Save back # filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'model'+what) # s.model = model.pack() # s.paramsreg = paramsreg # ssdf.save(os.path.join(basedir, ptcode, filename), s) # print('saved to disk as {}.'.format(filename) ) #===============================================================================
def DoScannning (self, event) : """ Perform scanning of different phase mask """ # Create pseudonyms of necessary devices self.DevSpectrometer = self.parent.Spectrometer.dev self.DevPulseShaper = self.parent.PulseShaper.dev self.DevSampleSwitcher = self.parent.SampleSwitcher.dev self.DevFilterWheel = self.parent.FilterWheel.dev # Save global settings and get the name of log file self.log_filename = SaveSettings(SettingsNotebook=self.parent, title="Select file to save phase mask scanning", filename="scanning_phase_mask.hdf5") if self.log_filename is None : return ####################### Initiate devices ############################# # Initiate spectrometer settings = self.parent.Spectrometer.GetSettings() if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL : return # Initiate pulse shaper settings = self.parent.PulseShaper.GetSettings() if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL : return # Get number of optimization variables self.num_pixels = self.DevPulseShaper.GetParamNumber() if self.num_pixels == RETURN_FAIL : raise RuntimeError ("Optimization cannot be started since calibration file was not loaded") # Initiate sample switcher settings = self.parent.SampleSwitcher.GetSettings() if self.DevSampleSwitcher.Initialize(settings) == RETURN_FAIL : return # Initialize the filter wheel settings = self.parent.FilterWheel.GetSettings() if self.DevFilterWheel.Initialize(settings) == RETURN_FAIL : return # Saving the name of channels settings = self.GetSettings() self.channels = sorted( eval( "(%s,)" % settings["channels"] ) ) if self.DevSampleSwitcher.GetChannelNum()-1 < max(self.channels) : raise ValueError ("Error: Some channels specified are not accessible by sample switcher.") # Saving the name of filter self.filters = sorted( eval( "(%s,)" % settings["filters"] ) ) if self.DevFilterWheel.GetNumFilters() < max(self.filters) : raise ValueError ("Error: Some filters specified are not accessible by filter wheel.") # Check whether the background signal array is present self.CheckBackground() ##################################################################### # Get range of coefficient coeff_range = np.linspace( settings["coeff_min"], settings["coeff_max"], settings["coeff_num"] ) min_N = settings["min_polynomial_order"] max_N = settings["max_polynomial_order"] # Create all polynomial coefficients for scanning coeff_iter = product( *chain(repeat([0], min_N), repeat(coeff_range, max_N+1-min_N)) ) poly_coeffs = np.array( list(coeff_iter) ) # Chose max amplitude max_ampl = settings["max_ampl"]*np.ones(self.num_pixels) # Arguments of the basis X = np.linspace(-1., 1., self.num_pixels) # Retrieve the basis type polynomial_basis = self.polynomial_bases[ settings["polynomial_basis"] ] # Adjusting button's settings button = event.GetEventObject() button.SetLabel (button._stop_label) button.SetBackgroundColour('red') button.Bind( wx.EVT_BUTTON, button._stop_method) self.need_abort = False ##################################################################### # Start scanning with h5py.File (self.log_filename, 'a') as log_file : # Allocate memory for fluorescence signal of all proteins fluorescences = dict( (key, np.zeros(len(poly_coeffs), dtype=np.int)) for key in product(self.channels, self.filters) ) # Allocate memory for reference fluoresence ref_fluorescences = dict( (C, []) for C in self.channels ) # Iterator for polynomial coefficients poly_coeffs_iter = enumerate(poly_coeffs) while True : # Chunk up the data chunk_poly_coeffs = list( islice(poly_coeffs_iter, len(coeff_range)) ) # about, if there is nothing to iterate over if len(chunk_poly_coeffs) == 0 : break # abort, if requested if self.need_abort : break for channel in self.channels : # Move to a selected channel self.DevSampleSwitcher.MoveToChannel(channel) # abort, if requested if self.need_abort : break # Looping over pulse shapes for scan_num, coeff in chunk_poly_coeffs : # Calculate new phase phase = polynomial_basis(coeff)(X) # Set the pulse shape self.DevPulseShaper.SetAmplPhase(max_ampl, phase) # abort, if requested if self.need_abort : break # Looping over filters in filter wheels for filter in self.filters : self.DevFilterWheel.SetFilter(filter) # abort, if requested wx.Yield() if self.need_abort : break # Get spectrum sum, i.e., fluorescence spectrum_sum = self.GetSampleSpectrum(channel).sum() # Save the spectrum fluorescences[ (channel, filter) ][scan_num] = spectrum_sum # Record reference fluorescence self.DevPulseShaper.SetAmplPhase(max_ampl, np.zeros_like(max_ampl)) # Go to filters with max transmission (ASSUMING that it has lowest number) self.DevFilterWheel.SetFilter( min(self.filters) ) spectrum_sum = self.GetSampleSpectrum(channel).sum() ref_fluorescences[channel].append( spectrum_sum ) # Display the currently acquired data try : for key, img in fluorescence_imgs.items() : img.SetYdata( fluorescences[key] ) except NameError : visvis.cla(); visvis.clf() # Iterator of colours colour_iter = cycle(['r', 'g', 'b', 'k', 'y']) fluorescence_imgs = dict( (K, visvis.plot( F, lw=1, lc=colour_iter.next() ) ) for K, F in fluorescences.items() ) visvis.xlabel("phase masks") visvis.ylabel("Integrated fluorescence") visvis.title("Measured fluorescence") ################ Scanning is over, save the data ######################## # Delete and create groups corresponding to channel for channel in self.channels : try : del log_file[ "channel_%d" % channel ] except KeyError : pass gchannel_grp = log_file.create_group( "channel_%d" % channel ) gchannel_grp["ref_fluorescence"] = ref_fluorescences[channel] gchannel_grp["poly_coeffs"] = poly_coeffs for channel_filter, fluorescence in fluorescences.items() : log_file["channel_%d/filter_%d_fluorescence" % channel_filter ] = fluorescence # Readjust buttons settings self.StopScannning(event)
'r': [(0.0, 0.0), (0.17727272, 1.0)], 'g': [(0.0, 0.0), (0.27272728, 1.0)], 'b': [(0.0, 0.0), (0.34545454, 1.0)], 'a': [(0.0, 1.0), (1.0, 1.0)] } import visvis as vv fig = vv.figure(1) vv.clf() fig.position = 0, 22, 1366, 706 a1 = vv.subplot(121) t1 = vv.volshow(vol1, clim=(0, 3000), renderStyle='iso') # iso or mip t1.isoThreshold = 400 t1.colormap = colormap a1b = vv.volshow2(vol1, clim=(-550, 500)) vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') # vv.title('One volume at %i procent of cardiac cycle' % phase ) vv.title('Vol40') a2 = vv.subplot(122) a2.daspect = 1, 1, -1 t2 = vv.volshow(vol2, clim=(0, 3000), renderStyle='iso') # iso or mip t2.isoThreshold = 400 t2.colormap = colormap a2b = vv.volshow2(vol2, clim=(-550, 500)) vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') # vv.title('One volume at %i procent of cardiac cycle' % phase ) vv.title('Vol78') a1.camera = a2.camera
## Plot for paper, example import os from stentseg.utils.datahandling import select_dir import matplotlib.pyplot as plt import matplotlib as mpl import prettyplotlib as ppl f = vv.figure() f.position = 0, 22, 1077, 273 # B1 (A=0.6, T=0.8, N=20, top=0.35) ax1 = vv.subplot(121) #; vv.title('profile1') plot_pattern(*(tt1, aa1)) ax1.axis.showGrid = False ax1.axis.showBox = False ax1.SetLimits(rangeX=(-0.01, 2), rangeY=(-0.02, 2.5)) vv.xlabel('time (s)') vv.ylabel('position (mm)') vv.legend('B1 (A=0.6, T=0.8)') # B5 (A=2.0, T=0.8, N=20, top=0.35, extra=(0.7, 0.8, 0.05)) ax5 = vv.subplot(122) #; vv.title('profile5') plot_pattern(*(tt5, aa5)) ax5.axis.showGrid = False ax5.SetLimits(rangeX=(-0.01, 2), rangeY=(-0.02, 2.5)) ax5.axis.showBox = False vv.xlabel('time (s)') vv.ylabel('position (mm)') vv.legend('B5 (A=2.0, T=0.8, extra=0.7, 0.8, 0.05)') f.relativeFontSize = 1.2 if False:
import visvis as vv def zlabel(text, axes=None): """ zlabel(text, axes=None) Set the zlabel of an axes. Note that you can also use "axes.axis.zLabel = text". Parameters ---------- text : string The text to display. axes : Axes instance Display the image in this axes, or the current axes if not given. """ if axes is None: axes = vv.gca() axes.axis.zLabel = text if __name__=='__main__': # Create a 3D plot a = vv.gca() vv.plot([1,2,3],[1,3,2],[3,1,2]) a.cameraType = '3d' # Set labels for all 3 dimensions vv.xlabel('label x') vv.ylabel('label y') vv.zlabel('label z')
def zlabel(text, axes=None): """ zlabel(text, axes=None) Set the zlabel of an axes. Note that you can also use "axes.axis.zLabel = text". Parameters ---------- text : string The text to display. axes : Axes instance Display the image in this axes, or the current axes if not given. """ if axes is None: axes = vv.gca() axes.axis.zLabel = text if __name__ == '__main__': # Create a 3D plot a = vv.gca() vv.plot([1, 2, 3], [1, 3, 2], [3, 1, 2]) a.cameraType = '3d' # Set labels for all 3 dimensions vv.xlabel('label x') vv.ylabel('label y') vv.zlabel('label z')
def DoScannning(self, event): """ Perform scanning of different phase mask """ # Create pseudonyms of necessary devices self.DevSpectrometer = self.parent.Spectrometer.dev self.DevPulseShaper = self.parent.PulseShaper.dev self.DevSampleSwitcher = self.parent.SampleSwitcher.dev self.DevFilterWheel = self.parent.FilterWheel.dev # Save global settings and get the name of log file self.log_filename = SaveSettings( SettingsNotebook=self.parent, title="Select file to save phase mask scanning", filename="scanning_phase_mask.hdf5") if self.log_filename is None: return ####################### Initiate devices ############################# # Initiate spectrometer settings = self.parent.Spectrometer.GetSettings() if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL: return # Initiate pulse shaper settings = self.parent.PulseShaper.GetSettings() if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL: return # Get number of optimization variables self.num_pixels = self.DevPulseShaper.GetParamNumber() if self.num_pixels == RETURN_FAIL: raise RuntimeError( "Optimization cannot be started since calibration file was not loaded" ) # Initiate sample switcher settings = self.parent.SampleSwitcher.GetSettings() if self.DevSampleSwitcher.Initialize(settings) == RETURN_FAIL: return # Initialize the filter wheel settings = self.parent.FilterWheel.GetSettings() if self.DevFilterWheel.Initialize(settings) == RETURN_FAIL: return # Saving the name of channels settings = self.GetSettings() self.channels = sorted(eval("(%s,)" % settings["channels"])) if self.DevSampleSwitcher.GetChannelNum() - 1 < max(self.channels): raise ValueError( "Error: Some channels specified are not accessible by sample switcher." ) # Saving the name of filter self.filters = sorted(eval("(%s,)" % settings["filters"])) if self.DevFilterWheel.GetNumFilters() < max(self.filters): raise ValueError( "Error: Some filters specified are not accessible by filter wheel." ) # Check whether the background signal array is present self.CheckBackground() ##################################################################### # Get range of coefficient coeff_range = np.linspace(settings["coeff_min"], settings["coeff_max"], settings["coeff_num"]) min_N = settings["min_polynomial_order"] max_N = settings["max_polynomial_order"] # Create all polynomial coefficients for scanning coeff_iter = product( *chain(repeat([0], min_N), repeat(coeff_range, max_N + 1 - min_N))) poly_coeffs = np.array(list(coeff_iter)) # Chose max amplitude max_ampl = settings["max_ampl"] * np.ones(self.num_pixels) # Arguments of the basis X = np.linspace(-1., 1., self.num_pixels) # Retrieve the basis type polynomial_basis = self.polynomial_bases[settings["polynomial_basis"]] # Adjusting button's settings button = event.GetEventObject() button.SetLabel(button._stop_label) button.SetBackgroundColour('red') button.Bind(wx.EVT_BUTTON, button._stop_method) self.need_abort = False ##################################################################### # Start scanning with h5py.File(self.log_filename, 'a') as log_file: # Allocate memory for fluorescence signal of all proteins fluorescences = dict( (key, np.zeros(len(poly_coeffs), dtype=np.int)) for key in product(self.channels, self.filters)) # Allocate memory for reference fluoresence ref_fluorescences = dict((C, []) for C in self.channels) # Iterator for polynomial coefficients poly_coeffs_iter = enumerate(poly_coeffs) while True: # Chunk up the data chunk_poly_coeffs = list( islice(poly_coeffs_iter, len(coeff_range))) # about, if there is nothing to iterate over if len(chunk_poly_coeffs) == 0: break # abort, if requested if self.need_abort: break for channel in self.channels: # Move to a selected channel self.DevSampleSwitcher.MoveToChannel(channel) # abort, if requested if self.need_abort: break # Looping over pulse shapes for scan_num, coeff in chunk_poly_coeffs: # Calculate new phase phase = polynomial_basis(coeff)(X) # Set the pulse shape self.DevPulseShaper.SetAmplPhase(max_ampl, phase) # abort, if requested if self.need_abort: break # Looping over filters in filter wheels for filter in self.filters: self.DevFilterWheel.SetFilter(filter) # abort, if requested wx.Yield() if self.need_abort: break # Get spectrum sum, i.e., fluorescence spectrum_sum = self.GetSampleSpectrum( channel).sum() # Save the spectrum fluorescences[(channel, filter)][scan_num] = spectrum_sum # Record reference fluorescence self.DevPulseShaper.SetAmplPhase(max_ampl, np.zeros_like(max_ampl)) # Go to filters with max transmission (ASSUMING that it has lowest number) self.DevFilterWheel.SetFilter(min(self.filters)) spectrum_sum = self.GetSampleSpectrum(channel).sum() ref_fluorescences[channel].append(spectrum_sum) # Display the currently acquired data try: for key, img in fluorescence_imgs.items(): img.SetYdata(fluorescences[key]) except NameError: visvis.cla() visvis.clf() # Iterator of colours colour_iter = cycle(['r', 'g', 'b', 'k', 'y']) fluorescence_imgs = dict( (K, visvis.plot(F, lw=1, lc=colour_iter.next())) for K, F in fluorescences.items()) visvis.xlabel("phase masks") visvis.ylabel("Integrated fluorescence") visvis.title("Measured fluorescence") ################ Scanning is over, save the data ######################## # Delete and create groups corresponding to channel for channel in self.channels: try: del log_file["channel_%d" % channel] except KeyError: pass gchannel_grp = log_file.create_group("channel_%d" % channel) gchannel_grp["ref_fluorescence"] = ref_fluorescences[channel] gchannel_grp["poly_coeffs"] = poly_coeffs for channel_filter, fluorescence in fluorescences.items(): log_file["channel_%d/filter_%d_fluorescence" % channel_filter] = fluorescence # Readjust buttons settings self.StopScannning(event)
# calculate B field at given points B = sol.CalculateB(points=points) Babs = np.linalg.norm(B, axis=1) # draw results # prepare axes a = vv.gca() a.cameraType = '3d' a.daspectAuto = False vol = Babs.reshape(grid.shape[1:]).T vol = np.clip(vol, 0.002, 0.01) vol = vv.Aarray(vol, sampling=(resolution, resolution, resolution), origin=(volume_corner1[2], volume_corner1[1], volume_corner1[0])) # set labels vv.xlabel('x axis') vv.ylabel('y axis') vv.zlabel('z axis') sol.vv_PlotWires() t = vv.volshow2(vol, renderStyle='mip', cm=vv.CM_JET) vv.colorbar() app = vv.use() app.Run()
# -*- coding: utf-8 -*- # Copyright (C) 2012, Almar Klein # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import visvis as vv def xlabel(text, axes=None): """ xlabel(text, axes=None) Set the xlabel of an axes. Note that you can also use "axes.axis.xLabel = text". Parameters ---------- text : string The text to display. axes : Axes instance Display the image in this axes, or the current axes if not given. """ if axes is None: axes = vv.gca() axes.axis.xLabel = text if __name__=='__main__': a = vv.gca() a.cameraType = '2d' vv.xlabel('label test')
# # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import visvis as vv def xlabel(text, axes=None): """ xlabel(text, axes=None) Set the xlabel of an axes. Note that you can also use "axes.axis.xLabel = text". Parameters ---------- text : string The text to display. axes : Axes instance Display the image in this axes, or the current axes if not given. """ if axes is None: axes = vv.gca() axes.axis.xLabel = text if __name__ == '__main__': a = vv.gca() a.cameraType = '2d' vv.xlabel('label test')
print( "FPS : %.2f (%d frames in %.2f second)" % (frames/elapsed, frames, elapsed)) t0, frames = t,0 event.source.update() # Run! app.run() if False: ## Evaluate measurements # Measured ncolrow = [6, 7, 8, 9, 10, 11, 12] fpss = [48, 37, 28, 23, 18, 15, 12] # Measured earlier fpss = [32, 24, 19, 15, 12, 10, 8] # Measured later, probably added extra overhead # Process xx = [x**2 for x in ncolrow] yy = [1.0 / fps for fps in fpss] timepersubplot = [1000*y/x for x, y in zip(xx, yy)] # Show import visvis as vv vv.figure(1); vv.clf() vv.plot(xx, yy) vv.xlabel('number of subplots') vv.ylabel('timer per frame') # vv.figure(2); vv.clf() vv.plot(timepersubplot) vv.gca().SetLimits(rangeY=(0, 1.1*max(timepersubplot)))
import sys import time import visvis as vv import numpy as np import cPickle as pickle import gzip f=gzip.open(sys.argv[1],"rb") data=pickle.load(f) #!/usr/bin/env python app = vv.use() vv.clf() # set labels vv.xlabel('x axis') vv.ylabel('y axis') vv.zlabel('z axis') # show print np.sum(data) t = vv.volshow(data,renderStyle='iso',axesAdjust=True) #t.isoThreshold = 0.5 # try the differtent render styles, for examample # "t.renderStyle='iso'" or "t.renderStyle='ray'" # If the drawing hangs, your video drived decided to render in software mode. # This is unfortunately (as far as I know) not possible to detect. # It might help if your data is shaped a power of 2. # Get axes and set camera to orthographic mode (with a field of view of 70) a = vv.gcf()
def GetDeltaScan (self, event) : """ Measure spectra by varying parameter delta in reference phase mask """ # Create pseudonyms of necessary devices self.DevSpectrometer = self.parent.Spectrometer.dev self.DevPulseShaper = self.parent.PulseShaper.dev ####################### Initiate devices ############################# # Initiate spectrometer settings = self.parent.Spectrometer.GetSettings() if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL : return # Initiate pulse shaper settings = self.parent.PulseShaper.GetSettings() if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL : return # Get number of optimization variables self.num_pixels = self.DevPulseShaper.GetParamNumber() if self.num_pixels == RETURN_FAIL : raise RuntimeError ("Optimization cannot be started since calibration file was not loaded") miips_settings = self.GetSettings() ##################################################################### # Get range of coefficient coeff_range = np.linspace( miips_settings["coeff_min"], miips_settings["coeff_max"], miips_settings["coeff_num"] ) # Get reference phase based on the corrections already obtained reference_phase, X, polynomial_basis = self.GetReferencePhase(miips_settings) # Get new polynomial new_coeffs = np.zeros(miips_settings["polynomial_order"] + 1) new_coeffs[-1] = 1 current_polynomial = polynomial_basis(new_coeffs)(X) # Chose max amplitude max_ampl = miips_settings["max_ampl"]*np.ones(self.num_pixels) # Adjusting button's settings button = event.GetEventObject() button.SetLabel (button._stop_label) button.SetBackgroundColour('red') button.Bind( wx.EVT_BUTTON, button._stop_method) self.need_abort = False for scan_num, coeff in enumerate(coeff_range) : # Get current phase mask current_phase = coeff*current_polynomial current_phase += reference_phase # Check for consistency current_phase %= 1 # Set the pulse shape self.DevPulseShaper.SetAmplPhase(max_ampl, current_phase) wx.Yield() # abort, if requested if self.need_abort : break # Get spectrum spectrum = self.DevSpectrometer.AcquiredData() # Vertical binning spectrum = ( spectrum.sum(axis=0) if len(spectrum.shape) == 2 else spectrum ) try : spectral_scans except NameError : # Allocate space for spectral scans spectral_scans = np.zeros( (coeff_range.size, spectrum.size), dtype=spectrum.dtype ) # Save spectrum spectral_scans[ scan_num ] = spectrum # Display the currently acquired data try : spectral_scan_2d_img.SetData(spectral_scans) except NameError : visvis.cla(); visvis.clf(); spectral_scan_2d_img = visvis.imshow(spectral_scans, cm=visvis.CM_JET) visvis.ylabel ('coefficeints') visvis.xlabel ('wavelegth') ####################################################### # Get current wavelength wavelength = self.DevSpectrometer.GetWavelengths() # Adding the scan to log self.scan_log.append( { "spectral_scans" : spectral_scans, "reference_phase" : reference_phase, "current_polynomial": current_polynomial, "coeff_range" : coeff_range, "wavelength" : wavelength } ) # Plotting fit visvis.cla(); visvis.clf(); ################ Find the value of coeff such that it maximizes the total intensity of SHG # Method 1: use polynomial filter # Ignored not scanned parameter spectral_sum = spectral_scans.sum(axis=1) indx = np.nonzero(spectral_sum > 0) # Fit the total spectral intensity with chosen polynomials spectral_sum_fit = polynomial_basis.fit(coeff_range[indx], spectral_sum[indx] , 10) # Find extrema of the polynomial fit opt_coeff = spectral_sum_fit.deriv().roots() # Find maximum fit_max_sum_val = opt_coeff[ np.argmax(spectral_sum_fit(opt_coeff)) ].real print "\n\nOptimal value of the coefficient (using the polynomial fit) is ", fit_max_sum_val # Method 2: Use Gaussian filter # Smoothing spectral scans filtered_spectral_scans = gaussian_filter(spectral_scans, (2, 0.5) ) gauss_max_sum_val = coeff_range[ np.argmax(filtered_spectral_scans.sum(axis=1)) ] print "\nOptimal value of the coefficient (using the Gaussian filter) is ", gauss_max_sum_val # If the difference between methods is great then use the Gaussian filter if abs(gauss_max_sum_val - fit_max_sum_val)/np.abs([gauss_max_sum_val, fit_max_sum_val]).max() > 0.3 : max_sum_val = gauss_max_sum_val else : max_sum_val = fit_max_sum_val self.current_coeff_val.SetValue( max_sum_val ) filtered_spectral_scans[ np.searchsorted(coeff_range, max_sum_val) ][0:-1:2] = spectral_scans.min() ################ Plotting results #################### #spectral_scan_2d_img.SetData(spectral_scans) #spectral_scan_2d_img.SetClim( spectral_scans.min(), spectral_scans.max() ) visvis.subplot(121) visvis.title("Raw spectral scans") visvis.imshow(spectral_scans, cm=visvis.CM_JET) visvis.ylabel ('coefficeints'); visvis.xlabel ('wavelegth') visvis.subplot(122) visvis.title("Finding maximum") visvis.imshow(filtered_spectral_scans, cm=visvis.CM_JET) visvis.ylabel ('coefficeints'); visvis.xlabel ('wavelegth') # Readjust buttons settings self.StopScannning(event)