コード例 #1
0
	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')
コード例 #2
0
ファイル: VideoViewer.py プロジェクト: MerDane/pyKinectTools
	def _createWindow(self, name, im, axis):

		vv.figure()
		vv.gca()
		vv.clf()
		fig = vv.imshow(im)
		dims = im.shape

		''' Change color bounds '''
		if im.dtype == np.uint8:
			fig.clim.Set(0, 255)
		else:
			fig.clim.Set(0., 1.)
		
		fig.GetFigure().title = name
		
		''' Show ticks on axes? '''
		if not axis:
			fig.GetAxes().axis.visible = False
			bgcolor = (0.,0.,0.)
		else:
			fig.GetAxes().axis.showBox = False
			bgcolor = (1.,1.,1.)

		''' Set background color '''
		fig.GetFigure().bgcolor = bgcolor
		fig.GetAxes().bgcolor = bgcolor

		''' Setup keyboard event handler '''
		fig.eventKeyDown.Bind(self._keyHandler)

		win = {'name':name, 'canvas':fig, 'shape':dims, 'keyEvent':None, 'text':[]}
		self.open_windows.append(win)

		return win
コード例 #3
0
	def ShowImg (self) :
		"""
		Draw image
		"""
		if self._abort_img  :
			# Exit
			return
		
		# Get image
		img = self.dev.StopImgAqusition()
		
		# Display image
		try :
			if img <> RETURN_FAIL :
				self._img_plot.SetData(img)
		except AttributeError :
			visvis.cla()
			visvis.clf()
			self._img_plot = visvis.imshow(img)
			visvis.title ('Camera view')
			ax = visvis.gca()
			ax.axis.xTicks = []
			ax.axis.yTicks = []
		
		# Start acquisition of histogram
		self.dev.StartImgAqusition()
		wx.CallAfter(self.ShowImg)
コード例 #4
0
	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()] )
コード例 #5
0
ファイル: show.py プロジェクト: simphony/nfluid
def show(items, normals=None):
    """Function that shows a mesh object.
    """
    for item in items:
        vv.clf()
        # convert to visvis.Mesh class
        new_normals = []
        new_vertices = []
        for k, v in item.vertices.iteritems():
            new_normals.append(item.normal(k))
            new_vertices.append(v)
        mesh = item.to_visvis_mesh()

        mesh.SetVertices(new_vertices)
        mesh.SetNormals(new_normals)
        mesh.faceColor = 'y'
        mesh.edgeShading = 'plain'
        mesh.edgeColor = (0, 0, 1)

    axes = vv.gca()
    if axes.daspectAuto is None:
        axes.daspectAuto = False
    axes.SetLimits()

    if normals is not None:
        for normal in normals:
            sl = solidLine(normal, 0.15)
            sl.faceColor = 'r'

    # Show title and enter main loop
    vv.title('Show')
    app = vv.use()
    app.Run()
コード例 #6
0
	def StartInteractivelyMeasureSpectrum (self, event) :
		"""
		This method display spectrum
		"""
		button = self.show_spectrum_button
		
		if button.GetLabel() == button.__start_label__ :
			self.StopAllJobs()
			# get spectrometer's settings
			spect_settings = self.SettingsNotebook.Spectrometer.GetSettings()
			
			# Initiate spectrometer
			if self.Spectrometer.SetSettings(spect_settings) == RETURN_FAIL : return
			
			try : self.wavelengths = self.Spectrometer.GetWavelengths()
			except AttributeError : self.wavelengths = None
			
			# Clearing the figure
			visvis.cla(); visvis.clf();		
			
			# Set up timer to draw spectrum
			TIMER_ID = wx.NewId()
			self.spectrum_timer =  wx.Timer (self, TIMER_ID)
			self.spectrum_timer.Start (spect_settings["exposure_time"])
			wx.EVT_TIMER (self, TIMER_ID, self.DrawSpectrum)
			
			# Chose plotting options 
			try :
				self.is_autoscaled_spectrum = not(spect_settings["fix_vertical_axis"])
			except KeyError :
				self.is_autoscaled_spectrum = True
				
			if not self.is_autoscaled_spectrum :
				self.spectrum_plot_limits = ( spect_settings["vertical_axis_min_val"],
											spect_settings["vertical_axis_max_val"] )
			
			# Change button's label
			button.SetLabel (button.__stop_label__)
		
		elif button.GetLabel() == button.__stop_label__ :		
			# Stopping timer
			self.spectrum_timer.Stop()
			del self.spectrum_timer
			# Delete the parameter for auto-scaling
			del self.spectrum_plot_limits, self.is_autoscaled_spectrum
			
			# Delate visvis objects
			try : del self.__interact_2d_spectrum__
			except AttributeError : pass
			try : del self.__interact_1d_spectrum__
			except AttributeError : pass
			
			# Change button's label
			button.SetLabel (button.__start_label__) 
			
		else : raise ValueError("Label is not recognized") 
コード例 #7
0
    def paint(self, visvis):
        vv.clf()

        colors = ["r", "g", "b", "c", "m", "y", "k"]
        for index, dataset in enumerate(self._value):
            l = visvis.plot(dataset, ms="o", mc=colors[index % len(colors)], mw="3", ls="", mew=0)
            l.alpha = 0.3

        self._a = vv.gca()
        self._a.daspectAuto = True
コード例 #8
0
ファイル: Mesh_Ex_09.py プロジェクト: CALFEM/calfem-python
 def _Plot(self, event):
     # Make sure our figure is the active one
     # If only one figure, this is not necessary.
     #vv.figure(self.fig.nr)
     
     # Clear it:
     vv.clf()
     
     # Plot:
     pcv.drawDisplacements(self.a, self.coords, self.edof, self.dofsPerNode, self.elType, doDrawUndisplacedMesh=True, title="Example 09")
コード例 #9
0
    def paint(self, visvis):
        vv.clf()  
        
        colors = ['r','g','b','c','m','y','k']
        for index, dataset in enumerate(self._value):
            l = visvis.plot(dataset, ms='o', mc=colors[ index % len(colors) ], mw='3', ls='', mew=0 )
            l.alpha = 0.3

        self._a = vv.gca()
        self._a.daspectAuto = True
コード例 #10
0
ファイル: main.py プロジェクト: dibondar/PyPhotonicReagents
	def MeasureSingleSpectrum (self, event=None) :
		"""
		Button <self.show_spectrum_button> was clicked
		"""
		button = self.show_spectrum_button
		
		if button.GetLabel() == button.__start_label__ :
			self.StopAllJobs()
			# get spectrometer's settings
			spect_settings = self.SettingsNotebook.Spectrometer.GetSettings()
			
			# Initiate spectrometer
			if self.Spectrometer.SetSettings(spect_settings) == RETURN_FAIL : return
			self.wavelengths = self.Spectrometer.GetWavelengths()
			
			# Clearing the figure
			visvis.clf()
		
			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() )
				
			# Set up timer to draw spectrum
			TIMER_ID = wx.NewId()
			self.spectrum_timer =  wx.Timer (self, TIMER_ID)
			self.spectrum_timer.Start (spect_settings["exposure_time"])
			
			# Change button's label
			button.SetLabel (button.__stop_label__)
			wx.EVT_TIMER (self, TIMER_ID, draw_spectrum)
			
		elif button.GetLabel() == button.__stop_label__ :
			# Stopping timer
			self.spectrum_timer.Stop()
			del self.spectrum_timer
			# Change button's label
			button.SetLabel (button.__start_label__) 
			
		else : raise ValueError("Label is not recognized") 
コード例 #11
0
def main(select=3, **kwargs):
    """Script main function.

    select: int
        1: Medical data
        2: Blocky data, different every time
        3: Two donuts
        4: Ellipsoid

    """
    import visvis as vv  # noqa: delay import visvis and GUI libraries

    # Create test volume
    if select == 1:
        vol = vv.volread('stent')
        isovalue = kwargs.pop('level', 800)
    elif select == 2:
        vol = vv.aVolume(20, 128)
        isovalue = kwargs.pop('level', 0.2)
    elif select == 3:
        with timer('computing donuts'):
            vol = donuts()
        isovalue = kwargs.pop('level', 0.0)
        # Uncommenting the line below will yield different results for
        # classic MC
        # vol *= -1
    elif select == 4:
        vol = ellipsoid(4, 3, 2, levelset=True)
        isovalue = kwargs.pop('level', 0.0)
    else:
        raise ValueError('invalid selection')

    # Get surface meshes
    with timer('finding surface lewiner'):
        vertices1, faces1 = marching_cubes_lewiner(vol, isovalue, **kwargs)[:2]

    with timer('finding surface classic'):
        vertices2, faces2 = marching_cubes_classic(vol, isovalue, **kwargs)

    # Show
    vv.figure(1)
    vv.clf()
    a1 = vv.subplot(121)
    vv.title('Lewiner')
    m1 = vv.mesh(np.fliplr(vertices1), faces1)
    a2 = vv.subplot(122)
    vv.title('Classic')
    m2 = vv.mesh(np.fliplr(vertices2), faces2)
    a1.camera = a2.camera

    # visvis uses right-hand rule, gradient_direction param uses left-hand rule
    m1.cullFaces = m2.cullFaces = 'front'  # None, front or back

    vv.use().Run()
コード例 #12
0
ファイル: embeddingInFLTK.py プロジェクト: chiluf/visvis.dev
 def _Plot(self, event):
     
     # Make sure our figure is the active one
     # If only one figure, this is not necessary.
     #vv.figure(self.fig.nr)
     
     # Clear it
     vv.clf()
     
     # Plot
     vv.plot([1,2,3,1,6])
     vv.legend(['this is a line'])        
