Example #1
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()] )
 def draw_arcs(ax, level, color=(1, 1, 0)):
     arcs = mesh.get_arcs()
     for arc in arcs:
         Y, X = np.transpose(arc)
         Z = np.ones(len(X)) * level
         pp = Pointset(np.transpose([X, Y, Z]))
         vv.plot(pp, lw=1, lc=color, alpha=0.5, ls='-', mew=0, axes=ax)
Example #3
0
    def draw( self ):
            """Draw data."""
            if len(self.fitResults) == 0:
                return
            
            # Make sure our figure is the active one
            vv.figure(self.fig.nr)
            
            if not hasattr( self, 'subplot1' ):
                self.subplot1 = vv.subplot(211)
                #self.subplot1.position = (30, 2, -32, -32)
                self.subplot2 = vv.subplot(212)
                #self.subplot1.position = (30, 2, -32, -32)

            

            a, ed = numpy.histogram(self.fitResults['tIndex'], self.Size[0]/6)
            print((float(numpy.diff(ed[:2]))))

            self.subplot1.MakeCurrent()
            vv.cla()
            vv.plot(ed[:-1], a/float(numpy.diff(ed[:2])), lc='b', lw=2)
            #self.subplot1.set_xticks([0, ed.max()])
            #self.subplot1.set_yticks([0, numpy.floor(a.max()/float(numpy.diff(ed[:2])))])
            self.subplot2.MakeCurrent()
            vv.cla()
            #cs =
            csa = numpy.cumsum(a)
            vv.plot(ed[:-1], csa/float(csa[-1]), lc='g', lw=2)
            #self.subplot2.set_xticks([0, ed.max()])
            #self.subplot2.set_yticks([0, a.sum()])

            self.fig.DrawNow()
            self.subplot1.position = (20, 2, -22, -32)
            self.subplot2.position = (20, 2, -22, -32)
Example #4
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')
Example #5
0
def compareGraphsVisually(graph1, graph2, fig=None):
    """ compareGraphsVisually(graph1, graph2, fig=None)
    Show the two graphs together in a figure. Matched nodes are
    indicated by lines between them.
    """
    
    # Get figure
    if isinstance(fig,int):
        fig = vv.figure(fig)
    elif fig is None:
        fig = vv.figure()
    
    # Prepare figure and axes
    fig.Clear()
    a = vv.gca()
    a.cameraType = '3d'; a.daspectAuto = False
    
    # Draw both graphs
    graph1.Draw(lc='b', mc='b')
    graph2.Draw(lc='r', mc='r')
    
    # Set the limits
    a.SetLimits()
    
    # Make a line from the edges
    pp = Pointset(3)
    for node in graph1:
        if hasattr(node, 'match') and node.match is not None:
            pp.append(node); pp.append(node.match)
    
    # Plot edges
    vv.plot(pp, lc='g', ls='+')
Example #6
0
 def on_down(self, event):
     
     if event.button != 1:
         return False        
     if not vv.KEY_SHIFT in event.modifiers:
         return False
     
     # Store location
     self._active = Point(event.x2d, event.y2d)
     
     # Clear any line object
     for l in self._lines:
         l.Destroy()
     
     # Create line objects
     tmp = Pointset(2)
     tmp.append(self._active)
     tmp.append(self._active)
     l1 = vv.plot(tmp, lc='g', lw='3', axes=self._a2, axesAdjust=0)
     l2 = vv.plot(tmp[:1], ls='', ms='.', mc='g', axes=self._a2, axesAdjust=0)
     self._lines = [l1, l2]
     
     # Draw
     self._a2.Draw()
     
     # Prevent dragging by indicating the event needs no further handling
     return True
Example #7
0
def show_surface_and_vol(vol,
                         pp_isosurface,
                         showVol='MIP',
                         clim=(-200, 1000),
                         isoTh=300,
                         climEditor=True):
    """ Show the generated isosurface in original volume
    """
    f = vv.figure()
    ax = vv.gca()
    ax.daspect = 1, 1, -1
    ax.axis.axisColor = 1, 1, 1
    ax.bgcolor = 0, 0, 0
    # show vol and iso vertices
    show_ctvolume(vol,
                  showVol=showVol,
                  isoTh=isoTh,
                  clim=clim,
                  climEditor=climEditor)
    label = pick3d(vv.gca(), vol)
    vv.plot(pp_isosurface, ms='.', ls='', mc='r', alpha=0.2, mw=4)
    a = vv.gca()
    f.eventKeyDown.Bind(lambda event: _utils_GUI.ViewPresets(event, [a]))
    print('------------------------')
    print('Use keys 1, 2, 3, 4 and 5 for preset anatomic views')
    print('Use v for a default zoomed view')
    print('Use x to show and hide axis')
    print('------------------------')

    vv.xlabel('x (mm)')
    vv.ylabel('y (mm)')
    vv.zlabel('z (mm)')

    return label
Example #8
0
    def DoAction(self):
        """
		This method is affiliated to the method <self.SartAction>
		"""
        ####################################################
        #
        # Zak add you code here
        # e.g., in what follows we just acquire spectra
        #
        ####################################################

        # If you want to apply some radom phase maske then uncomment the following:
        #amplitude_mask = self.PulseShaper.GetZeroMask() + 1
        #phase_mask = np.random.rand(max_amplitude_mask.size)
        #self.PulseShaper.SetMasks(amplitude_mask, phase_mask)

        # Getting spectrum
        spectrum = self.Spectrometer.AcquiredData()

        # Plot the spectra
        visvis.gca().Clear()
        visvis.plot(self.wavelengths, spectrum)
        visvis.xlabel("wavelength (nm)")
        visvis.ylabel("counts")
        visvis.title("Spectrum from radom pulse shape")
        self.fig.DrawNow()

        # Going to the next iteration
        if self._continue_action:
            wx.CallAfter(self.DoAction)
Example #9
0
def compareGraphsVisually(graph1, graph2, fig=None):
    """ compareGraphsVisually(graph1, graph2, fig=None)
    Show the two graphs together in a figure. Matched nodes are
    indicated by lines between them.
    """
    
    # Get figure
    if isinstance(fig,int):
        fig = vv.figure(fig)
    elif fig is None:
        fig = vv.figure()
    
    # Prepare figure and axes
    fig.Clear()
    a = vv.gca()
    a.cameraType = '3d'; a.daspectAuto = False
    
    # Draw both graphs
    graph1.Draw(lc='b', mc='b')
    graph2.Draw(lc='r', mc='r')
    
    # Set the limits
    a.SetLimits()
    
    # Make a line from the edges
    pp = Pointset(3)
    for node in graph1:
        if hasattr(node, 'match') and node.match is not None:
            pp.append(node); pp.append(node.match)
    
    # Plot edges
    vv.plot(pp, lc='g', ls='+')
