Beispiel #1
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)
Beispiel #2
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)
Beispiel #3
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')
Beispiel #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()] )
	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)
	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')
Beispiel #7
0
 def update_plot(self):
     vv.cla()
     self.surf = vv.surf(self.x,
                         self.y,
                         self.z,
                         axesAdjust=False,
                         axes=self.axes)
     self.surf.clim = self.clim
     self.surf.colormap = vv.CM_JET
	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") 
    def DrawSpectrum(self, event):
        """
		Draw spectrum interactively
		"""
        spectrum = self.Spectrometer.AcquiredData()
        if spectrum == RETURN_FAIL: return
        # Display the spectrum
        if len(spectrum.shape) > 1:
            try:
                self.__interact_2d_spectrum__.SetData(spectrum)
            except AttributeError:
                visvis.cla()
                visvis.clf()
                # Spectrum is a 2D image
                visvis.subplot(211)
                self.__interact_2d_spectrum__ = visvis.imshow(spectrum,
                                                              cm=visvis.CM_JET)
                visvis.subplot(212)

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

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

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

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

        # Display the current temperature
        try:
            visvis.title("Temperature %d (C)" %
                         self.Spectrometer.GetTemperature())
        except AttributeError:
            pass
	def AnalyzeTotalFluorescence (self, event=None) :
		"""
		`analyse_button` was clicked
		"""
		# Get current settings
		settings = self.GetSettings()
	
		# Apply peak finding filter
		signal = self.peak_finders[ settings["peak_finder"] ](self.total_fluorescence)
		
		# Scale to (0,1)
		signal -= signal.min()
		signal = signal / signal.max()
		
		##########################################################################
		
		# Partition signal into segments that are above the background noise  
		#signal = gaussian_filter(total_fluorescence, sigma=0.5)
		background_cutoff = settings["background_cutoff"]
		segments = [ [] ]
		for num, is_segment in enumerate( signal > background_cutoff ) :
			if is_segment : 
				# this index is in the segment
				segments[-1].append( num )
			elif len(segments[-1]) : # this condition is not to add empty segments
				# Start new segments
				segments.append( [] )
		
		# Find peaks as weighted average of the segment
		peaks = [ np.average(self.positions[S], weights=self.total_fluorescence[S]) for S in segments if len(S) ]
		
		##########################################################################
		
		# Saving the positions
		self.chanel_positions_ctrl.SetValue( ", ".join( "%2.4f" % p for p in peaks ) )
		
		##########################################################################
		
		# Plot acquired data
		visvis.cla(); visvis.clf()
		
		visvis.plot( self.positions, signal )
		visvis.plot( peaks, background_cutoff*np.ones(len(peaks)), ls=None, ms='+', mc='r', mw=20)
		visvis.plot( [self.positions.min(), self.positions.max()], [background_cutoff, background_cutoff], lc='r', ls='--', ms=None)
		
		visvis.legend( ["measured signal", "peaks found", "background cut-off"] )
		
		visvis.ylabel( "total fluorescence") 
		visvis.xlabel( 'position (mm)')
		
		
Beispiel #11
0
 def _Plot2(self):
     vv.figure(self.fig.nr)
     vv.clf()
     ax1f2 = vv.cla()
     ax1f2.daspect = 1,-1,1
     vv.surf(self.z)
     vv.axis('off')
     
     ax1f1 = self.fig2.add_subplot(221)
     ax1f1.imshow(self.Nx)   
     ax1f1.axis('off')
     
     ax2f1 = self.fig2.add_subplot(222)
     ax2f1.imshow(self.Ny)
     ax2f1.axis('off')
     
     ax3f1 = self.fig2.add_subplot(223)
     ax3f1.imshow(self.Nz)
     ax3f1.axis('off')
     
     ax4f1 = self.fig2.add_subplot(224)
     ax4f1.imshow(self.A, cmap='gray')
     ax4f1.axis('off')
     
     self.canvas.draw()
     if not hasattr(self, 'toolbar'):
         self.toolbar = NavigationToolbar(self.canvas, 
             self.mplwindow3, coordinates=True)
         self.mplvl3.addWidget(self.toolbar)
     
     self.setWindowTitle('PS Acquisition Tool - %s' % self.currentArchive)
	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