コード例 #13
0
    def __plot(self, spectrum):
        vv.clf()
        axes = vv.gca()
        axes.axis.showGrid = True
        axes.axis.xLabel = 'Frequency (MHz)'
        axes.axis.yLabel = 'Level (dB)'

        total = len(spectrum)
        count = 0.
        for _time, sweep in spectrum.items():
            alpha = (total - count) / total
            vv.plot(sweep.keys(), sweep.values(), lw=1, alpha=alpha)
            count += 1
コード例 #14
0
	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)')
		
		
コード例 #15
0
    def plot(self, new_point):
        vv.clf()
        # checking amount of points
        length = max(len(self.points[0]) - 90, len(self.points_i[0]) - 90, 0)
        if self.check_u.checkState():
            # plots points for voltage if voltage is on
            self.plot_point_set(new_point[:2], 'b', length)
        if self.check_i.checkState():
            # plots points for currency if currency is on
            self.plot_point_set([new_point[0], new_point[2]], 'r', length, i=True)

        first_point = self.points_i[0][0] if self.check_i.checkState() else self.points[0][0]

        # set Axes limits on current time
        self.fig.currentAxes.SetLimits((first_point, first_point+10), (-5, 5))
        self.fig.currentAxes.axis.showGrid = True
        self.fig.DrawNow()
コード例 #16
0
ファイル: dataController.py プロジェクト: MUSpeechLab/TOAK
    def setupAxes(self):
        """
            Sets up the axes initially.  Shows a 2d view with a range based 
            on the sensor positions.  Might want to give the user the option to set the range
            in future releases.
            The if statement is for when the sensors got switched.. which only
            happens on 2 subjects, but totally messes up the axes view then.
            
        """
        vv.clf()    
        self.axes = vv.gca()
        self.axisLabeler = self.axes.axis
        self.axes.cameraType = 3
        self.axes.daspectAuto= False

        #.SetLimits(#rangeX = (xmin,xmax),rangeY = (ymin,ymax), rangeZ = (zmin,zmax))
        self.axisLabeler.showGrid = True
コード例 #17
0
	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
コード例 #18
0
    def _Plot(self, event):
        # Make sure our figure is the active one
        # If only one figure, this is not necessary.
        # vv.figure(self.fig.nr)

        # Clear it
        vv.clf()

        song = wave.open("C:\Users\Mario\Desktop\infoadex antonio\\20150617070001.wav", 'r')
        frames = song.getnframes()
        ch = song.getnchannels()
        song_f = song.readframes(ch*frames)
        data = np.fromstring(song_f, np.int16)

        print data

        # Plot
        # vv.plot([1,2,3,1,6])
        vv.plot(data)
        vv.legend(['this is a line'])
コード例 #19
0
ファイル: visualizer.py プロジェクト: simphony/nfluid
    def set_mesh(self, mesh):
        vv.clf()
        self._vv_widget = vv.gcf()
        self._vv_widget._widget.show()
        self.main_win.setCentralWidget(self.widget())
        if mesh:
            v_mesh = mesh.to_visvis_mesh()
            v_mesh.faceColor = 'y'
            v_mesh.edgeShading = 'plain'
            v_mesh.edgeColor = (0, 0, 1)

            axes = vv.gca()
            if axes.daspectAuto is None:
                axes.daspectAuto = False
            axes.SetLimits()
            axes.legend = 'X', 'Y', 'Z'
            axes.axis.showGrid = True
            axes.axis.xLabel = 'X'
            axes.axis.yLabel = 'Y'
            axes.axis.zLabel = 'Z'