Example #10
0
 def __init__(self):
     
     # Init visualization
     fig = vv.figure(102); vv.clf()
     a = vv.gca()
     
     # Init points
     pp = Pointset(2)
     pp.append(14,12)
     pp.append(12,16)
     pp.append(16,16)
     self._pp = vv.plot(pp, ls='', ms='.', mw=10, mc='g')
     
     # Init line representing the circle
     self._cc = vv.plot(pp, lc='r', lw=2, ms='.', mw=5, mew=0, mc='r')
     
     # Set limits
     a.SetLimits((0,32), (0,32))
     a.daspectAuto = False
     
     # Init object being moved
     self._movedPoint = None
     
     # Enable callbacks
     self._pp.hitTest = True
     self._pp.eventMouseDown.Bind(self.OnDown)
     self._pp.eventMouseUp.Bind(self.OnUp)
     a.eventMotion.Bind(self.OnMotion)
     a.eventDoubleClick.Bind(self.OnDD)
     
     # Start
     self.Apply()
Example #11
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')
Example #12
0
    def draw(self):
        """Draw data."""
        if len(self.fitResults) == 0:
            return

        # Make sure our figure is the active one
        vv.figure(self.fig.nr)

        if not hasattr(self, 'subplot1'):
            self.subplot1 = vv.subplot(211)
            #self.subplot1.position = (30, 2, -32, -32)
            self.subplot2 = vv.subplot(212)
            #self.subplot1.position = (30, 2, -32, -32)

        a, ed = numpy.histogram(self.fitResults['tIndex'], self.Size[0] / 6)
        print((float(numpy.diff(ed[:2]))))

        self.subplot1.MakeCurrent()
        vv.cla()
        vv.plot(ed[:-1], a / float(numpy.diff(ed[:2])), lc='b', lw=2)
        #self.subplot1.set_xticks([0, ed.max()])
        #self.subplot1.set_yticks([0, numpy.floor(a.max()/float(numpy.diff(ed[:2])))])
        self.subplot2.MakeCurrent()
        vv.cla()
        #cs =
        csa = numpy.cumsum(a)
        vv.plot(ed[:-1], csa / float(csa[-1]), lc='g', lw=2)
        #self.subplot2.set_xticks([0, ed.max()])
        #self.subplot2.set_yticks([0, a.sum()])

        self.fig.DrawNow()
        self.subplot1.position = (20, 2, -22, -32)
        self.subplot2.position = (20, 2, -22, -32)
Example #13
0
    def show(self, axes=None, axesAdjust=True, showGrid=True):
        """ show(axes=None, axesAdjust=True, showGrid=True)
        
        For 2D grids, illustrates the deformation and the knots of the grid.
        A grid image is made that is deformed and displayed in the given 
        (or current) axes. By default the positions of the underlying knots 
        are also shown using markers.
        Returns the texture object of the grid image.
        
        Requires visvis.
        
        """

        import visvis as vv

        # Show grid using base method
        t = Deformation.show(self, axes, axesAdjust)

        if showGrid:

            # Get points for all knots
            pp = PointSet(2)
            for gy in range(self.grid_shape[0]):
                for gx in range(self.grid_shape[1]):
                    x = (gx - 1) * self.grid_sampling
                    y = (gy - 1) * self.grid_sampling
                    pp.append(x, y)

            # Draw
            vv.plot(pp, ms='.', mc='g', ls='', axes=axes, axesAdjust=0)

        # Done
        return t
    def ScanVoltage(self):
        """
		Using the iterator <self.scan_pixel_voltage_pair> record the spectral response 
		by applying the voltages
		"""
        # Pause calibration, if user requested
        try:
            if self.pause_calibration: return
        except AttributeError:
            return

        try:
            param = self.scan_pixel_voltage_pair.next()
            self.PulseShaper.SetUniformMasks(*param)

            # Getting spectrum
            spectrum = self.Spectrometer.AcquiredData()
            # Save the spectrum
            try:
                self.SpectraGroup["voltages_%d_%d" % param] = spectrum
            except RuntimeError:
                print "There was RuntimeError while saving scan voltages_%d_%d" % param

            # Plot the spectra
            visvis.gca().Clear()

            visvis.plot(self.wavelengths, spectrum)
            visvis.xlabel("wavelength (nm)")
            visvis.ylabel("counts")

            # Scanning progress info
            self.scanned += 1.
            percentage_completed = 100. * self.scanned / self.scan_length
            seconds_left = (time.clock() - self.initial_time) * (
                100. / percentage_completed - 1.)
            # convert to hours:min:sec
            m, s = divmod(seconds_left, 60)
            h, m = divmod(m, 60)

            title_info = param + (percentage_completed, h, m, s)
            visvis.title(
                "Scanning spectrum by applying voltages %d/%d. Progress: %.1f%% completed. Time left: %d:%02d:%02d."
                % title_info)

            self.fig.DrawNow()

            # Measure the next pair
            wx.CallAfter(self.ScanVoltage)
        except StopIteration:
            # Perform processing of the measured data
            wx.CallAfter(self.ExtractPhaseFunc,
                         filename=self.calibration_file.filename)
            # All voltages are scanned
            self.StopAllJobs()
            # Sop using the shaper
            self.PulseShaper.StopDevice()
Example #15
0
    def draw(self,
             mc='b',
             lc='g',
             mw=7,
             lw=0.6,
             alpha=0.5,
             axes=None,
             simple=False):
        """ Draw in visvis.
        """

        # we can only draw if we have any nodes
        if not self.number_of_nodes():
            return

        # Convert nodes to Poinset
        ppn = PointSet(3)
        for n in self.nodes_iter():
            ppn.append(*n)

        # Convert connections to Pointset
        ppe = PointSet(3)
        if simple:
            # Edges only
            for n1, n2 in self.edges_iter():
                ppe.append(*n1)
                ppe.append(*n2)
        else:
            # Paths
            for n1, n2 in self.edges_iter():
                path = self.edge[n1][n2]['path']
                ppe.append(path[0])
                for p in path[1:-1]:
                    ppe.append(p)
                    ppe.append(p)
                ppe.append(path[-1])

        # Plot markers (i.e. nodes)
        vv.plot(ppn,
                ms='o',
                mc=mc,
                mw=mw,
                ls='',
                alpha=alpha,
                axes=axes,
                axesAdjust=False)

        # Plot lines
        vv.plot(ppe,
                ls='+',
                lc=lc,
                lw=lw,
                ms='',
                alpha=alpha,
                axes=axes,
                axesAdjust=False)