Beispiel #13
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
        try:
            visvis.plot(self.log_reference_signal)
        except Exception:
            pass

        visvis.xlabel('iteration')
        visvis.ylabel("Signal from reference pulse")
	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)
    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")
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()



Beispiel #17
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)
Beispiel #18
0
 def update_plot(self):
   vv.cla()
   self.surf = vv.surf(self.x, self.y, self.z, axesAdjust=False, axes=self.axes)
   self.surf.clim = self.clim
   self.surf.colormap = vv.CM_JET
Beispiel #19
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)
Beispiel #20
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)
Beispiel #21
0
#!/usr/bin/env python
""" This example illustrate using text and formatting for text
world objects and labels.
"""

import visvis as vv

# Create figure and figure
fig = vv.figure()
a = vv.cla()
a.cameraType = '2d'
a.daspectAuto = True
a.SetLimits((0, 8), (-1, 10))

# Create text inside the axes
vv.Text(a, 'These are texts living in the scene:', 1, 3)
vv.Text(a, 'Text can be made \b{bold} easil\by!', 1, 2)
vv.Text(a, 'Text can be made \i{italic} easil\iy!', 1, 1)

# Create text labels
label0 = vv.Label(a, 'These are texts in widget coordinates:')
label0.position = 10, 20
label1 = vv.Label(a, 'Sub_{script} and super^{script} are easy as pi^2.')
label1.position = 10, 40
label2 = vv.Label(a, u'You can use many Unicode characters: \\u0183 = \u0183')
label2.position = 10, 60
label3 = vv.Label(
    a, 'And can use many Latex like commands: \\alpha \\Alpha' +
    '\\approx, \sigma, \pi, ')