コード例 #20
0
ファイル: test_random.py プロジェクト: binaryannamolly/visvis
def show(self):
    
    import visvis as vv
    
    # If there are many tests, make a selection
    if len(self._tests) > 1000:
        tests = random.sample(self._tests, 1000)
    else:
        tests = self._tests
    
    # Get ticks
    nn = [test[0] for test in tests]
    
    # Create figure
    vv.figure(1)
    vv.clf()
    
    # Prepare kwargs
    plotKwargsText = {'ms':'.', 'mc':'b', 'mw':5, 'ls':''}
    plotKwargsBin = {'ms':'.', 'mc':'r', 'mw':5, 'ls':''}
    
    # File size against number of elements
    vv.subplot(221)
    vv.plot(nn, [test[2][0] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[2][1] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('File size')
    
    # Speed against number of elements
    vv.subplot(223)
    vv.plot(nn, [test[1][4] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[1][6] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('Save time')
    
    # Speed (file) against number of elements
    vv.subplot(224)
    vv.plot(nn, [test[1][5] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[1][7] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('Load time')
コード例 #21
0
ファイル: test_ffmpeg.py プロジェクト: ghisvail/imageio
def show_in_visvis():
    reader = imageio.read('cockatoo.mp4', 'ffmpeg')
    #reader = imageio.read('<video0>')
    
    import visvis as vv
    im = reader.get_next_data()
    f = vv.clf()
    f.title = reader.format.name
    t = vv.imshow(im, clim=(0, 255))
    
    while not f._destroyed:
        t.SetData(reader.get_next_data())
        vv.processEvents()
コード例 #22
0
ファイル: indicator.py プロジェクト: oligo/indicator
    def _Plot(self, event):
        
        # update status text
        self.status.SetLabel("CPU:%.1f\nMemory:%.1f" % (cpudata[-1], vmemdata[-1]))
        # Make sure our figure is the active one
        # If only one figure, this is not necessary.
        #vv.figure(self.fig.nr)
        
        # Clear it
        vv.clf()
        
        # Plot
        a = vv.subplot(211)
        vv.plot(cpudata, lw=2, lc="c", mc ='y', ms='d')
        vv.legend("cpu percent ")
        a.axis.showGrid = True
        a.axis.xlabel = "CPU Usage Percent"
        a.axis.ylabel = "sampling time line"

        a = vv.subplot(212)
        vv.plot(vmemdata, lw=2, mew=1, lc='m', mc ='y', ms='d' )
        vv.legend("virtual memory")
        a.axis.showGrid = True
コード例 #23
0
def show_in_visvis():
    reader = imageio.read("cockatoo.mp4", "ffmpeg")
    # reader = imageio.read('<video0>')

    import visvis as vv

    im = reader.get_next_data()
    f = vv.clf()
    f.title = reader.format.name
    t = vv.imshow(im, clim=(0, 255))

    while not f._destroyed:
        t.SetData(reader.get_next_data())
        vv.processEvents()
コード例 #24
0
    def _createWindow(self, name, im, axis):

        vv.figure()
        vv.gca()
        vv.clf()
        fig = vv.imshow(im)
        dims = im.shape
        ''' Change color bounds '''
        if im.dtype == np.uint8:
            fig.clim.Set(0, 255)
        else:
            fig.clim.Set(0., 1.)

        fig.GetFigure().title = name
        ''' Show ticks on axes? '''
        if not axis:
            fig.GetAxes().axis.visible = False
            bgcolor = (0., 0., 0.)
        else:
            fig.GetAxes().axis.showBox = False
            bgcolor = (1., 1., 1.)
        ''' Set background color '''
        fig.GetFigure().bgcolor = bgcolor
        fig.GetAxes().bgcolor = bgcolor
        ''' Setup keyboard event handler '''
        fig.eventKeyDown.Bind(self._keyHandler)

        win = {
            'name': name,
            'canvas': fig,
            'shape': dims,
            'keyEvent': None,
            'text': []
        }
        self.open_windows.append(win)

        return win
コード例 #25
0
 def __init__(self, c=None, p1=None, p2=None):
     
     # Init visualization
     fig = vv.figure(101); vv.clf()
     a = vv.gca()
     
     # Init patch
     self._patchSize = patchSize = 64
     self._im = np.zeros((patchSize,patchSize), dtype=np.float32)
     self._t = vv.imshow(self._im, clim=(0,10))
     
     # Init points
     if c is None: c = Point(14,12)
     if p1 is None: p1 = Point(12,16)
     if p2 is None: p2 = Point(16,16)
     
     #
     self._c = vv.plot(c, ls='', ms='+', mw=10, mc='k')
     self._p1 = vv.plot(p1, ls='', ms='.', mw=10, mc='r')
     self._p2 = vv.plot(p2, ls='', ms='.', mw=10, mc='b')
     
     
     
     # Init object being moved
     self._movedPoint = None
     
     # Enable callbacks
     for line in [self._c, self._p1, self._p2]:
         line.hitTest = True
         line.eventMouseDown.Bind(self.OnDown)
         line.eventMotion.Bind(self.OnMotion)
         line.eventMouseUp.Bind(self.OnUp)
     a.eventMotion.Bind(self.OnMotion)
     a.eventMouseUp.Bind(self.OnUp)
     
     # Start
     self.Apply()
コード例 #26
0
    def _Plot(self, event):

        # update status text
        self.status.SetLabel("CPU:%.1f\nMemory:%.1f" %
                             (cpudata[-1], vmemdata[-1]))
        # Make sure our figure is the active one
        # If only one figure, this is not necessary.
        #vv.figure(self.fig.nr)

        # Clear it
        vv.clf()

        # Plot
        a = vv.subplot(211)
        vv.plot(cpudata, lw=2, lc="c", mc='y', ms='d')
        vv.legend("cpu percent ")
        a.axis.showGrid = True
        a.axis.xlabel = "CPU Usage Percent"
        a.axis.ylabel = "sampling time line"

        a = vv.subplot(212)
        vv.plot(vmemdata, lw=2, mew=1, lc='m', mc='y', ms='d')
        vv.legend("virtual memory")
        a.axis.showGrid = True
コード例 #27
0
	def createWindow(self, name, im, axis):

		vv.figure()
		vv.gca()
		vv.clf()
		fig = vv.imshow(im)
		dims = im.shape

		''' Change color bounds '''
		if im.dtype == np.uint8:
			fig.clim.Set(0, 255)
		else:
			fig.clim.Set(im.min(), im.max())
		
		fig.GetFigure().title = name
		
		''' Show ticks on axes? '''

		if not axis:
			fig.GetAxes().axis.visible = False
			bgcolor = (0.,0.,0.)
		else:
			fig.GetAxes().axis.showBox = False
			bgcolor = (1.,1.,1.)

		fig.GetFigure().bgcolor = bgcolor
		fig.GetAxes().bgcolor = bgcolor



		fig.eventKeyUp.Bind(self.keyHandler)

		win = {'name':name, 'figure':fig, 'shape':dims, 'keyEvent':None}
		self.open_windows.append(win)

		return win
コード例 #28
0
ファイル: test_ffmpeg.py プロジェクト: imageio/imageio
def show_in_visvis():
    # reader = imageio.read("imageio:cockatoo.mp4", "ffmpeg")
    reader = imageio.read("<video0>", fps=20)

    import visvis as vv

    im = reader.get_next_data()
    f = vv.clf()
    f.title = reader.format.name
    t = vv.imshow(im, clim=(0, 255))

    while not f._destroyed:
        im = reader.get_next_data()
        if im.meta["new"]:
            t.SetData(im)
        vv.processEvents()
コード例 #29
0
def show_in_visvis():
    # reader = imageio.read("imageio:cockatoo.mp4", "ffmpeg")
    reader = imageio.read("<video0>", fps=20)

    import visvis as vv

    im = reader.get_next_data()
    f = vv.clf()
    f.title = reader.format.name
    t = vv.imshow(im, clim=(0, 255))

    while not f._destroyed:
        im = reader.get_next_data()
        if im.meta["new"]:
            t.SetData(im)
        vv.processEvents()
コード例 #30
0
ファイル: exm9wx.py プロジェクト: opetlund/TMM4135-CALFEM
 def _Clear(self, event):
     vv.clf()  #Clear current figure
コード例 #31
0
    def __init__(self,
                 ptcode,
                 ctcode,
                 StartPoints,
                 EndPoints,
                 basedir,
                 modelname='modelavgreg'):
        """ with start and endpoints provided, calculate centerline and save as
        ssdf in basedir as model and dynamic model
        """
        #todo: name of dynamic model is now deforms, unclear, should be dynamic
        #import numpy as np
        import visvis as vv
        import numpy as np
        import os
        import copy

        from stentseg.utils import PointSet, _utils_GUI
        from stentseg.utils.centerline import (find_centerline,
                                               points_from_nodes_in_graph,
                                               points_from_mesh,
                                               smooth_centerline)
        from stentseg.utils.datahandling import loadmodel, loadvol
        from stentseg.utils.visualization import show_ctvolume
        from stentseg.utils.picker import pick3d

        stentnr = len(StartPoints)

        cropname = 'prox'
        what = modelname
        what_vol = 'avgreg'
        vismids = True
        m = loadmodel(basedir, ptcode, ctcode, cropname, what)
        s = loadvol(basedir, ptcode, ctcode, cropname, what_vol)
        s.vol.sampling = [s.sampling[1], s.sampling[1], s.sampling[2]]
        s.sampling = s.vol.sampling

        start1 = StartPoints.copy()
        ends = EndPoints.copy()

        from stentseg.stentdirect import stentgraph
        ppp = points_from_nodes_in_graph(m.model)

        allcenterlines = []  # for pp
        allcenterlines_nosmooth = []  # for pp
        centerlines = []  # for stentgraph
        nodes_total = stentgraph.StentGraph()
        for j in range(stentnr):
            if j == 0 or not start1[j] == ends[j - 1]:
                # if first stent or when stent did not continue with this start point
                nodes = stentgraph.StentGraph()
                centerline = PointSet(3)  # empty

            # Find main centerline
            # if j > 3: # for stent with midpoints
            #     centerline1 = find_centerline(ppp, start1[j], ends[j], step= 1,
            #     ndist=10, regfactor=0.5, regsteps=10, verbose=False)

            #else:
            centerline1 = find_centerline(ppp,
                                          start1[j],
                                          ends[j],
                                          step=1,
                                          ndist=10,
                                          regfactor=0.5,
                                          regsteps=1,
                                          verbose=False)
            # centerline1 is a PointSet

            print('Centerline calculation completed')

            # ========= Maaike =======
            smoothfactor = 15  # Mirthe used 2 or 4

            # check if cll continued here from last end point
            if not j == 0 and start1[j] == ends[j - 1]:
                # yes we continued
                ppart = centerline1[:
                                    -1]  # cut last but do not cut first point as this is midpoint
            else:
                # do not use first points, as they are influenced by user selected points
                ppart = centerline1[1:-1]

            for p in ppart:
                centerline.append(p)

            # if last stent or stent does not continue with next start-endpoint
            if j == stentnr - 1 or not ends[j] == start1[j + 1]:
                # store non-smoothed for vis
                allcenterlines_nosmooth.append(centerline)
                pp = smooth_centerline(centerline, n=smoothfactor)
                # add pp to list
                allcenterlines.append(pp)  # list with PointSet per centerline
                self.allcenterlines = allcenterlines

                # add pp as nodes
                for i, p in enumerate(pp):
                    p_as_tuple = tuple(p.flat)
                    nodes.add_node(p_as_tuple)
                    nodes_total.add_node(p_as_tuple)
                # add pp as one edge so that pathpoints are in fixed order
                pstart = tuple(pp[0].flat)
                pend = tuple(pp[-1].flat)
                nodes.add_edge(pstart, pend, path=pp)
                nodes_total.add_edge(pstart, pend, path=pp)
                # add final centerline nodes model to list
                centerlines.append(nodes)

            # ========= Maaike =======

        ## Store segmentation to disk

        # Build struct
        s2 = vv.ssdf.new()
        s2.sampling = s.sampling
        s2.origin = s.origin
        s2.stenttype = m.stenttype
        s2.croprange = m.croprange
        for key in dir(m):
            if key.startswith('meta'):
                suffix = key[4:]
                s2['meta' + suffix] = m['meta' + suffix]
        s2.what = what
        s2.params = s.params  #reg
        s2.paramsseeds = m.params
        s2.stentType = 'nellix'
        s2.StartPoints = StartPoints
        s2.EndPoints = EndPoints
        # keep centerlines as pp also [Maaike]
        s2.ppallCenterlines = allcenterlines
        for k in range(len(allcenterlines)):
            suffix = str(k)
            pp = allcenterlines[k]
            s2['ppCenterline' + suffix] = pp

        s3 = copy.deepcopy(s2)
        s3['model'] = nodes_total.pack()

        # Store model for each centerline
        for j in range(len(centerlines)):
            suffix = str(j)
            model = centerlines[j]
            s2['model' + suffix] = model.pack()

        # Save model with seperate centerlines.
        filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname,
                                         'centerline_' + what)
        vv.ssdf.save(os.path.join(basedir, ptcode, filename), s2)
        print('saved to disk as {}.'.format(filename))

        # Save model with combined centerlines
        filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname,
                                         'centerline_total_' + what)
        vv.ssdf.save(os.path.join(basedir, ptcode, filename), s3)
        print('saved to disk as {}.'.format(filename))

        # remove intermediate centerline points
        # start1 = map(tuple, start1)
        # ends = map(tuple, ends)
        startpoints_clean = copy.deepcopy(start1)
        endpoints_clean = copy.deepcopy(ends)
        duplicates = list(set(start1) & set(ends))
        for i in range(len(duplicates)):
            startpoints_clean.remove(duplicates[i])
            endpoints_clean.remove(duplicates[i])

        #Visualize
        f = vv.figure(10)
        vv.clf()
        a1 = vv.subplot(121)
        a1.daspect = 1, 1, -1

        vv.plot(ppp, ms='.', ls='', alpha=0.6, mw=2)
        for j in range(len(startpoints_clean)):
            vv.plot(PointSet(list(startpoints_clean[j])),
                    ms='.',
                    ls='',
                    mc='g',
                    mw=20)  # startpoint green
            vv.plot(PointSet(list(endpoints_clean[j])),
                    ms='.',
                    ls='',
                    mc='r',
                    mw=20)  # endpoint red
        for j in range(len(allcenterlines)):
            vv.plot(allcenterlines[j], ms='.', ls='', mw=10, mc='y')
        vv.title('Centerlines and seed points')
        vv.xlabel('x (mm)')
        vv.ylabel('y (mm)')
        vv.zlabel('z (mm)')
        # for j in range(len(allcenterlines_nosmooth)):
        #     vv.plot(allcenterlines_nosmooth[j], ms='o', ls='', mw=10, mc='c', alpha=0.6)

        a2 = vv.subplot(122)
        a2.daspect = 1, 1, -1

        vv.plot(ppp, ms='.', ls='', alpha=0.6, mw=2)
        # vv.volshow(s.vol, clim=clim, renderStyle = 'mip')
        t = show_ctvolume(s.vol,
                          axis=a2,
                          showVol='ISO',
                          clim=(0, 2500),
                          isoTh=250,
                          removeStent=False,
                          climEditor=True)
        label = pick3d(vv.gca(), s.vol)
        for j in range(len(startpoints_clean)):
            vv.plot(PointSet(list(startpoints_clean[j])),
                    ms='.',
                    ls='',
                    mc='g',
                    mw=20,
                    alpha=0.6)  # startpoint green
            vv.plot(PointSet(list(endpoints_clean[j])),
                    ms='.',
                    ls='',
                    mc='r',
                    mw=20,
                    alpha=0.6)  # endpoint red
        for j in range(len(allcenterlines)):
            vv.plot(allcenterlines[j], ms='o', ls='', mw=10, mc='y', alpha=0.6)

        # show midpoints (e.g. duplicates)
        if vismids:
            for p in duplicates:
                vv.plot(p[0], p[1], p[2], mc='m', ms='o', mw=10, alpha=0.6)

        a2.axis.visible = False

        vv.title('Centerlines and seed points')

        a1.camera = a2.camera

        f.eventKeyDown.Bind(
            lambda event: _utils_GUI.RotateView(event, [a1, a2]))
        f.eventKeyDown.Bind(
            lambda event: _utils_GUI.ViewPresets(event, [a1, a2]))

        # Pick node for midpoint to redo get_centerline
        self.pickedCLLpoint = _utils_GUI.Event_pick_graph_point(
            nodes_total, s.vol, label, nodesOnly=True)  # x,y,z
        # use key p to select point

        #===============================================================================
        vv.figure(11)
        vv.gca().daspect = 1, 1, -1
        t = show_ctvolume(s.vol,
                          showVol='ISO',
                          clim=(0, 2500),
                          isoTh=250,
                          removeStent=False,
                          climEditor=True)
        label2 = pick3d(vv.gca(), s.vol)
        for j in range(len(startpoints_clean)):
            vv.plot(PointSet(list(startpoints_clean[j])),
                    ms='.',
                    ls='',
                    mc='g',
                    mw=20,
                    alpha=0.6)  # startpoint green
            vv.plot(PointSet(list(endpoints_clean[j])),
                    ms='.',
                    ls='',
                    mc='r',
                    mw=20,
                    alpha=0.6)  # endpoint red
        vv.xlabel('x (mm)')
        vv.ylabel('y (mm)')
        vv.zlabel('z (mm)')
        #===============================================================================

        ## Make model dynamic (and store/overwrite to disk)
        import pirt
        from stentseg.motion.dynamic import incorporate_motion_nodes, incorporate_motion_edges

        # Load deforms
        filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'deforms')
        s1 = vv.ssdf.load(os.path.join(basedir, ptcode, filename))
        deformkeys = []
        for key in dir(s1):
            if key.startswith('deform'):
                deformkeys.append(key)
        deforms = [s1[key] for key in deformkeys]
        deforms = [
            pirt.DeformationFieldBackward(*fields) for fields in deforms
        ]
        for i in range(len(deforms)):
            deforms[i]._field_sampling = tuple(s1.sampling)
        paramsreg = s1.params

        # Load model
        s2 = loadmodel(basedir, ptcode, ctcode, cropname, 'centerline_' + what)
        s3 = loadmodel(basedir, ptcode, ctcode, cropname,
                       'centerline_total_' + what)

        # Combine ...
        for key in dir(s2):
            if key.startswith('model'):
                incorporate_motion_nodes(s2[key], deforms, s.origin)
                incorporate_motion_edges(s2[key], deforms, s.origin)
                model = s2[key]
                s2[key] = model.pack()
        # Combine ...
        for key in dir(s3):
            if key.startswith('model'):
                incorporate_motion_nodes(s3[key], deforms, s.origin)
                incorporate_motion_edges(s3[key], deforms, s.origin)
                model = s3[key]
                s3[key] = model.pack()

        # Save
        s2.paramsreg = paramsreg
        filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname,
                                         'centerline_' + what + '_deforms')
        vv.ssdf.save(os.path.join(basedir, ptcode, filename), s2)
        print('saved to disk as {}.'.format(filename))

        # Save
        s3.paramsreg = paramsreg
        filename = '%s_%s_%s_%s.ssdf' % (
            ptcode, ctcode, cropname, 'centerline_total_' + what + '_deforms')
        vv.ssdf.save(os.path.join(basedir, ptcode, filename), s3)
        print('saved to disk as {}.'.format(filename))
コード例 #32
0
    def plot(self, engine='pyplot', iterations=None):
        """Plots the system using a specified render engine.
        Needs compute_3d_vectrices() to be called before.
        - engine: String for the render engine. Can be 'pyplot', 'plotly' or 'visvis'.
        pyplot is the nicest because it supports antialiasing on translucent objects.
        plotly is a way faster alternative that uses your web browser's render engine.
        visvis is faster but a bit rough.
        - iterations: Limits the plotting to this number of iterations.
        If None, the whole system states will be plotted."""
        engine = engine.lower()
        if iterations is None:
            iterations = self.iterations
        elif iterations > self.iterations:
            raise ValueError("Unable to plot %s out of %s iterations"
                % (iterations, self.iterations))

        if engine == 'visvis':
            try:
                import visvis as vv
            except ImportError:
                raise ImportError("visvis must be installed in order to use it."
                "Try to 'pip install visvis' in a command line.")
            app = vv.use()
            fig = vv.clf()
            ax  = vv.cla()

        elif engine == 'pyplot':
            try:
                import matplotlib.pyplot as plt
                from mpl_toolkits.mplot3d import Axes3D
            except ImportError:
                raise ImportError("pyplot must be installed in order to use it."
                "Try to 'pip install matplotlib' in a command line.")
            fig = plt.figure(figsize=(32, 18), dpi=100)
            ax = fig.gca(projection='3d')
            ax.set_axis_off()

        elif engine == 'plotly':
            try:
                import plotly as pl
                from plotly.graph_objs import Scatter3d, Layout, Scene, Figure
            except ImportError:
                raise ImportError("plotly must be installed in order to use it."
                "Try to 'pip install plotly' in a command line.")
            data = []
            layout = Layout(
                scene = Scene(
                    xaxis=dict(
                        visible = False,
                        autorange = True,
                    ),
                    yaxis=dict(
                        visible = False,
                        autorange = True,
                    ),
                    zaxis=dict(
                        visible = False,
                        autorange = True,
                    )
                ),
                margin=dict(
                    r=0, l=0,
                    b=0, t=0
                ),
                showlegend = False,
                hovermode = False
            )

        else:
            raise ValueError("%s is not a supported render engine." % engine)


        rings  = self.rings[:iterations]
        for i, ring in enumerate(rings):
            color = self.cmap(i, 0, len(self.rings) / 2, 1)
            if engine == 'visvis':
                vv.plot(*ring, lc=color, mw=0, alpha=.2)
            elif engine == 'pyplot':
                ax.plot(*ring, c=color+(.4,)) # Adding alpha as (r, g, b, a)
            else:
                data.append(Scatter3d(
                    x = ring[0],
                    y = ring[1],
                    z = ring[2],
                    mode = 'lines',
                    opacity = .3,
                    line = dict(
                        color = ("rgb(%s,%s,%s)" % tuple([int(x*255) for x in color])),
                        width = 3)
                ))

        curves = [curve[:iterations] for curve in self.curves]
        for curve in curves:
            if engine == 'visvis':
                vv.plot(*curve, lc='k', mw=0, lw=2)
            elif engine == 'pyplot':
                ax.plot(*curve, c=(0, 0, 0, .8))
            else:
                data.append(Scatter3d(
                x = curve[0],
                y = curve[1],
                z = curve[2],
                mode = 'lines',
                line = dict(
                    color = ("rgb(0, 0, 0)"),
                    width = 4)
                ))

        if engine == 'visvis':
            ax = vv.gca()
            app.Run()

        elif engine == 'pyplot':
            fig.tight_layout()
            # plt.draw()
            mng = plt.get_current_fig_manager()
            mng.full_screen_toggle()
            plt.show()

        else:
            fig = Figure(data=data, layout=layout)
            # pl.plot(fig, filename='3d-scatter-with-axes-titles')
            pl.offline.plot(fig)

        return
コード例 #33
0
	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)
コード例 #34
0
ファイル: picking.py プロジェクト: chiluf/visvis.dev
#!/usr/bin/env python
""" This example illustrates picking using the simple event system.
It also shows the working of the picking in an environment.

Notice for example that the leave event is not fired when you move 
the mouse beyond the boundaries of the yellow rectangle as long
as it's still inside the red rectangle. This is because the red
rectangle is a child of the yellow rectangle. 
"""

import numpy as np
import visvis as vv
app = vv.use()

f = vv.clf()
l1 = vv.plot([1, 2, 3, 2, 4], lw=3)
l2 = vv.plot([4, 6, 5, 1, 3], lc='r', mc='r', lw=3)

# im = np.zeros((10,10)); im[7:9,:]=1; im[:,7:9]=0.6
# t1 = vv.imshow(im)

b1 = vv.Box(f)
b1.position = 0.1, 0.2, 100, 40
b1.bgcolor = (1, 1, 0)

b2 = vv.Box(b1)
b2.position = 5, 20, 20, 50
#b2.bgcolor=(1,0,0)

a = vv.gca()
a.daspectAuto = True
コード例 #35
0
    def StartInteractivelyMeasureSpectrum(self, event):
        """
		This method display spectrum
		"""
        button = self.show_spectrum_button

        if button.GetLabel() == button.__start_label__:
            self.StopAllJobs()
            # get spectrometer's settings
            spect_settings = self.SettingsNotebook.Spectrometer.GetSettings()

            # Initiate spectrometer
            if self.Spectrometer.SetSettings(spect_settings) == RETURN_FAIL:
                return

            try:
                self.wavelengths = self.Spectrometer.GetWavelengths()
            except AttributeError:
                self.wavelengths = None

            # Clearing the figure
            visvis.cla()
            visvis.clf()

            # Set up timer to draw spectrum
            TIMER_ID = wx.NewId()
            self.spectrum_timer = wx.Timer(self, TIMER_ID)
            self.spectrum_timer.Start(spect_settings["exposure_time"])
            wx.EVT_TIMER(self, TIMER_ID, self.DrawSpectrum)

            # Chose plotting options
            try:
                self.is_autoscaled_spectrum = not (
                    spect_settings["fix_vertical_axis"])
            except KeyError:
                self.is_autoscaled_spectrum = True

            if not self.is_autoscaled_spectrum:
                self.spectrum_plot_limits = (
                    spect_settings["vertical_axis_min_val"],
                    spect_settings["vertical_axis_max_val"])

            # Change button's label
            button.SetLabel(button.__stop_label__)

        elif button.GetLabel() == button.__stop_label__:
            # Stopping timer
            self.spectrum_timer.Stop()
            del self.spectrum_timer
            # Delete the parameter for auto-scaling
            del self.spectrum_plot_limits, self.is_autoscaled_spectrum

            # Delate visvis objects
            try:
                del self.__interact_2d_spectrum__
            except AttributeError:
                pass
            try:
                del self.__interact_1d_spectrum__
            except AttributeError:
                pass

            # Change button's label
            button.SetLabel(button.__start_label__)

        else:
            raise ValueError("Label is not recognized")
コード例 #36
0
ファイル: fitting.py プロジェクト: almarklein/stentseg
    c3 = fit_circle(pp3_2)
    e3 = fit_ellipse(pp3_2)
    print('area circle 3D: % 1.2f' % area(c3))
    print('area ellipse 3D: % 1.2f' % area(e3))
    
    # 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]
    
    # Init visualization
    import visvis as vv
    fig = vv.clf()
    fig.position = 300, 300, 1000, 600
    
    # 2D vis
    a = vv.subplot(121)
    a.daspectAuto = False
    a.axis.showGrid = True
    vv.title('2D fitting')
    vv.xlabel('x'); vv.ylabel('y')
    # Plot
    vv.plot(pp2, ls='', ms='.', mc='k')
#     vv.plot(sample_circle(c2), lc='r', lw=2)
    vv.plot(sample_ellipse(e2), lc='b', lw=2)
#     vv.legend('2D points', 'Circle fit', 'Ellipse fit')
    vv.legend('2D points', 'Ellipse fit')
    
コード例 #37
0
def identifyCenterlines(s,
                        ptcode,
                        ctcode,
                        basedir,
                        modelname,
                        showVol='MIP',
                        **kwargs):
    """ s is struct with models
    """
    from stentseg.utils.datahandling import select_dir, loadvol, loadmodel
    from stentseg.utils.picker import pick3d
    from stentseg.utils.visualization import show_ctvolume
    from stentseg.utils import _utils_GUI

    showAxis = False
    # showVol  = 'MIP'  # MIP or ISO or 2D or None
    clim = (0, 2500)
    # clim = -200,500 # 2D
    isoTh = 250
    cropname = 'prox'

    # init fig
    f = vv.figure()
    vv.clf()
    f.position = 0.00, 22.00, 1920.00, 1018.00
    # load vol
    svol = loadvol(basedir, ptcode, ctcode, cropname, what='avgreg')
    # set sampling for cases where this was not stored correctly
    svol.vol.sampling = [svol.sampling[1], svol.sampling[1], svol.sampling[2]]
    vol = svol.vol
    s.sampling = [svol.sampling[1], svol.sampling[1],
                  svol.sampling[2]]  # for model
    # show vol
    t = show_ctvolume(vol, showVol=showVol, clim=clim, isoTh=isoTh, **kwargs)
    label = pick3d(vv.gca(), vol)
    vv.xlabel('x (mm)')
    vv.ylabel('y (mm)')
    vv.zlabel('z (mm)')

    if showVol == 'MIP':
        c = vv.ClimEditor(vv.gca())
        c.position = (10, 50)
        f.eventKeyDown.Bind(lambda event: _utils_GUI.ShowHideSlider(event, c))
        print('Use "s" to show/hide slider')
    if showVol == 'ISO':
        c = _utils_GUI.IsoThEditor(vv.gca())
        c.position = (10, 50)
        f.eventKeyDown.Bind(lambda event: _utils_GUI.ShowHideSlider(event, c))
        print('Use "s" to show/hide slider')

    f.eventKeyDown.Bind(
        lambda event: _utils_GUI.ViewPresets(event, [vv.gca()]))
    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('------------------------')

    ax, s2 = interactiveCenterlineID(s, ptcode, ctcode, basedir, cropname,
                                     modelname)

    return ax, s2
コード例 #38
0
ファイル: hist.py プロジェクト: chiluf/visvis.dev
    
    """
    
    # Auto determine bins?
    if bins is None:
        from visvis.processing.statistics import StatData
        stats = StatData(data)
        bins = stats.best_number_of_bins()
    
    # let numpy do the work
    if np.__version__ < '1.3':
        values, edges = np.histogram(data, bins, drange, normed, weights, new=True)
    else:
        values, edges = np.histogram(data, bins, drange, normed, weights)
    
    # the bins are the left bin edges, let's get the centers
    centers = np.empty(values.shape, np.float64)
    for i in range(len(values)):
        centers[i] = (edges[i] + edges[i+1]) * 0.5
    
    # plot
    dbin = centers[1] - centers[0]
    return vv.bar(centers, values, width=dbin*0.9)
    #return vv.plot(centers, values, **kwargs)
    
if __name__ == '__main__':
    vv.clf()
    data = np.random.normal(7,2,size=(100,100))
    b = hist(data)
    b.color = 'r'
コード例 #39
0
 def _Plot(self, *args):
     vv.figure(self.figure.nr)
     vv.clf()
     vv.plot([1, 2, 3, 1, 6])
     vv.legend(['this is a line'])
コード例 #40
0
ファイル: nellix2ssdf.py プロジェクト: almarklein/stentseg
    def __init__(self, dicom_basedir, ptcode, ctcode, basedir):

        import imageio
        #import easygui

        from stentseg.utils.datahandling import loadvol
        from stentseg.utils.datahandling import savecropvols, saveaveraged

        ## Select base directory for LOADING DICOM data

        #dicom_basedir = easygui.diropenbox()
        print('DICOM Path = ', dicom_basedir)

        #ctcode = '12months'  # 'pre', 'post_x', '12months'
        stenttype = 'nellix'

        ## Select base directory to SAVE SSDF
        #basedir = easygui.diropenbox()
        print('Base Path = ', basedir)

        # Set which crops to save
        cropnames = ['prox']  #,'stent'] # ['ring'] or ['ring','stent'] or ..

        #===============================================================================
        ## Step A: read single volumes to get vols:
        #  folder1 = '10%'
        #  folder2 = '60%'
        #  vol1 = imageio.volread(os.path.join(dicom_basedir, folder1), 'dicom')
        #  vol2 = imageio.volread(os.path.join(dicom_basedir, folder2), 'dicom')
        #  print(  )
        #
        #  if vol1.meta.SeriesDescription[:2] < vol2.meta.SeriesDescription[:2]:
        #      vols4078 = [vol1,vol2]
        #  else:
        #      vols4078 = [vol2,vol1]
        #
        #  vols = vols4078.copy()
        #
        #  for vol in vols:
        #      vol.meta.PatientName = ptcode # anonimyze
        #      vol.meta.PatientID = 'anonymous'
        #     print(vol.meta.SeriesDescription,'-', vol.meta.sampling)
        #===============================================================================

        ##Orginele code
        #===============================================================================
        #
        # folder1 = '40% iDose'
        # folder2 = '78 iDose'
        # vol1 = imageio.volread(os.path.join(dicom_basedir, folder1), 'dicom')
        # vol2 = imageio.volread(os.path.join(dicom_basedir, folder2), 'dicom')
        # print(  )
        #
        # if vol1.meta.SeriesDescription[:2] < vol2.meta.SeriesDescription[:2]:
        #     vols4078 = [vol1,vol2]
        # else:
        #     vols4078 = [vol2,vol1]
        #
        # vols = vols4078.copy()
        #
        # for vol in vols:
        #     vol.meta.PatientName = ptcode # anonimyze
        #     vol.meta.PatientID = 'anonymous'
        #     print(vol.meta.SeriesDescription,'-', vol.meta.sampling)
        #===============================================================================

        ## Step A: read 10 volumes to get vols
        # Deze zoekt alle mappen en dat zijn er dus 10 maar niet in de goede volgorde
        vols2 = [
            vol2 for vol2 in imageio.get_reader(dicom_basedir, 'DICOM', 'V')
        ]

        vols = [None] * len(vols2)
        for i, vol in enumerate(vols2):
            #    print(vol.meta.sampling)
            print(vol.meta.SeriesDescription)
            phase = int(vol.meta.SeriesDescription[:1])
            # use phase to fix order of phases
            vols[phase] = vol
            #vols[phase].meta.ImagePositionPatient = (0.0,0.0,0.0)

        for i, vol in enumerate(
                vols):  #wat ik heb veranderd is i, en enumerate()
            print(vol.meta.SeriesDescription)
            assert vol.shape == vols[0].shape
            assert str(i * 10) in vol.meta.SeriesDescription  # 0% , 10% etc.

        ## Step B: Crop and Save SSDF
        # 1 of 2 cropnames opgeven voor opslaan 1 of 2 crpos.
        # Het eerste volume wordt geladen in MIP, crop met marges van minimaal 30 mm
        for cropname in cropnames:
            savecropvols(vols, basedir, ptcode, ctcode, cropname, stenttype)
        #    saveaveraged(basedir, ptcode, ctcode, cropname, range(0,100,10))

        ## Visualize result

        #s1 = loadvol(basedir, ptcode, ctcode, cropnames[0], what ='10avgreg')
        #s2 = loadvol(basedir, ptcode, ctcode, cropnames[0], what ='10phases')
        s1 = loadvol(basedir, ptcode, ctcode, cropnames[0], what='phases')
        #s2 = loadvol(basedir, ptcode, ctcode, cropnames[0], what = 'avg010')
        #vol1 = s1.vol
        vol1 = s1.vol40

        # Visualize and compare
        colormap = {
            '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(111)
        a1.daspect = 1, 1, -1
        # t1 = vv.volshow(vol1, clim=(0, 3000), renderStyle='iso') # iso or mip
        # t1.isoThreshold = 600 # stond op 400 maar je moet hoger zetten als je alleen stent wil
        # t1.colormap = colormap
        a1 = vv.volshow2(vol1, clim=(-500, 1500), renderStyle='mip')
        vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z')
        # vv.title('One volume at %i procent of cardiac cycle' % phase )
        vv.title('Vol40')
コード例 #41
0
 def updatePlot(self, X, Y, Z):
     self.activePlot = (X,Y,Z)
     x, y = np.meshgrid(X,Y)
     vv.clf()
     surface = vv.surf(x,y,Z)
     surface.colormap = vv.CM_HOT
コード例 #42
0
 def _Plot(self, *args):
     vv.figure(self.figure.nr)
     vv.clf()
     vv.plot([1,2,3,1,6])
     vv.legend(['this is a line'])
コード例 #43
0
# Perform the first (seeding) step out of 3 steps of stentDirect
sd.Step1()

vol = vol2

## Visualization and interactive segmentation steps
#todo: depending on the speedFactor fronts do not propagate from manually added seeds. 
# see costfunction, from speedfactor > 750 it works

guiRemove = False # True for option to remove nodes/edges but takes longer
clim = (0,3000)
showVol = 'MIP'
meshColor = None # or give FaceColor
viewLR = {'azimuth': 90, 'roll': 0}

fig = vv.figure(3); vv.clf()
fig.position = 0.00, 22.00,  1920.00, 1018.00

# Show model Step 1
a1 = vv.subplot(131)
label = DrawModelAxes(vol, sd._nodes1, a1, clim=clim, showVol=showVol, climEditor=True, removeStent=False) # lc, mc

# Create axis for Step 2
a2 = vv.subplot(132)
DrawModelAxes(vol, ax=a2, clim=clim, showVol=showVol, climEditor=False)

# Create axis for Step 3
a3 = vv.subplot(133)
DrawModelAxes(vol, ax=a3, clim=clim, showVol=showVol, climEditor=False)
# _utils_GUI.vis_spared_edges(sd._nodes3)
コード例 #44
0
ファイル: dicom2ssdf.py プロジェクト: almarklein/stentseg
def dicom2ssdf(dicom_basedir,
               ptcode,
               ctcode,
               basedir,
               cropnames=['stent'],
               savedistolicavg=False,
               visvol=True,
               visdynamic=False):
    """ read dicom volumes and store as ssdf format
    """
    #Step A
    vols2 = [vol2 for vol2 in imageio.get_reader(dicom_basedir, 'DICOM', 'V')]
    try:
        for i, vol in enumerate(vols2):
            print(vol.meta.ImagePositionPatient)
        for i, vol in enumerate(vols2):
            print(vol.shape)
        for i, vol in enumerate(vols2):
            print(vol.meta.AcquisitionTime)
            print(vol.meta.sampling)
            assert vol.shape == vols2[0].shape
            assert vol.meta.SeriesTime == vols2[0].meta.SeriesTime
    except AttributeError:
        print('Some meta information is not available')
        pass

    # check order of phases
    vols = vols2.copy()
    try:
        for i, vol in enumerate(vols):
            print(vol.meta.SeriesDescription)
            assert str(i * 10) in vol.meta.SeriesDescription  # 0% , 10% etc.
    except AttributeError:  # meta info is missing
        print('vol.meta.SeriesDescription meta information is not available')
        pass
    except AssertionError:  # not correct order, fix
        vols = [None] * len(vols2)
        for i, vol in enumerate(vols2):
            print(vol.meta.SeriesDescription)
            phase = int(vol.meta.SeriesDescription[:1])
            # use phase to fix order of phases
            vols[phase] = vol

    # Step B: Crop and Save SSDF
    # Load and show first volume: crop with a margin of at least ~25 mm
    print()
    print('Crop with margins ~25 mm around ROI for the registration algorithm')
    stenttype = None  # deprecate, not needed
    for cropname in cropnames:
        savecropvols(vols, basedir, ptcode, ctcode, cropname, stenttype)
        # Step C: average diastolic phases
        if savedistolicavg:
            phases = 50, 10  # use 7 phases from 50% to 10%
            saveaveraged(basedir, ptcode, ctcode, cropname, phases)

    # Visualize 1 phase
    import visvis as vv
    if visvol:
        vol1 = vols[1]
        colormap = {
            '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)]
        }

        fig = vv.figure(2)
        vv.clf()
        fig.position = 0, 22, 1366, 706
        a1 = vv.subplot(111)
        a1.daspect = 1, 1, -1
        renderStyle = 'mip'
        t1 = vv.volshow(vol1, clim=(0, 3000),
                        renderStyle=renderStyle)  # iso or mip
        if renderStyle == 'iso':
            t1.isoThreshold = 300
            t1.colormap = colormap
        a1 = vv.volshow2(vol1, clim=(-500, 500), renderStyle=renderStyle)
        vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z')
        vv.title('One volume at 10\% procent of cardiac cycle')

    if visdynamic:
        from lspeas.utils.vis import showVolPhases
        showVol = 'mip'
        t = showVolPhases(basedir,
                          vols2,
                          showVol=showVol,
                          mipIsocolor=True,
                          isoTh=310,
                          clim=(60, 3000),
                          slider=True)

    return vols
コード例 #45
0
ファイル: _measureRing.py プロジェクト: almarklein/stentseg
    model = s2.model
    modelmesh = create_mesh(model, 0.6)  # Param is thickness
    
    showAxis = True  # True or False
    showVol  = 'MIP'  # MIP or ISO or 2D or None
    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
    
コード例 #46
0
    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)')
コード例 #47
0
# Perform the three steps of stentDirect
sd.Step1()
sd.Step2()
# sd._nodes2 = stentgraph.StentGraph()
# sd._nodes2.Unpack(ssdf.load('/home/almar/tmp.ssdf'))
sd.Step3()

# Create a mesh object for visualization (argument is strut tickness)
if hasattr(sd._nodes3, 'CreateMesh'):
    bm = sd._nodes3.CreateMesh(0.6)  # old
else:
    bm = create_mesh(sd._nodes3, 0.6) # new


# Create figue
vv.figure(2); vv.clf()

# Show volume and segmented stent as a graph
a1 = vv.subplot(131)
t = vv.volshow(vol)
t.clim = 0, 3000
#sd._nodes1.Draw(mc='g', mw = 6)    # draw seeded nodes
#sd._nodes2.Draw(mc='g')            # draw seeded and MCP connected nodes

# Show cleaned up
a2 = vv.subplot(132)
sd._nodes3.Draw(mc='g', lc='b')

# Show the mesh
a3 = vv.subplot(133)
a3.daspect = 1,-1,1
コード例 #48
0
def clf():
    """Clear visvis figure"""
    vv.clf()
コード例 #49
0
    def __init__(self, ptcode, ctcode, basedir):
        ## Perform image registration

        import os, time

        import numpy as np
        import visvis as vv
        import pirt.reg  # Python Image Registration Toolkit
        from stentseg.utils.datahandling import select_dir, loadvol
        import scipy
        from scipy import ndimage

        # Select dataset to register
        cropname = 'prox'
        what = 'phases'

        # Load volumes
        s = loadvol(basedir, ptcode, ctcode, cropname, what)

        vols = []
        phases = []
        for key in dir(s):
            if key.startswith('vol'):
                print(key)
                # create vol with zoom in z-direction
                zscale = (s[key].sampling[0] / s[key].sampling[1])  # z / y
                # resample vol using spline interpolation, 3rd order piecewise polynomial
                vol_zoom = scipy.ndimage.interpolation.zoom(
                    s[key], [zscale, 1, 1], 'float32')
                s[key].sampling = [
                    s[key].sampling[1], s[key].sampling[1], s[key].sampling[2]
                ]

                # set scale and origin
                vol_zoom_type = vv.Aarray(vol_zoom, s[key].sampling,
                                          s[key].origin)
                vol = vol_zoom_type

                phases.append(key)
                vols.append(vol)

        t0 = time.time()

        # Initialize registration object
        reg = pirt.reg.GravityRegistration(*vols)

        reg.params.mass_transforms = 2  # 2nd order (Laplacian) triggers more at lines
        reg.params.speed_factor = 1.0
        reg.params.deform_wise = 'groupwise'  # groupwise!
        reg.params.mapping = 'backward'
        reg.params.deform_limit = 1.0
        reg.params.final_scale = 1.0  # We might set this a wee bit lower than 1 (but slower!)
        reg.params.scale_sampling = 16
        reg.params.final_grid_sampling = 20
        reg.params.grid_sampling_factor = 0.5

        # Go!
        reg.register(verbose=1)

        t1 = time.time()
        print('Registration completed, which took %1.2f min.' %
              ((t1 - t0) / 60))

        # Store registration result

        from visvis import ssdf

        # Create struct

        s2 = vv.ssdf.new()
        N = len(vols)
        for key in dir(s):
            if key.startswith('meta'):
                s2[key] = s[key]
        s2.origin = s.origin
        s2.stenttype = s.stenttype
        s2.croprange = s.croprange

        # Obtain deform fields
        for i in range(N):
            fields = [field for field in reg.get_deform(i).as_backward()]
            phase = phases[i][3:]
            s2['deform%s' % phase] = fields
        s2.sampling = s2['deform%s' %
                         phase][0].sampling  # Sampling of deform is different!
        s2.originDeforms = s2['deform%s' %
                              phase][0].origin  # But origin is zero
        s2.params = reg.params

        # Save
        filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'deforms')
        ssdf.save(os.path.join(basedir, ptcode, filename), s2)
        print("deforms saved to disk.")

        #============================================================================
        # Store averaged volume, where the volumes are registered

        #from visvis import ssdf

        # Create average volume from *all* volumes deformed to the "center"
        N = len(reg._ims)
        mean_vol = np.zeros(reg._ims[0].shape, 'float64')
        for i in range(N):
            vol, deform = reg._ims[i], reg.get_deform(i)
            mean_vol += deform.as_backward().apply_deformation(vol)
        mean_vol *= 1.0 / N

        # Create struct
        s_avg = ssdf.new()
        for key in dir(s):
            if key.startswith('meta'):
                s_avg[key] = s[key]
        s_avg.sampling = s.vol0.sampling  # z, y, x after interpolation
        s_avg.origin = s.origin
        s_avg.stenttype = s.stenttype
        s_avg.croprange = s.croprange
        s_avg.vol = mean_vol.astype('float32')
        s_avg.params = s2.params

        fig1 = vv.figure(1)
        vv.clf()
        fig1.position = 0, 22, 1366, 706
        a1 = vv.subplot(111)
        a1.daspect = 1, 1, -1
        renderstyle = 'mip'
        a1b = vv.volshow(s_avg.vol, clim=(0, 2000), renderStyle=renderstyle)
        #a1b.isoThreshold = 600
        vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z')
        vv.title('Average volume of %s phases (%s) (resized data)' %
                 (len(phases), renderstyle))

        # Save
        avg = 'avgreg'
        filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, avg)
        ssdf.save(os.path.join(basedir, ptcode, filename), s_avg)
        print("avgreg saved to disk.")

        t1 = time.time()
        print('Registration completed, which took %1.2f min.' %
              ((t1 - t0) / 60))
コード例 #50
0
    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)
コード例 #51
0
    cc = pirt.get_cubic_spline_coefs(tt[i], type)
    vv0[i] = cc[0]
    vv1[i] = cc[1]
    vv2[i] = cc[2]
    vv3[i] = cc[3]
    vvt[i] = sum(cc)

# Interpolate (0 means Cardinal with tension 0)
samples = np.arange(0,len(data)-1,0.05, dtype=np.float32) 
values1 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 'linear')
values2 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 'basis')
values3 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 0)  


# Visualize
fig = vv.figure(1); vv.clf()
fig.position = 57.00, 45.00,  948.00, 969.00

vv.subplot(211)
vv.title('The basis functions for the %s spline' % type)
vv.plot(tt, vv0, lc='r')
vv.plot(tt, vv1, lc='g')
vv.plot(tt, vv2, lc='b')
vv.plot(tt, vv3, lc='m')
vv.plot(tt, vvt, lc='k', ls='--')

vv.subplot(212)
vv.plot(range(len(data)), data, ms='.', ls='')
vv.plot(samples, values1, lc='r')
vv.plot(samples, values2, lc='g')
vv.plot(samples, values3, lc='b', lw=3)
コード例 #52
0
    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)
コード例 #53
0
ファイル: boxplot.py プロジェクト: chiluf/visvis.dev
    
    @vv.misc.PropWithDraw
    def whiskers():
        """ Get/Set the style of the whiskers. 
        """
        def fget(self):
            return self._boxes[0]._whiskers
        def fset(self, value):
            for box in self._boxes:
                box.SetWhiskers(value)
        return locals()


if __name__ == '__main__':
    
    vv.figure(1); vv.clf()
    a = vv.gca()
    d1 = np.random.normal(1, 4, (1000,1000))
    d2 = np.random.normal(2, 3, (20,))
    d3 = np.random.uniform(-1, 3, (100,))
    d4 = [1,2,1,2.0, 8, 2, 3, 1, 2, 2, 3, 2, 2.1, 8, 8, 8, 8, 8,  1.2, 1.3, 0, 0, 1.5, 2]
    
    b = boxplot((d1,d2,d3, d4), width=0.8, whiskers='violin')
    ##
    dd = d4
    stat = StatData(dd)
    bins1, values1 = stat.histogram_np(normed=True)
    bins2, values2 = stat.histogram()
    bins3, values3 = stat.kde(     )
    vv.figure(2); vv.clf()    
    vv.bar(bins2, values2)#, lc='r', ms='.', mc='r')
コード例 #54
0
genres=pandas.DataFrame(all_by_week['BoxOffice'].mean()/norm1)
genres.columns=['All Genres']
genres=genres.join(fantasy_by_week['BoxOffice'].mean()/norm2)
genres.columns=['All Genres','Fantasy']
genres=genres.join(animation_by_week['BoxOffice'].mean()/norm3)
genres.columns=['All Genres','Fantasy','Animation']
genres=genres.join(romance_by_week['BoxOffice'].mean()/norm4)
genres.columns=['All Genres','Fantasy','Animation','Romance']

genres=genres.fillna(0)

columns_name = ['All Genres','Fantasy','Animation','Romance']
genres.columns = [ 0, 4, 8, 12]

x, y, z = genres.stack().reset_index().values.T
#print  genres.stack().reset_index().values.T  #debug
#print genres#debug

app = vv.use()
f = vv.clf()
a = vv.cla()
plot =vv.bar3(x, y, z)
plot.colors = ["b","g","y","r"] * 53
a.axis.xLabel = 'Week #'
a.axis.yTicks = dict(zip(genres.columns, columns_name))
a.axis.zLabel = 'Avg BoxOffice (Aribitrary Units)'
app.Run()



コード例 #55
0
except FileNotFoundError:
    s2 = loadvol(basedir, ptcode, ctcode, 'ring', staticref)
vol = s2.vol

s3 = loadvol(basedir, ptcode, ctcode, cropname, 'phases')
vol0ori = s3.vol0

# todo: backward/forward based on how deforms were obtained??
# deforms was obtained as backward, from original phases to mean volume avgreg
deform = pirt.DeformationFieldBackward(deforms[0])
# vol2 = pirt.interp.deform_backward(vol, deforms[0]) # te low level, gebruikt awarp niet
vol2 = deform.inverse().as_backward().apply_deformation(
    vol0ori)  # gebruikt pirt deformation.py

vv.figure(1)
vv.clf()
a1 = vv.subplot(131)
t1 = vv.volshow(vol)
a1.daspect = (1, 1, -1)
vv.title('vol average of cardiac cycle')
# vv.figure(2); vv.clf()
a2 = vv.subplot(132)
t2 = vv.volshow(vol2)
a2.daspect = (1, 1, -1)
vv.title('vol 0 deformed to avg volume')
# vv.figure(3); vv.clf()
a3 = vv.subplot(133)
t3 = vv.volshow2((vol2 - vol), clim=(-500, 500))
a3.daspect = (1, 1, -1)
vv.title('difference')
コード例 #56
0
ファイル: _show_model.py プロジェクト: almarklein/stentseg
    def __init__(self,
                 ptcode,
                 ctcode,
                 basedir,
                 showVol='mip',
                 meshWithColors=False,
                 motion='amplitude',
                 clim2=(0, 2)):
        """
        Script to show the stent model. [ nellix]
        """

        import os
        import pirt
        import visvis as vv

        from stentseg.utils.datahandling import select_dir, loadvol, loadmodel
        from pirt.utils.deformvis import DeformableTexture3D, DeformableMesh
        from stentseg.stentdirect.stentgraph import create_mesh
        from stentseg.stentdirect import stentgraph
        from stentseg.utils.visualization import show_ctvolume
        from stentseg.motion.vis import create_mesh_with_abs_displacement
        import copy
        from stentseg.motion.dynamic import incorporate_motion_nodes, incorporate_motion_edges
        from lspeas.utils.ecgslider import runEcgSlider
        from stentseg.utils import _utils_GUI

        import numpy as np

        cropname = 'prox'
        # params
        nr = 1
        # motion = 'amplitude'  # amplitude or sum
        dimension = 'xyz'
        showVol = showVol  # MIP or ISO or 2D or None
        clim0 = (0, 2000)
        # clim2 = (0,2)
        motionPlay = 9, 1  # each x ms, a step of x %

        s = loadvol(basedir, ptcode, ctcode, cropname, what='deforms')
        m = loadmodel(basedir, ptcode, ctcode, cropname,
                      'centerline_total_modelavgreg_deforms')
        v = loadmodel(basedir,
                      ptcode,
                      ctcode,
                      cropname,
                      modelname='centerline_total_modelvesselavgreg_deforms')
        s2 = loadvol(basedir, ptcode, ctcode, cropname, what='avgreg')
        vol_org = copy.deepcopy(s2.vol)
        s2.vol.sampling = [
            vol_org.sampling[1], vol_org.sampling[1], vol_org.sampling[2]
        ]
        s2.sampling = s2.vol.sampling
        vol = s2.vol

        # merge models into one for dynamic visualization
        model_total = stentgraph.StentGraph()
        for key in dir(m):
            if key.startswith('model'):
                model_total.add_nodes_from(
                    m[key].nodes(data=True))  # also attributes
                model_total.add_edges_from(m[key].edges(data=True))
        for key in dir(v):
            if key.startswith('model'):
                model_total.add_nodes_from(
                    v[key].nodes(data=True))  # also attributes
                model_total.add_edges_from(v[key].edges(data=True))

        # Load deformations (forward for mesh)
        deformkeys = []
        for key in dir(s):
            if key.startswith('deform'):
                deformkeys.append(key)
        deforms = [s[key] for key in deformkeys]
        deforms = [[field[::2, ::2, ::2] for field in fields]
                   for fields in deforms]

        # These deforms are forward mapping. Turn into DeformationFields.
        # Also get the backwards mapping variants (i.e. the inverse deforms).
        # The forward mapping deforms should be used to deform meshes (since
        # the information is used to displace vertices). The backward mapping
        # deforms should be used to deform textures (since they are used in
        # interpolating the texture data).
        deforms_f = [pirt.DeformationFieldForward(*f) for f in deforms]
        deforms_b = [f.as_backward() for f in deforms_f]

        # Create mesh
        if meshWithColors:
            try:
                modelmesh = create_mesh_with_abs_displacement(model_total,
                                                              radius=0.7,
                                                              dim=dimension,
                                                              motion=motion)
            except KeyError:
                print('Centerline model has no pathdeforms so we create them')
                # use unsampled deforms
                deforms2 = [s[key] for key in deformkeys]
                # deforms as backward for model
                deformsB = [
                    pirt.DeformationFieldBackward(*fields)
                    for fields in deforms2
                ]
                # set sampling to original
                # for i in range(len(deformsB)):
                #         deformsB[i]._field_sampling = tuple(s.sampling)
                # not needed because we use unsampled deforms
                # Combine ...
                incorporate_motion_nodes(model_total, deformsB, s2.origin)
                convert_paths_to_PointSet(model_total)
                incorporate_motion_edges(model_total, deformsB, s2.origin)
                convert_paths_to_ndarray(model_total)
                modelmesh = create_mesh_with_abs_displacement(model_total,
                                                              radius=0.7,
                                                              dim=dimension,
                                                              motion=motion)
        else:
            modelmesh = create_mesh(model_total, 0.7, fullPaths=True)

        ## Start vis
        f = vv.figure(nr)
        vv.clf()
        if nr == 1:
            f.position = 8.00, 30.00, 944.00, 1002.00
        else:
            f.position = 968.00, 30.00, 944.00, 1002.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 = vv.volshow(vol, clim=clim0, renderStyle=showVol, axes=a)
        vv.xlabel('x (mm)')
        vv.ylabel('y (mm)')
        vv.zlabel('z (mm)')
        if meshWithColors:
            if dimension == 'xyz':
                dim = '3D'
            vv.title(
                'Model for chEVAS %s  (color-coded %s of movement in %s in mm)'
                % (ptcode[8:], motion, dim))
        else:
            vv.title('Model for chEVAS %s' % (ptcode[8:]))

        colorbar = True
        # Create deformable mesh
        dm = DeformableMesh(a, modelmesh)  # in x,y,z
        dm.SetDeforms(*[list(reversed(deform))
                        for deform in deforms_f])  # from z,y,x to x,y,z
        if meshWithColors:
            dm.clim = clim2
            dm.colormap = vv.CM_JET  #todo: use colormap Viridis or Magma as JET is not linear (https://bids.github.io/colormap/)
            if colorbar:
                vv.colorbar()
            colorbar = False
        else:
            dm.faceColor = 'g'

        # Run mesh
        a.SetLimits()
        # a.SetView(viewringcrop)
        dm.MotionPlay(motionPlay[0],
                      motionPlay[1])  # (10, 0.2) = each 10 ms do a step of 20%
        dm.motionSplineType = 'B-spline'
        dm.motionAmplitude = 0.5

        ## run ecgslider
        ecg = runEcgSlider(dm, f, a, motionPlay)
コード例 #57
0
    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) )
        #===============================================================================
コード例 #58
0
FIG1 = False


## Load all rings of the limb
for i in nrs:
    ring = 'ringR%s' %(i)
    filename = '%s_%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'model'+what,ring)
    s["ringR" + str(i)] = ssdf.load(os.path.join(basedir1, filename))


## Visualize centerlines rings
s2 = loadmodel(targetdir2, ptcode, ctcode, cropname, modelname='stentseedsavgreg')
pmodel = points_from_nodes_in_graph(s2.model)
if FIG1 == True:
    f = vv.figure(1); vv.clf()
    f.position = 709.00, 30.00,  1203.00, 1008.00
    a1 = vv.subplot(121)
    show_ctvolume(s.vol, None, showVol=showVol, clim=clim0, isoTh=isoTh, removeStent=False)
    label = pick3d(vv.gca(), s.vol)
    a1.axis.visible = showAxis
    a1.daspect = 1,1,-1 
    
    a2 = vv.subplot(122)
    vv.plot(pmodel, ms='.', ls='', alpha=0.2, mw = 2) # stent seed points
    for i in nrs:  
        pp = s["ringR" + str(i)].ringpoints
        vv.plot(pp[0],pp[1],pp[2], ms='.', ls='', mw=3, mc='c')
    a2.axis.visible = showAxis
    a2.daspect = 1,1,-1 
コード例 #59
0
    def __init__(self,
                 dirsave,
                 ptcode,
                 ctcode,
                 cropname,
                 s,
                 what='phases',
                 axes=None,
                 **kwargs):
        """ s is struct from loadvol
        """

        self.fig = vv.figure(1)
        vv.clf()
        self.fig.position = 0.00, 29.00, 1680.00, 973.00
        self.defaultzoom = 0.025  # check current zoom with foo.ax.GetView()
        self.what = what
        self.ptcode = ptcode
        self.dirsave = dirsave
        self.ctcode = ctcode
        self.cropname = cropname
        if self.what == 'phases':
            self.phase = 0
        else:
            self.phase = self.what  # avgreg
        # self.vol = s.vol0
        self.s = s  # s with vol(s)
        self.s_landmarks = vv.ssdf.new()
        self.graph = stentgraph.StentGraph()
        self.points = []  # selected points
        self.nodepoints = []
        self.pointindex = 0  # for selected points
        try:
            self.vol = s.vol0  # when phases
        except AttributeError:
            self.vol = s.vol  # when avgreg

        self.ax = vv.subplot(121)
        self.axref = vv.subplot(122)

        self.label = DrawModelAxes(self.vol,
                                   ax=self.ax)  # label of clicked point
        self.axref.bgcolor = 0, 0, 0
        self.axref.visible = False

        # create axis for buttons
        a_select = vv.Wibject(self.ax)  # on self.ax or fig?
        a_select.position = 0.55, 0.7, 0.6, 0.5  # x, y, w, h

        # Create text objects
        self._labelcurrentIndexT = vv.Label(a_select)  # for text title
        self._labelcurrentIndexT.position = 125, 180
        self._labelcurrentIndexT.text = ' Total selected ='
        self._labelcurrentIndex = vv.Label(a_select)
        self._labelcurrentIndex.position = 225, 180

        # Create Select button
        self._select = False
        self._butselect = vv.PushButton(a_select)
        self._butselect.position = 10, 150
        self._butselect.text = 'Select'

        # Create Back button
        self._back = False
        self._butback = vv.PushButton(a_select)
        self._butback.position = 125, 150
        self._butback.text = 'Undo'

        # Create Next/Save button
        self._finished = False
        self._butclose = vv.PushButton(a_select)
        self._butclose.position = 10, 230
        self._butclose.text = 'Next/Save'

        # # Create Save landmarks button
        # self._save = False
        # self._butsave = vv.PushButton(a_select)
        # self._butsave.position = 125,230
        # self._butsave.text = 'Save|Finished'

        # Create Reset-View button
        self._resetview = False
        self._butresetview = vv.PushButton(a_select)
        self._butresetview.position = 10, 180
        self._butresetview.text = 'Default Zoom'  # back to default zoom

        # bind event handlers
        self.fig.eventClose.Bind(self._onFinish)
        self._butclose.eventPress.Bind(self._onFinish)
        self._butselect.eventPress.Bind(self._onSelect)
        self._butback.eventPress.Bind(self._onBack)
        self._butresetview.eventPress.Bind(self._onView)
        # self._butsave.eventPress.Bind(self._onSave)

        self._updateTextIndex()
        self._updateTitle()
コード例 #60
0
    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)