Example #16
0
    def set_plot(self, spectrum):
        self.clear_plots()

        total = len(spectrum)
        count = 0.
        for _time, sweep in spectrum.items():
            if self.settings.fadeScans:
                alpha = (count + 1) / total
            vv.plot(sweep.keys(), sweep.values(), lw=1., alpha=alpha)
            count += 1
Example #17
0
    def set_plot(self, spectrum):
        self.clear_plots()

        total = len(spectrum)
        count = 0.
        for _time, sweep in spectrum.items():
            if self.settings.fadeScans:
                alpha = (count + 1) / total
            vv.plot(sweep.keys(), sweep.values(), lw=1., alpha=alpha)
            count += 1
Example #18
0
    def vv_plot_path(self, discretized=True, color='r'):
        if not visvis_avail:
            print("plot path works only with visvis module")
            return

        if discretized:
            p = self.discretized_path
        else:
            p = self.path

        vv.plot(p, ms='x', mc=color, mw='2', ls='-', mew=0)
Example #19
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()
     
     # Plot
     vv.plot([1,2,3,1,6])
     vv.legend(['this is a line'])        
 def plot_point_set(self, new_point, color, length, i=False):
     points = self.points_i if i else self.points
     # appending new point and drop old if window is full
     points[0].append(new_point[0])
     points[1].append(new_point[1])
     points[0] = points[0][length:]
     points[1] = points[1][length:]
     vv.plot(points[0], points[1], lw=0, mw=1, ms='.', mc=color, mec=color)
     if i:
         self.points_i = points
     else:
         self.points = points
Example #21
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()
     
     # Plot
     vv.plot([1,2,3,1,6])
     vv.legend(['this is a line'])        
    def DrawSpectrum(self, event):
        """
		Draw spectrum interactively
		"""
        spectrum = self.Spectrometer.AcquiredData()
        if spectrum == RETURN_FAIL: return
        # Display the spectrum
        if len(spectrum.shape) > 1:
            try:
                self.__interact_2d_spectrum__.SetData(spectrum)
            except AttributeError:
                visvis.cla()
                visvis.clf()
                # Spectrum is a 2D image
                visvis.subplot(211)
                self.__interact_2d_spectrum__ = visvis.imshow(spectrum,
                                                              cm=visvis.CM_JET)
                visvis.subplot(212)

            # Plot a vertical binning
            spectrum = spectrum.sum(axis=0)

        # Linear spectrum
        try:
            self.__interact_1d_spectrum__.SetYdata(spectrum)
        except AttributeError:
            if self.wavelengths is None:
                self.__interact_1d_spectrum__ = visvis.plot(spectrum, lw=3)
                visvis.xlabel("pixels")
            else:
                self.__interact_1d_spectrum__ = visvis.plot(self.wavelengths,
                                                            spectrum,
                                                            lw=3)
                visvis.xlabel("wavelength (nm)")
            visvis.ylabel("counts")

        if self.is_autoscaled_spectrum:
            # Smart auto-scale linear plot
            try:
                self.spectrum_plot_limits = GetSmartAutoScaleRange(
                    spectrum, self.spectrum_plot_limits)
            except AttributeError:
                self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum)

        visvis.gca().SetLimits(rangeY=self.spectrum_plot_limits)

        # Display the current temperature
        try:
            visvis.title("Temperature %d (C)" %
                         self.Spectrometer.GetTemperature())
        except AttributeError:
            pass
    def __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
Example #24
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
Example #25
0
def vis2Dfit(fitted, ptcode, ctcode, showAxis):
    """Visualize ellipse fit in 2D in current axis
    input: fitted = _fit3D output = (pp3, plane, pp3_2, e3)
    """
    from stentseg.utils import fitting
    import numpy as np
    plane,pp3_2,e3 = fitted[1],fitted[2],fitted[3]
    # endpoints axis
    x0,y0,res1,res2,phi = e3[0], e3[1], e3[2], e3[3], e3[4]
    dxax1 = np.cos(phi)*res1 
    dyax1 = np.sin(phi)*res1
    dxax2 = np.cos(phi+0.5*np.pi)*res2 
    dyax2 = np.sin(phi+0.5*np.pi)*res2
    p1ax1, p2ax1 = (x0+dxax1, y0+dyax1), (x0-dxax1, y0-dyax1)
    p1ax2, p2ax2 = (x0+dxax2, y0+dyax2), (x0-dxax2, y0-dyax2)
      
    a = vv.gca()
    vv.xlabel('x (mm)');vv.ylabel('y (mm)')
    vv.title('Ellipse fit for model %s  -  %s' % (ptcode[7:], ctcode))
    a.axis.axisColor= 0,0,0
    a.bgcolor= 0,0,0
    a.axis.visible = showAxis
    a.daspectAuto = False
    a.axis.showGrid = True
    vv.plot(pp3_2, ls='', ms='.', mc='r', mw=9)
    vv.plot(fitting.sample_ellipse(e3), lc='b', lw=2)
    vv.plot(np.array([p1ax1, p2ax1]), lc='w', lw=2) # major axis
    vv.plot(np.array([p1ax2, p2ax2]), lc='w', lw=2) # minor axis
    vv.legend('3D points projected to plane', 'Ellipse fit on projected points')