label3.position = 10, 80
    def ExtractPhaseFunc(self, event=None, filename=None):
        """
		This function is the last stage of calibration, 
		when measured data is mathematically processed to obtain the calibration curves.
		"""

        # If filename is not specified, open the file dialogue
        if filename is None:
            filename = self.LoadSettings(title="Load calibration file...")
            # Update the name of pulse shaper calibration file
            import os
            self.SettingsNotebook.PulseShaper.SetSettings(
                {"calibration_file_name": os.path.abspath(filename)})

        visvis.clf()

        # Loading the file calibration file
        with h5py.File(filename, 'a') as calibration_file:
            ############### Loading data ####################
            wavelengths = calibration_file["calibration_settings/wavelengths"][
                ...]
            fixed_voltage = calibration_file[
                "calibration_settings/fixed_voltage"][...]
            pulse_shaper_pixel_num = calibration_file[
                "calibration_settings/pulse_shaper_pixel_num"][...]
            initial_pixel = calibration_file[
                "settings/CalibrateShaper/initial_pixel"][...]
            final_pixel = calibration_file[
                "settings/CalibrateShaper/final_pixel"][...]
            pixel_bundle_width = calibration_file[
                "settings/CalibrateShaper/pixel_bundle_width"][...]
            pixel_to_lamba = str(
                calibration_file["settings/CalibrateShaper/pixel_to_lamba"][
                    ...])
            # Convert to dict
            pixel_to_lamba = eval("{%s}" % pixel_to_lamba)

            # Loading scans of slave and masker masks
            master_mask_scans = []
            slave_mask_scans = []
            for key, spectrum in calibration_file[
                    "spectra_from_uniform_masks"].items():
                master_volt, slave_volt = map(int, key.split('_')[-2:])
                if master_volt == fixed_voltage:
                    slave_mask_scans.append((slave_volt, spectrum[...]))
                if slave_volt == fixed_voltage:
                    master_mask_scans.append((master_volt, spectrum[...]))

            # Sort by voltage
            master_mask_scans.sort()
            slave_mask_scans.sort()

            # Extract spectral scans and voltages for each mask
            master_mask_voltage, master_mask_scans = zip(*master_mask_scans)
            master_mask_voltage = np.array(master_mask_voltage)
            master_mask_scans = np.array(master_mask_scans)

            slave_mask_voltage, slave_mask_scans = zip(*slave_mask_scans)
            slave_mask_voltage = np.array(slave_mask_voltage)
            slave_mask_scans = np.array(slave_mask_scans)

            ################### Find the edges of pixels #################

            # function that converts pixel number to pulse shaper
            # `pixel_to_lamba` is a dictionary  with key = pixel, value = lambda
            deg = 1  #min(1,len(pixel_to_lamba)-1)
            print np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), 1)
            pixel2lambda_func = np.poly1d(
                np.polyfit(pixel_to_lamba.keys(),
                           pixel_to_lamba.values(),
                           deg=deg))
            #lambda2pixel_func = np.poly1d( np.polyfit(pixel_to_lamba.values(), pixel_to_lamba.keys(), deg=deg ) )

            # Get pixels_edges in shaper pixels
            pixels_edges_num = np.arange(initial_pixel, final_pixel,
                                         pixel_bundle_width)
            if pixels_edges_num[-1] < final_pixel:
                pixels_edges_num = np.append(pixels_edges_num, [final_pixel])

            # Get pixels_edges in logical_pixel_lambda
            pixels_edges = pixel2lambda_func(pixels_edges_num)

            # Get pixels_edges in positions of the spectrometer spectra
            pixels_edges = np.abs(wavelengths -
                                  pixels_edges[:, np.newaxis]).argmin(axis=1)

            # Sorting
            indx = np.argsort(pixels_edges)
            pixels_edges = pixels_edges[indx]
            pixels_edges_num = pixels_edges_num[indx]

            # Plot
            visvis.cla()
            visvis.clf()
            visvis.plot(pixel_to_lamba.values(),
                        pixel_to_lamba.keys(),
                        ls=None,
                        ms='*',
                        mc='g',
                        mw=15)
            visvis.plot(wavelengths[pixels_edges],
                        pixels_edges_num,
                        ls='-',
                        lc='r')
            visvis.xlabel('wavelength (nm)')
            visvis.ylabel('pulse shaper pixel')
            visvis.legend(['measured', 'interpolated'])
            self.fig.DrawNow()

            ################ Perform fitting of the phase masks #################
            master_mask_fits = self.FitSpectralScans(master_mask_scans,
                                                     master_mask_voltage,
                                                     pixels_edges)
            slave_mask_fits = self.FitSpectralScans(slave_mask_scans,
                                                    slave_mask_voltage,
                                                    pixels_edges)

            ################# Perform fitting of dispersion and phase functions #################
            master_mask_TC_fitted, master_mask_scans, master_mask_disp_ph_curves = \
             self.GetDispersionPhaseCurves (wavelengths, master_mask_scans, master_mask_voltage,
              pixels_edges, master_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num )

            slave_mask_TC_fitted, slave_mask_scans, slave_mask_disp_ph_curves = \
             self.GetDispersionPhaseCurves (wavelengths, slave_mask_scans, slave_mask_voltage,
              pixels_edges, slave_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num )

            ################ Saving fitting parameters ####################

            #################################################################
            # Save surface calibration
            try:
                del calibration_file["calibrated_surface"]
            except KeyError:
                pass

            CalibratedSurfaceGroupe = calibration_file.create_group(
                "calibrated_surface")

            master_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group(
                "master_mask")
            for key, value in master_mask_disp_ph_curves.items():
                master_mask_calibrated_surface[key] = value

            slave_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group(
                "slave_mask")
            for key, value in slave_mask_disp_ph_curves.items():
                slave_mask_calibrated_surface[key] = value

            #################################################################
            # Clear the group, if it exits
            try:
                del calibration_file["calibrated_pixels"]
            except KeyError:
                pass

            # This group is self consistent, thus the redundancy in saved data (with respect to other group in the file)
            CalibratedPixelsGroupe = calibration_file.create_group(
                "calibrated_pixels")
            CalibratedPixelsGroupe["pixels_edges"] = pixels_edges

            # Finding spectral bounds for each pixel
            pixels_spectral_bounds = zip(wavelengths[pixels_edges[:-1]],
                                         wavelengths[pixels_edges[1:]])

            # Pulse shaper pixel bounds
            pixels_bounds = zip(pixels_edges_num[:-1], pixels_edges_num[1:])

            PixelsGroup = CalibratedPixelsGroupe.create_group("pixels")
            for pixel_num, master_mask_calibration, slave_mask_calibration, \
             spectral_bound, pixel_bound in zip( range(len(master_mask_fits)), \
               master_mask_fits, slave_mask_fits, pixels_spectral_bounds, pixels_bounds  ) :
                pixel = PixelsGroup.create_group("pixel_%d" % pixel_num)
                pixel["spectral_bound"] = spectral_bound
                pixel["pixel_bound"] = pixel_bound
                # Saving fitted calibration data in the tabular form
                pixel["voltage_master_mask"] = master_mask_calibration[0]
                pixel["phase_master_mask"] = master_mask_calibration[1]
                pixel["voltage_slave_mask"] = slave_mask_calibration[0]
                pixel["phase_slave_mask"] = slave_mask_calibration[1]

        ################ Plotting results of calibration ####################
        visvis.cla()
        visvis.clf()

        visvis.subplot(2, 2, 1)
        visvis.imshow(master_mask_scans, cm=visvis.CM_JET)
        visvis.title("Master mask (measured data)")
        visvis.ylabel('voltage')
        visvis.xlabel('wavelength (nm)')

        visvis.subplot(2, 2, 3)
        visvis.imshow(master_mask_TC_fitted, cm=visvis.CM_JET)
        visvis.title("Master mask (fitted data)")
        visvis.ylabel('voltage')
        visvis.xlabel('wavelength (nm)')

        visvis.subplot(2, 2, 2)
        visvis.imshow(slave_mask_scans, cm=visvis.CM_JET)
        visvis.title("Slave mask (measured data)")
        visvis.ylabel('voltage')
        visvis.xlabel('wavelength (nm)')

        visvis.subplot(2, 2, 4)
        visvis.imshow(slave_mask_TC_fitted, cm=visvis.CM_JET)
        visvis.title("Slave mask (fitted data)")
        visvis.ylabel('voltage')
        visvis.xlabel('wavelength (nm)')