Example #26
0
def vis3Dfit(fitted, vol, model, ptcode, ctcode, showAxis, **kwargs):
    """Visualize ellipse fit in 3D with CT volume in current axis
    input: fitted = _fit3D output = (pp3, plane, pp3_2, e3)
    """
    from stentseg.utils import fitting
    import numpy as np
    pp3,plane,pp3_2,e3 = fitted[0],fitted[1],fitted[2],fitted[3]
    a = vv.gca()
    # show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh)
    show_ctvolume(vol, model, **kwargs)
    vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)')
    vv.title('Ellipse fit for model %s  -  %s' % (ptcode[7:], ctcode))
    a.axis.axisColor= 1,1,1
    a.bgcolor= 0,0,0
    a.daspect= 1, 1, -1  # z-axis flipped
    a.axis.visible = showAxis
    # For visualization, calculate 4 points on rectangle that lies on the plane
    x1, x2 = pp3.min(0)[0]-0.3, pp3.max(0)[0]+0.3
    y1, y2 = pp3.min(0)[1]-0.3, pp3.max(0)[1]+0.3
    p1 = x1, y1, -(x1*plane[0] + y1*plane[1] + plane[3]) / plane[2]
    p2 = x2, y1, -(x2*plane[0] + y1*plane[1] + plane[3]) / plane[2]
    p3 = x2, y2, -(x2*plane[0] + y2*plane[1] + plane[3]) / plane[2]
    p4 = x1, y2, -(x1*plane[0] + y2*plane[1] + plane[3]) / plane[2]
    
    vv.plot(pp3, ls='', ms='.', mc='y', mw = 10)
    vv.plot(fitting.project_from_plane(pp3_2, plane), lc='r', ls='', ms='.', mc='r', mw=9)
    #     vv.plot(fitting.project_from_plane(fitting.sample_circle(c3), plane), lc='r', lw=2)
    vv.plot(fitting.project_from_plane(fitting.sample_ellipse(e3), plane), lc='b', lw=2)
    vv.plot(np.array([p1, p2, p3, p4, p1]), lc='g', lw=2)
    #     vv.legend('3D points', 'Projected points', 'Circle fit', 'Ellipse fit', 'Plane fit')
    vv.legend('3D points', 'Projected points', 'Ellipse fit', 'Plane fit')
	def ScanVoltage (self) :
		"""
		Using the iterator <self.scan_pixel_voltage_pair> record the spectral response 
		by applying the voltages
		"""
		# Pause calibration, if user requested
		try : 
			if self.pause_calibration : return
		except AttributeError : return
				
		try :
			param = self.scan_pixel_voltage_pair.next()
			self.PulseShaper.SetUniformMasks(*param)
			
			# Getting spectrum
			spectrum = self.Spectrometer.AcquiredData() 
			# Save the spectrum
			try : self.SpectraGroup["voltages_%d_%d" % param] = spectrum
			except RuntimeError : print "There was RuntimeError while saving scan voltages_%d_%d" % param
			
			# Plot the spectra
			visvis.gca().Clear()
			
			visvis.plot (self.wavelengths, spectrum)
			visvis.xlabel("wavelength (nm)")
			visvis.ylabel("counts")
			
			# Scanning progress info
			self.scanned += 1.
			percentage_completed = 100.*self.scanned/self.scan_length
			seconds_left = ( time.clock() - self.initial_time )*(100./percentage_completed - 1.)
			# convert to hours:min:sec
			m, s = divmod(seconds_left, 60)
			h, m = divmod(m, 60)
			
			title_info = param + (percentage_completed, h, m, s)
			visvis.title ("Scanning spectrum by applying voltages %d/%d. Progress: %.1f%% completed. Time left: %d:%02d:%02d." %  title_info)
			
			self.fig.DrawNow()
			
			# Measure the next pair
			wx.CallAfter(self.ScanVoltage)
		except StopIteration :
			# Perform processing of the measured data
			wx.CallAfter(self.ExtractPhaseFunc, filename=self.calibration_file.filename)
			# All voltages are scanned
			self.StopAllJobs()
			# Sop using the shaper
			self.PulseShaper.StopDevice()
Example #28
0
 def _call_new_item(self, key, item_type, *args, **kwargs):
     if key in self.items:
         # an item with that key already exists
         # should raise an exception or warning
         pass
     else:
         # make this the current figure
         vv.figure(self.figure)
         # create a new dictionary of options for plotting
         plot_kwargs = dict()
         if 'line_width' in kwargs:
             value = kwargs.pop('line_width')
             plot_kwargs['lw'] = value
         if 'marker_width' in kwargs:
             value = kwargs.pop('marker_width')
             plot_kwargs['mw'] = value
         if 'marker_edge_width' in kwargs:
             value = kwargs.pop('marker_edge_width')
             plot_kwargs['mew'] = value
         if 'line_color' in kwargs:
             value = kwargs.pop('line_color')
             plot_kwargs['lc'] = value
         if 'marker_color' in kwargs:
             value = kwargs.pop('marker_color')
             plot_kwargs['mc'] = value
         if 'marker_edge_color' in kwargs:
             value = kwargs.pop('marker_edge_color')
             plot_kwargs['mec'] = value
         if 'line_style' in kwargs:
             value = kwargs.pop('line_style')
             plot_kwargs['ls'] = value
         if 'marker_style' in kwargs:
             value = kwargs.pop('marker_style')
             plot_kwargs['ms'] = value
         if 'adjust_axes' in kwargs:
             value = kwargs.pop('adjust_axes')
             plot_kwargs['axesAdjust'] = value
         # create the plot item
         if item_type == 'circular':
             data = pythics.lib.CircularArray(cols=2, length=kwargs['length'])
             item = vv.plot(np.array([]), np.array([]), axes=self.axes, **plot_kwargs)
         elif item_type == 'growable':
             data = pythics.lib.GrowableArray(cols=2, length=kwargs['length'])
             item = vv.plot(np.array([]), np.array([]), axes=self.axes, **plot_kwargs)
         else:
             data = np.array([])
             item = vv.plot(np.array([]), np.array([]), axes=self.axes, **plot_kwargs)
         self.items[key] = (item_type, data, item)
Example #29
0
    def __init__(self):

        # Create figure and axes
        vv.figure()
        self._a = a = vv.gca()
        vv.title("Hold mouse to draw lines. Use 'rgbcmyk' and '1-9' keys.")

        # Set axes
        a.SetLimits((0, 1), (0, 1))
        a.cameraType = "2d"
        a.daspectAuto = False
        a.axis.showGrid = True

        # Init variables needed during drawing
        self._active = None
        self._pp = Pointset(2)

        # Create null and empty line objects
        self._line1 = None
        self._line2 = vv.plot(vv.Pointset(2), ls="+", lc="c", lw="2", axes=a)

        # Bind to events
        a.eventMouseDown.Bind(self.OnDown)
        a.eventMouseUp.Bind(self.OnUp)
        a.eventMotion.Bind(self.OnMotion)
        a.eventKeyDown.Bind(self.OnKey)
Example #30
0
def _visualise_world_visvis(X, Y, Z, format="surf"):
    """
    Legacy function to produce a surface render using visvis
    :param X:
    :param Y:
    :param Z:
    :param format:
    """
    import visvis as vv

    # m2 = vv.surf(worldx[::detail], worldy[::detail], worldz[::detail])

    app = vv.use()
    # prepare axes
    a = vv.gca()
    a.cameraType = '3d'
    a.daspectAuto = False
    # print("view", a.camera.GetViewParams())
    # a.SetView(loc=(-1000,0,0))
    # a.camera.SetView(None, loc=(-1000,0,0))

    if format == "surf":
        l = vv.surf(X, Y, Z)
        a.SetLimits(rangeX=(-0.2, 0.2),
                    rangeY=(-0.5, 0.5),
                    rangeZ=(-0.5, 0),
                    margin=0.02)
    else:
        # draw points
        pp = vv.Pointset(
            np.concatenate([X.flatten(), Y.flatten(),
                            Z.flatten()], axis=0).reshape((-1, 3)))
        l = vv.plot(pp, ms='.', mc='r', mw='5', ls='', mew=0)
        l.alpha = 0.2
    app.Run()