Beispiel #23
0
    # 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


if __name__ == '__main__':
    vv.cla()
    vv.title('Selec three points.')
    print(vv.ginput(3))
Beispiel #24
0
    
    # 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


if __name__ == '__main__':
    vv.cla()
    vv.title('Selec three points.')
    print(vv.ginput(3))
allcenterlinesv = AC.s_vessel.ppallCenterlines

# get seedpoints segmentations
s_modelvessel = loadmodel(basedir,
                          ptcode,
                          ctcode,
                          'prox',
                          modelname='modelvesselavgreg')
ppmodelvessel = points_from_nodes_in_graph(s_modelvessel.model)

s_model = loadmodel(basedir, ptcode, ctcode, 'prox', modelname='modelavgreg')
ppmodel = points_from_nodes_in_graph(s_model.model)

# Visualize
AC.a.MakeCurrent()
vv.cla()  # clear vol otherwise plots not visible somehow

# seedpoints segmentations
vv.plot(ppmodelvessel, ms='.', ls='', alpha=0.6, mw=2)
vv.plot(ppmodel, ms='.', ls='', alpha=0.6, mw=2)

# stents
for j in range(len(stentsStartPoints)):
    vv.plot(PointSet(list(stentsStartPoints[j])), ms='.', ls='', mc='g',
            mw=20)  # startpoint green
    vv.plot(PointSet(list(stentsEndPoints[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')
# vessels
for j in range(len(vesselStartPoints)):
Beispiel #26
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)')
Beispiel #27
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)
	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)
Beispiel #29
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
	def ExtractPhaseFunc (self, event=None, filename=None) :
		"""
		This function is the last stage of calibration, 
		when measured data is mathematically processed to obtain the calibration curves.
		"""
		
		# If filename is not specified, open the file dialogue
		if filename is None : 
			filename = self.LoadSettings (title="Load calibration file...")
			# Update the name of pulse shaper calibration file
			import os
			self.SettingsNotebook.PulseShaper.SetSettings({"calibration_file_name" : os.path.abspath(filename)})
			
		visvis.clf()
		
		# Loading the file calibration file
		with h5py.File(filename, 'a') as calibration_file :
			############### Loading data ####################
			wavelengths 		= calibration_file["calibration_settings/wavelengths"][...]
			fixed_voltage 		= calibration_file["calibration_settings/fixed_voltage"][...]
			pulse_shaper_pixel_num = calibration_file["calibration_settings/pulse_shaper_pixel_num"][...]
			initial_pixel	 	= calibration_file["settings/CalibrateShaper/initial_pixel"][...]
			final_pixel 		= calibration_file["settings/CalibrateShaper/final_pixel"][...]
			pixel_bundle_width 	= calibration_file["settings/CalibrateShaper/pixel_bundle_width"][...]
			pixel_to_lamba		= str(calibration_file["settings/CalibrateShaper/pixel_to_lamba"][...])
			# Convert to dict
			pixel_to_lamba 		= eval( "{%s}" % pixel_to_lamba )
			
			# Loading scans of slave and masker masks
			master_mask_scans = []; slave_mask_scans = []
			for key, spectrum in calibration_file["spectra_from_uniform_masks"].items() :
				master_volt, slave_volt = map(int, key.split('_')[-2:])
				if master_volt == fixed_voltage : slave_mask_scans.append( (slave_volt, spectrum[...]) )
				if slave_volt == fixed_voltage	: master_mask_scans.append( (master_volt, spectrum[...]) )
			
			# Sort by voltage
			master_mask_scans.sort(); slave_mask_scans.sort()
			
			# Extract spectral scans and voltages for each mask
			master_mask_voltage, master_mask_scans = zip(*master_mask_scans) 
			master_mask_voltage = np.array(master_mask_voltage); master_mask_scans = np.array(master_mask_scans)
			
			slave_mask_voltage, slave_mask_scans = zip(*slave_mask_scans)
			slave_mask_voltage = np.array(slave_mask_voltage); slave_mask_scans = np.array(slave_mask_scans)
			
			################### Find the edges of pixels #################
			
			# function that converts pixel number to pulse shaper
			# `pixel_to_lamba` is a dictionary  with key = pixel, value = lambda
			deg = 1 #min(1,len(pixel_to_lamba)-1)
			print np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), 1 )
			pixel2lambda_func = np.poly1d( np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), deg=deg ) )
			#lambda2pixel_func = np.poly1d( np.polyfit(pixel_to_lamba.values(), pixel_to_lamba.keys(), deg=deg ) )
			
			# Get pixels_edges in shaper pixels 
			pixels_edges_num = np.arange(initial_pixel, final_pixel, pixel_bundle_width)
			if pixels_edges_num[-1] < final_pixel :
				pixels_edges_num = np.append( pixels_edges_num, [final_pixel])
			
			# Get pixels_edges in logical_pixel_lambda
			pixels_edges = pixel2lambda_func(pixels_edges_num)
			
			# Get pixels_edges in positions of the spectrometer spectra
			pixels_edges = np.abs(wavelengths - pixels_edges[:,np.newaxis]).argmin(axis=1)
			
			# Sorting
			indx = np.argsort(pixels_edges)
			pixels_edges = pixels_edges[indx]
			pixels_edges_num = pixels_edges_num[indx]
			
			# Plot
			visvis.cla(); visvis.clf()
			visvis.plot( pixel_to_lamba.values(), pixel_to_lamba.keys(), ls=None, ms='*', mc='g', mw=15)
			visvis.plot ( wavelengths[pixels_edges], pixels_edges_num, ls='-',lc='r')
			visvis.xlabel('wavelength (nm)')
			visvis.ylabel ('pulse shaper pixel')
			visvis.legend( ['measured', 'interpolated'])
			self.fig.DrawNow()
			 
			################ Perform fitting of the phase masks #################	
			master_mask_fits = self.FitSpectralScans(  master_mask_scans, master_mask_voltage, pixels_edges )
			slave_mask_fits = self.FitSpectralScans(  slave_mask_scans, slave_mask_voltage, pixels_edges )
			
			################# Perform fitting of dispersion and phase functions #################
			master_mask_TC_fitted, master_mask_scans, master_mask_disp_ph_curves = \
				self.GetDispersionPhaseCurves (wavelengths, master_mask_scans, master_mask_voltage, 
					pixels_edges, master_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num ) 
			
			slave_mask_TC_fitted, slave_mask_scans, slave_mask_disp_ph_curves = \
				self.GetDispersionPhaseCurves (wavelengths, slave_mask_scans, slave_mask_voltage, 
					pixels_edges, slave_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num ) 
			
			################ Saving fitting parameters ####################
			
			#################################################################
			# Save surface calibration
			try : del calibration_file["calibrated_surface"]
			except KeyError : pass
			
			CalibratedSurfaceGroupe = calibration_file.create_group("calibrated_surface")
			
			master_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group("master_mask")
			for key, value in master_mask_disp_ph_curves.items() :
				master_mask_calibrated_surface[key] = value
			
			slave_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group("slave_mask")
			for key, value in slave_mask_disp_ph_curves.items() :
				slave_mask_calibrated_surface[key] = value
			
			#################################################################
			# Clear the group, if it exits 
			try : del calibration_file["calibrated_pixels"]
			except KeyError : pass
			
			# This group is self consistent, thus the redundancy in saved data (with respect to other group in the file)
			CalibratedPixelsGroupe = calibration_file.create_group ("calibrated_pixels")
			CalibratedPixelsGroupe["pixels_edges"] 			= pixels_edges
			
			# Finding spectral bounds for each pixel
			pixels_spectral_bounds = zip( wavelengths[pixels_edges[:-1]], wavelengths[pixels_edges[1:]] )
			
			# Pulse shaper pixel bounds
			pixels_bounds = zip(pixels_edges_num[:-1], pixels_edges_num[1:])
			
			PixelsGroup = CalibratedPixelsGroupe.create_group("pixels")
			for pixel_num, master_mask_calibration, slave_mask_calibration, \
				spectral_bound, pixel_bound in zip( range(len(master_mask_fits)), \
						master_mask_fits, slave_mask_fits, pixels_spectral_bounds, pixels_bounds  ) :
				pixel =	PixelsGroup.create_group("pixel_%d" % pixel_num)
				pixel["spectral_bound"] 		= spectral_bound
				pixel["pixel_bound"]			= pixel_bound
				# Saving fitted calibration data in the tabular form
				pixel["voltage_master_mask"] 	= master_mask_calibration[0]
				pixel["phase_master_mask"] 		= master_mask_calibration[1]
				pixel["voltage_slave_mask"] 	= slave_mask_calibration[0]
				pixel["phase_slave_mask"]		= slave_mask_calibration[1]
						
						
		################ Plotting results of calibration ####################
		visvis.cla(); visvis.clf(); 
		
		visvis.subplot(2,2,1)
		visvis.imshow( master_mask_scans, cm=visvis.CM_JET )
		visvis.title ("Master mask (measured data)")
		visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')
		
		visvis.subplot(2,2,3)
		visvis.imshow( master_mask_TC_fitted, cm=visvis.CM_JET )
		visvis.title ("Master mask (fitted data)")
		visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')
		
		visvis.subplot(2,2,2)
		visvis.imshow( slave_mask_scans, cm=visvis.CM_JET )
		visvis.title ("Slave mask (measured data)")
		visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')
		
		visvis.subplot(2,2,4)
		visvis.imshow( slave_mask_TC_fitted, cm=visvis.CM_JET )
		visvis.title ("Slave mask (fitted data)")
		visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')