Example #31
0
 def OnDown(self, event):
     """ Called when the mouse is pressed down in the axes.
     """
     
     # Only process left mouse button
     if event.button != 1:
         return False
     
     # Store location
     self._active = Point(event.x2d, event.y2d)
     
     # Clear temp line object
     if self._line1:
         self._line1.Destroy()
     
     # Create line objects
     tmp = Pointset(2)
     tmp.append(self._active)
     tmp.append(self._active)
     self._line1 = vv.plot(tmp, lc='r', lw='1', axes=self._a, axesAdjust=0)
     
     # Draw
     self._a.Draw()
     
     # Prevent dragging by indicating the event needs no further handling
     return True
Example #32
0
def plot_points(pp, mc='g', ms='o', mw=8, alpha=0.5, ls='', ax=None, **kwargs):
    """ Plot a point or set of points in current axis and restore current view 
    alpha 0.9 = solid; 0.1 transparant
    """
    if ax is None:
        ax = vv.gca()
    # check if pp is 1 point and not a PointSet
    if not isinstance(pp, PointSet):
        pp = np.asarray(pp)
        if pp.ndim == 1:
            p = PointSet(3)
            p.append(pp)
            pp = p
    # get view and plot
    view = ax.GetView()
    point = vv.plot(PointSet(pp),
                    mc=mc,
                    ms=ms,
                    mw=mw,
                    ls=ls,
                    alpha=alpha,
                    axes=ax,
                    **kwargs)
    ax.SetView(view)

    return point
def arrows(points, vectors, head=(0.2, 1.0), **kwargs):

    if 'ls' in kwargs:
        raise ValueError('Cannot set line style for arrows.')

    ppd = vv.Pointset(pp.ndim)
    for i in range(len(points)):

        p1 = points[i]  # source point
        v1 = vectors[i]  # THE vector
        v1_norm = v1.norm()
        p2 = p1 + v1  # destination point
        if v1_norm:
            pn = v1.normal() * v1_norm * abs(head[0])  # normal vector
        else:
            pn = vv.Point(0, 0)
        ph1 = p1 + v1 * head[1]
        ph2 = ph1 - v1 * head[0]

        # Add stick
        ppd.append(p1)
        ppd.append(p2)
        # Add arrowhead
        ppd.append(ph1)
        ppd.append(ph2 + pn)
        ppd.append(ph1)
        ppd.append(ph2 - pn)

    return vv.plot(ppd, ls='+', **kwargs)
Example #34
0
def kde(data, bins=None, kernel=None, **kwargs):
    """ kde(a, bins=None, range=None, **kwargs)
    
    Make a kernerl density estimate plot of the data. This is like a 
    histogram, but produces a smoother result, thereby better represening
    the probability density function.
    
    See the vv.StatData for more statistics on data.
    
    Parameters
    ----------
    a : array_like
        The data to calculate the historgam of.
    bins : int (optional)
        The number of bins. If not given, the best number of bins is 
        determined automatically using the Freedman-Diaconis rule.
    kernel : float or sequence (optional)
        The kernel to use for distributing the values. If a scalar is given,
        a Gaussian kernel with a sigma equal to the given number is used.
        If not given, the best kernel is chosen baded on the number of bins.
    kwargs : keyword arguments
        These are given to the plot function.
    
    """

    # Get stats
    from visvis.processing.statistics import StatData

    stats = StatData(data)

    # Get kde
    xx, values = stats.kde(bins, kernel)

    # Plot
    return vv.plot(xx, values, **kwargs)
Example #35
0
File: kde.py Project: chiluf/visvis
def kde(data, bins=None, kernel=None, **kwargs):
    """ kde(a, bins=None, range=None, **kwargs)
    
    Make a kernerl density estimate plot of the data. This is like a 
    histogram, but produces a smoother result, thereby better represening
    the probability density function.
    
    See the vv.StatData for more statistics on data.
    
    Parameters
    ----------
    a : array_like
        The data to calculate the historgam of.
    bins : int (optional)
        The number of bins. If not given, the best number of bins is 
        determined automatically using the Freedman-Diaconis rule.
    kernel : float or sequence (optional)
        The kernel to use for distributing the values. If a scalar is given,
        a Gaussian kernel with a sigma equal to the given number is used.
        If not given, the best kernel is chosen baded on the number of bins.
    kwargs : keyword arguments
        These are given to the plot function.
    
    """

    # Get stats
    from visvis.processing.statistics import StatData
    stats = StatData(data)

    # Get kde
    xx, values = stats.kde(bins, kernel)

    # Plot
    return vv.plot(xx, values, **kwargs)
Example #36
0
 def __init__(self):
     
     # Create figure and axes
     vv.figure()
     self._a = a = vv.gca()
     vv.title("Hold mouse to draw lines. Use 'rgbcmyk' and '1-9' keys.")
     
     # Set axes
     a.SetLimits((0,1), (0,1))
     a.cameraType = '2d'
     a.daspectAuto = False
     a.axis.showGrid = True
     
     # Init variables needed during drawing
     self._active = None
     self._pp = Pointset(2)
     
     # Create null and empty line objects
     self._line1 = None
     self._line2 = vv.plot(vv.Pointset(2), ls='+', lc='c', lw='2', axes=a)
     
     # Bind to events
     a.eventMouseDown.Bind(self.OnDown)
     a.eventMouseUp.Bind(self.OnUp)
     a.eventMotion.Bind(self.OnMotion)
     a.eventKeyDown.Bind(self.OnKey)
Example #37
0
    def OnDown(self, event):
        """ Called when the mouse is pressed down in the axes.
        """

        # Only process left mouse button
        if event.button != 1:
            return False

        # Store location
        self._active = Point(event.x2d, event.y2d)

        # Clear temp line object
        if self._line1:
            self._line1.Destroy()

        # Create line objects
        tmp = Pointset(2)
        tmp.append(self._active)
        tmp.append(self._active)
        self._line1 = vv.plot(tmp, lc="r", lw="1", axes=self._a, axesAdjust=0)

        # Draw
        self._a.Draw()

        # Prevent dragging by indicating the event needs no further handling
        return True
Example #38
0
def plot_progress(plots, sampler_info):

    settings = requests.get(sampler_info['settings']).json()
    lower = settings['lower']
    upper = settings['upper']

    subplt = vv.subplot(*(plots['shape'] + (1 + plots['count'], )))
    plots['count'] += 1

    # Request the training data
    training_data = requests.get(sampler_info['training_data_uri']).json()

    xres = 30
    yres = 30
    xeva, yeva = np.meshgrid(np.linspace(lower[0], upper[0], xres),
                             np.linspace(lower[1], upper[1], yres))
    Xquery = np.array([xeva.flatten(), yeva.flatten()]).T

    #Request the predictions from the server
    r = requests.get(sampler_info['pred_uri'], json=Xquery.tolist())
    r.raise_for_status()
    pred = r.json()
    pred_mean = np.array(pred['predictive_mean'])
    id_matrix = np.reshape(
        np.arange(Xquery.shape[0])[:, np.newaxis], xeva.shape)
    n, n_outputs = pred_mean.shape

    # Plot the training data and the predictions
    vol = np.zeros((n_outputs, xeva.shape[0], xeva.shape[1]))
    for x in range(xres):
        for y in range(yres):
            vol[:, x, y] = pred_mean[id_matrix[x, y]]
    plt = vv.volshow(vol, renderStyle='mip', clim=(-0.5, 1))
    plt.colormap = vv.CM_JET
    subplt.axis.xLabel = 'input 1'
    subplt.axis.yLabel = 'input 2'
    subplt.axis.zLabel = 'model output'
    a = ((np.asarray(training_data['X']) - np.array([np.min(xeva),
          np.min(yeva)])[np.newaxis, :]) / np.array([np.max(xeva) -
          np.min(xeva), np.max(yeva)-np.min(yeva)])[np.newaxis, :])  \
          * np.array(xeva.shape)  # NOQA
    n = a.shape[0]
    a = np.hstack((a, (n_outputs + 0.01) * np.ones((n, 1))))
    pp = vv.Pointset(a)
    vv.plot(pp, ms='.', mc='w', mw='9', ls='')
Example #39
0
def showVesselMesh(vesselstl, ax=None, vesselMeshColor=(1,0,0,0.5),
    type = 1, **kwargs):
    """ plot pointcloud of mesh in ax
    type = 1 use vv.mesh; type = 2 use vv.plot
    """
    if ax is None:
        ax = vv.gca()
    if vesselstl is None:
        return
    if type == 1:
        vessel = vv.mesh(vesselstl, axes=ax, **kwargs)
        vessel.faceColor = vesselMeshColor # (1,0,0,0.5) or alpha 0.4-0.6
        return vessel
    elif type == 2:
        # get PointSet from STL 
        ppvessel = points_from_mesh(vesselstl, invertZ = False) # removes duplicates
        vv.plot(ppvessel, ms='.', ls='', mc= 'r', alpha=0.2, mw = 7, axes = ax)
        return ppvessel
Example #40
0
 def Draw(self, mc='g', lc='y', mw=7, lw=0.6, alpha=0.5, axes=None):
     """ Draw(mc='g', lc='y', mw=7, lw=0.6, alpha=0.5, axes=None)
     Draw nodes and edges. 
     """ 
     
     # We can only draw if we have any nodes
     if not len(self):
         return
     
     # Make sure there are elements in the lines list
     while len(self._lines)<2:
         self._lines.append(None)
     
     # Build node list
     if mc and mw:
         pp = Pointset(self[0].ndim)
         for p in self:
             pp.append(p)
         # Draw nodes, reuse if possible!
         l_node = self._lines[0]            
         if l_node and len(l_node._points) == len(pp):
             l_node.SetPoints(pp)
         elif l_node:
             l_node.Destroy()
             l_node = None
         if l_node is None:                
             l_node = vv.plot(pp, ls='', ms='o', mc=mc, mw=mw, 
                 axesAdjust=0, axes=axes, alpha=alpha)
             self._lines[0] = l_node
     
     # For simplicity, always redraw edges
     if self._lines[1] is not None: 
         self._lines[1].Destroy()
     
     # Build edge list
     if lc and lw:
         cc = self.GetEdges()
         # Draw edges
         pp = Pointset(self[0].ndim)
         for c in cc:            
             pp.append(c.end1); pp.append(c.end2)
         tmp = vv.plot(pp, ms='', ls='+', lc=lc, lw=lw, 
             axesAdjust=0, axes=axes, alpha=alpha)
         self._lines[1] = tmp
	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
Example #42
0
 def Draw(self, mc='g', lc='y', mw=7, lw=0.6, alpha=0.5, axes=None):
     """ Draw(mc='g', lc='y', mw=7, lw=0.6, alpha=0.5, axes=None)
     Draw nodes and edges. 
     """ 
     
     # We can only draw if we have any nodes
     if not len(self):
         return
     
     # Make sure there are elements in the lines list
     while len(self._lines)<2:
         self._lines.append(None)
     
     # Build node list
     if mc and mw:
         pp = Pointset(self[0].ndim)
         for p in self:
             pp.append(p)
         # Draw nodes, reuse if possible!
         l_node = self._lines[0]            
         if l_node and len(l_node._points) == len(pp):
             l_node.SetPoints(pp)
         elif l_node:
             l_node.Destroy()
             l_node = None
         if l_node is None:                
             l_node = vv.plot(pp, ls='', ms='o', mc=mc, mw=mw, 
                 axesAdjust=0, axes=axes, alpha=alpha)
             self._lines[0] = l_node
     
     # For simplicity, always redraw edges
     if self._lines[1] is not None: 
         self._lines[1].Destroy()
     
     # Build edge list
     if lc and lw:
         cc = self.GetEdges()
         # Draw edges
         pp = Pointset(self[0].ndim)
         for c in cc:            
             pp.append(c.end1); pp.append(c.end2)
         tmp = vv.plot(pp, ms='', ls='+', lc=lc, lw=lw, 
             axesAdjust=0, axes=axes, alpha=alpha)
         self._lines[1] = tmp
Example #43
0
    def show(self, axes=None, axesAdjust=True, showGrid=True):
        """ show(axes=None, axesAdjust=True, showGrid=True)
        
        For 2D grids, shows the field and the knots of the grid.
        The image is displayed in the given (or current) axes. By default
        the positions of the underlying knots are also shown using markers.
        Returns the texture object of the field image.
        
        Requires visvis.
        
        """
        import visvis as vv

        # Test dimensions
        if self.ndim != 2:
            raise RuntimeError('Show only works for 2D data.')

        # Get field
        field = Aarray(self.get_field(), self.field_sampling)

        # Get points for all knots
        pp = PointSet(2)
        for gy in range(self.grid_shape[0]):
            for gx in range(self.grid_shape[0]):
                x = (gx - 1) * self.grid_sampling
                y = (gy - 1) * self.grid_sampling
                pp.append(x, y)

        # Draw
        if showGrid:
            vv.plot(pp,
                    ms='.',
                    mc='g',
                    ls='',
                    axes=axes,
                    axesAdjust=axesAdjust)
            return vv.imshow(field, axes=axes)
        else:
            return vv.plot(pp,
                           ms='.',
                           mc='g',
                           ls='',
                           axes=axes,
                           axesAdjust=axesAdjust)
Example #44
0
			def draw_spectrum (event) :
				"""Timer function """
				spectrum = self.Spectrometer.AcquiredData() 
				if spectrum == RETURN_FAIL : return
				# Display the spectrum
				
				############### Take the log of spectrum ##########
				#spectrum = spectrum / float(spectrum.max())
				#np.log10(spectrum, out=spectrum)
				##############################
				
				ax = visvis.gca()
				ax.Clear()	
				visvis.plot (self.wavelengths, spectrum)
				visvis.xlabel("wavelength (nm)")
				visvis.ylabel("counts")
				
				# Display the current temperature
				visvis.title ("Temperature %d (C)" % self.Spectrometer.GetTemperature() )
    def _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'])
	def ShowSpectra_by_VaryingPixelBundle (self) :
		"""
		This method is affiliated to the method <self.VaryPixelBundle>
		"""
		# Exit if the iterator is not defined
		try : self.pixel_bundel_value_iter
		except AttributeError : return
		
		try :
			voltage = self.pixel_bundel_value_iter.next()
			
			# Set the mask for pixel bundle
			width = self.SettingsNotebook.CalibrateShaper.pixel_bundle_width.GetValue() / 2
			start_pixel_bundle = self.pixel_to_vary.GetValue()
			mask = np.copy(self.fixed_mask)
			if width:
				mask[max(start_pixel_bundle-width, 0):min(mask.size, start_pixel_bundle+width)] = voltage
			else:
				# Enforce single pixel width
				mask[min(max(start_pixel_bundle,0),mask.size)] = voltage	
			self.PulseShaper.SetMasks( mask, self.fixed_mask)
		
			# Getting spectrum
			spectrum = self.Spectrometer.AcquiredData()
		
			# Plot the spectra
			visvis.gca().Clear()
			visvis.plot (self.wavelengths, spectrum)
			visvis.xlabel("wavelength (nm)")
			visvis.ylabel("counts")
			visvis.title ("Voltage %d / %d " % (voltage, self.fixed_mask[0]) )
			self.fig.DrawNow()
			
			# Going to the next iteration
			wx.CallAfter (self.ShowSpectra_by_VaryingPixelBundle)
		except StopIteration :
			# Finish the job
			self.StopAllJobs()
Example #47
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
Example #48
0
def ginput(N=0, axes=None, ms='+', **kwargs):
    """ ginput(N=0, axes=None, ms='+', **kwargs)
    
    Graphical input: select N number of points with the mouse. 
    Returns a 2D pointset.
    
    Parameters
    ----------
    N : int
        The maximum number of points to capture. If N=0, will keep capturing
        until the user stops it. The capturing always stops when enter is
        pressed or the mouse is double clicked. In the latter case a final
        point is added.
    axes : Axes instance
        The axes to capture the points in, or the current axes if not given.
    ms : markerStyle
        The marker style to use for the points. See plot.
    
    Any other keyword arguments are passed to plot to show the selected
    points and the lines between them.
    
    """
    
    # Get axes
    if not axes:
        axes = vv.gca()
    
    # Get figure
    fig = axes.GetFigure()
    if not fig:
        return
    
    # Init pointset, helper, and line object
    line = vv.plot(Pointset(2), axes=axes, ms=ms, **kwargs)    
    pp = line._points
    ginputHelper.Start(axes, pp, N)
    
    # Enter a loop
    while ginputHelper.axes:
        fig._ProcessGuiEvents()
        time.sleep(0.1)
    
    # Remove line object and return points
    pp = Pointset(pp[:,:2])
    line.Destroy()
    return pp
Example #49
0
    def __init__(self, sampleinterval=0.1, timewindow=10.0, size=(600, 350)):
        # Data stuff
        self._interval = int(sampleinterval * 1000)
        self._bufsize = int(timewindow / sampleinterval)
        self.databuffer = collections.deque([0.0] * self._bufsize, self._bufsize)
        self.x = np.linspace(-timewindow, 0.0, self._bufsize)
        self.y = np.zeros(self._bufsize, dtype=np.float)
        # Visvis stuff
        self.app = vv.use("qt4")
        vv.title("Dynamic Plotting with VisVis")
        self.line = vv.plot(self.x, self.y, lc="b", lw=3, ms="+")
        vv.xlabel("time")
        vv.ylabel("amplitude")
        self.ax = vv.gca()

        self.timer = vv.Timer(self.app, 50, oneshot=False)
        self.timer.Bind(self.updateplot)
        self.timer.Start()
	def AnalyzeTotalFluorescence (self, event=None) :
		"""
		`analyse_button` was clicked
		"""
		# Get current settings
		settings = self.GetSettings()
	
		# Apply peak finding filter
		signal = self.peak_finders[ settings["peak_finder"] ](self.total_fluorescence)
		
		# Scale to (0,1)
		signal -= signal.min()
		signal = signal / signal.max()
		
		##########################################################################
		
		# Partition signal into segments that are above the background noise  
		#signal = gaussian_filter(total_fluorescence, sigma=0.5)
		background_cutoff = settings["background_cutoff"]
		segments = [ [] ]
		for num, is_segment in enumerate( signal > background_cutoff ) :
			if is_segment : 
				# this index is in the segment
				segments[-1].append( num )
			elif len(segments[-1]) : # this condition is not to add empty segments
				# Start new segments
				segments.append( [] )
		
		# Find peaks as weighted average of the segment
		peaks = [ np.average(self.positions[S], weights=self.total_fluorescence[S]) for S in segments if len(S) ]
		
		##########################################################################
		
		# Saving the positions
		self.chanel_positions_ctrl.SetValue( ", ".join( "%2.4f" % p for p in peaks ) )
		
		##########################################################################
		
		# Plot acquired data
		visvis.cla(); visvis.clf()
		
		visvis.plot( self.positions, signal )
		visvis.plot( peaks, background_cutoff*np.ones(len(peaks)), ls=None, ms='+', mc='r', mw=20)
		visvis.plot( [self.positions.min(), self.positions.max()], [background_cutoff, background_cutoff], lc='r', ls='--', ms=None)
		
		visvis.legend( ["measured signal", "peaks found", "background cut-off"] )
		
		visvis.ylabel( "total fluorescence") 
		visvis.xlabel( 'position (mm)')
		
		
def draw_error_ellipsoid_visvis(mu, covariance_matrix, stdev=1, z_offset=0, color_ellipsoid="g", pt_size=5):
    """
    @brief Plot the error (uncertainty) ellipsoid using a 3D covariance matrix for a given standard deviation
    @param mu: The mean vector
    @param covariance_matrix: the 3x3 covariance matrix
    @param stdev: The desire standard deviation value to draw the uncertainty ellipsoid for. Default is 1.
    """
    import visvis as vv

    # Step 1: make a unit n-sphere
    u = np.linspace(0.0, 2.0 * np.pi, 30)
    v = np.linspace(0.0, np.pi, 30)
    x_sph = np.outer(np.cos(u), np.sin(v))
    y_sph = np.outer(np.sin(u), np.sin(v))
    z_sph = np.outer(np.ones_like(u), np.cos(v))
    X_sphere = np.dstack((x_sph, y_sph, z_sph))
    # Step 2:  apply the following linear transformation to get the points of your ellipsoid (Y):
    C = np.linalg.cholesky(covariance_matrix)

    ellipsoid_pts = mu + stdev * np.dot(X_sphere, C)

    x = ellipsoid_pts[..., 0]
    y = ellipsoid_pts[..., 1]
    z = ellipsoid_pts[..., 2] + z_offset

    # plot
    ellipsoid_surf = vv.surf(x, y, z)
 # Get axes


#     ellipsoid_surf = vv.grid(x, y, z)
    ellipsoid_surf.faceShading = "smooth"
    ellipsoid_surf.faceColor = color_ellipsoid
#     ellipsoid_surf.edgeShading = "plain"
#     ellipsoid_surf.edgeColor = color_ellipsoid
    ellipsoid_surf.diffuse = 0.9
    ellipsoid_surf.specular = 0.9

    mu_pt = vv.Point(mu[0], mu[1], mu[2] + z_offset)
    pt_mu = vv.plot(mu_pt, ms='.', mc="k", mw=pt_size, ls='', mew=0, axesAdjust=True)
Example #52
0
    def viewRender(self,elevation):       
        
        
        if self.cLayer.type()==QgsMapLayer.RasterLayer: return
        x=[]
        y=[]
        z=[]
        for feat in self.cLayer.getFeatures():
           
            geom=feat.geometry()
            wkb=geom.asWkb()
            point3d = ogr.CreateGeometryFromWkb(wkb)       
          
            x.append(point3d.GetX())
            y.append(point3d.GetY())
            if elevation!='Z value' :
                z.append(feat[elevation] or 0)
            else : z.append(point3d.GetZ() or 0)
            
        print z
        f = visvis.gca()
        m = visvis.plot(x,y,z, lc='k', ls='', mc='g', mw=2, lw=2, ms='.')

        f.daspect = 1,1,20
Example #53
0
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')
Example #54
0
        """ 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')
    vv.plot(bins3, values3)#, lc='g', ms='.', mc='g')
    vv.plot(bins1, values1, lc='b', ms='.', mc='b', ls=':', mw=4)
    #print abs(bins1-bins2).sum()
Example #55
0
        print( "FPS : %.2f (%d frames in %.2f second)"
               % (frames/elapsed, frames, elapsed))
        t0, frames = t,0
    event.source.update()
    
# Run!
app.run()


if False:
    ## Evaluate measurements 
    # Measured
    ncolrow = [6,  7,   8,  9, 10, 11, 12]
    fpss    = [48, 37, 28, 23, 18, 15, 12]  # Measured earlier
    fpss    = [32, 24, 19, 15, 12, 10, 8]   # Measured later, probably added extra overhead
    # Process
    xx = [x**2 for x in ncolrow]
    yy = [1.0 / fps for fps in fpss]
    timepersubplot = [1000*y/x for x, y in zip(xx, yy)]
    # Show
    import visvis as vv
    vv.figure(1); vv.clf()
    vv.plot(xx, yy)
    vv.xlabel('number of subplots')
    vv.ylabel('timer per frame')
    #
    vv.figure(2); vv.clf()
    vv.plot(timepersubplot)
    vv.gca().SetLimits(rangeY=(0, 1.1*max(timepersubplot)))
    
    
Example #56
0
    
    """
    
    # Get axes
    if axes is None:
        axes = vv.gca()
    
    if command == 'off':
        axes.axis.visible = 0 
    elif command == 'on':
        axes.axis.visible = 1
    elif command == 'equal':
        axes.daspectAuto = 0
    elif command == 'auto':
        axes.daspectAuto = 1
    elif command == 'tight':
        axes.SetLimits()
    elif command == 'ij':
        da = [abs(tmp) for tmp in axes.daspect]
        axes.daspect = da[0], -abs(da[1]), da[2]
    elif command == 'xy':
        da = [abs(tmp) for tmp in axes.daspect]
        axes.daspect = da[0], abs(da[1]), da[2]
    else:
        raise ValueError('Unknown command in vv.axis().')


if __name__ == '__main__':
    l = vv.plot([1,2,3,1,4,0])
    vv.axis('off')
Example #57
0
#!/usr/bin/env python

import numpy as np
import visvis as vv
from visvis import Point, Pointset

app = vv.use()

# create random points
a = np.random.normal(size=(1000, 3))
pp = Pointset(a)
pp *= Point(2, 5, 1)

# prepare axes
a = vv.gca()
a.cameraType = "3d"
a.daspectAuto = False

# draw points
l = vv.plot(pp, ms=".", mc="r", mw="9", ls="", mew=0)
l.alpha = 0.1

app.Run()
Example #58
0
    # reshape, flip, and store
    im.shape = h,w,3
    im = np.flipud(im)
    
    # done
    return im
    


if __name__ == '__main__':
    import time
    
    f = vv.figure()
    a1 = vv.subplot(211)
    a2 = vv.subplot(212)
    
    vv.plot([2,3,4,2,4,3], axes=a1)
    
    for i in range(4):
        # draw and wait a bit
        f.DrawNow()
        time.sleep(1)
        # make snapshots
        im1 = getframe(f)
        im2 = getframe(a1)
        # clear and show snapshots
        a1.Clear()
        a2.Clear()
        vv.imshow(im1,axes=a1, clim=(0,1))
        vv.imshow(im2,axes=a2, clim=(0,1))