def LoadShowImage(self):
        QtGui.QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        #initialization
        self.data_struct = data_struct.h5()
        self.stk_sam = data_stack.data(self.data_struct)
        self.stk_bkg = data_stack.data(self.data_struct)
        self.anlz_sam = analyze.analyze(self.stk_sam)
        self.anlz_bkg = analyze.analyze(self.stk_bkg)
        self.common = common()

        #load sample and background
        if self.ui.samTxrm.isChecked() == True:
            #self.new_stack_refresh()
            self.stk_sam.new_data()
            #self.stk.data_struct.delete_data()
            self.anlz_sam.delete_data()
            self.stk_sam.read_txrm(self.sam_filepath)

        if self.ui.samXrm.isChecked() == True:
            self.stk_sam.new_data()
            self.anlz_sam.delete_data()
            #self.sam_filelist = os.path.basename(str(self.sam_filepaths))
            self.stk_sam.read_xrm_list(self.sam_filepaths)

        if self.ui.bkgTxrm.isChecked() == True:
            self.stk_bkg.new_data()
            self.anlz_bkg.delete_data()
            self.stk_bkg.read_txrm(self.bkg_filepath)

        if self.ui.bkgXrm.isChecked() == True:
            self.stk_bkg.new_data()
            self.anlz_bkg.delete_data()
            #self.bkg_filelist = os.path.basename(str(self.bkg_filepaths))
            self.stk_bkg.read_xrm_list(self.bkg_filepaths)

        self.common.stack_loaded == 1

        #update image information
        self.iev = int(self.stk_sam.n_ev)
        x = self.stk_sam.n_cols
        y = self.stk_sam.n_rows
        z = self.iev
        print(z)
        self.ix = int(x / 2)
        self.iy = int(y / 2)

        #calculate scaleimg
        sam_image_stack = self.stk_sam.absdata.copy()
        bkg_image_stack = self.stk_bkg.absdata.copy()
        self.scale_image_stack = np.true_divide(sam_image_stack,
                                                bkg_image_stack)

        #refresh_widgets
        #show image
        self.ShowImage()
        QtGui.QApplication.restoreOverrideCursor()
  def LoadShowImage(self):
    QtGui.QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
    #initialization
    self.data_struct = data_struct.h5()
    self.stk_sam = data_stack.data(self.data_struct)
    self.stk_bkg = data_stack.data(self.data_struct)
    self.anlz_sam = analyze.analyze(self.stk_sam)
    self.anlz_bkg = analyze.analyze(self.stk_bkg)
    self.common = common()

    #load sample and background
    if self.ui.samTxrm.isChecked() == True:            
        #self.new_stack_refresh()  
        self.stk_sam.new_data()
        #self.stk.data_struct.delete_data()
        self.anlz_sam.delete_data()  
        self.stk_sam.read_txrm(self.sam_filepath)        
                
    if self.ui.samXrm.isChecked() == True:              
        self.stk_sam.new_data()
        self.anlz_sam.delete_data()
        #self.sam_filelist = os.path.basename(str(self.sam_filepaths))
        self.stk_sam.read_xrm_list(self.sam_filepaths) 

    if self.ui.bkgTxrm.isChecked() == True:
        self.stk_bkg.new_data()
        self.anlz_bkg.delete_data() 
        self.stk_bkg.read_txrm(self.bkg_filepath)

    if self.ui.bkgXrm.isChecked() == True:
        self.stk_bkg.new_data()
        self.anlz_bkg.delete_data()
        #self.bkg_filelist = os.path.basename(str(self.bkg_filepaths))
        self.stk_bkg.read_xrm_list(self.bkg_filepaths)
 
    self.common.stack_loaded == 1

    #update image information
    self.iev = int(self.stk_sam.n_ev)
    x=self.stk_sam.n_cols
    y=self.stk_sam.n_rows
    z=self.iev  
    print(z)             
    self.ix = int(x/2)
    self.iy = int(y/2)
    
    #calculate scaleimg
    sam_image_stack = self.stk_sam.absdata.copy() 
    bkg_image_stack = self.stk_bkg.absdata.copy()
    self.scale_image_stack = np.true_divide(sam_image_stack,bkg_image_stack)

    #refresh_widgets
    #show image
    self.ShowImage()
    QtGui.QApplication.restoreOverrideCursor()
Ejemplo n.º 3
0
def load(filename, stack_object=None, plugin=None, selection=None):
    """
    Pass the load command over to the appropriate plugin so that it can import data from the named file.
    """
    if plugin is None:
        plugin = identify(filename)
    if plugin is None:
        return None
    else:
        print "load", filename, "with the", plugin.title, "plugin."
        if selection is None or len(selection) == 1:
            if stack_object is None:
                return plugin.read(filename, None,
                                   selection[0])  #should this ever be used?
            else:
                plugin.read(filename, stack_object, selection[0])
                return
        else:
            plugin.read(filename, stack_object, selection[0])
            temp_stack = data_stack.data(stack_object.data_struct)
            full_stack = stack_object.absdata.copy()
            for s in selection[1:]:
                plugin.read(filename, temp_stack, s)
                if full_stack.shape[1] > temp_stack.absdata.shape[1]:
                    temp_stack.absdata = numpy.pad(
                        temp_stack.absdata,
                        ((0, 0), (0, full_stack.shape[1] -
                                  temp_stack.absdata.shape[1]), (0, 0)),
                        mode='constant',
                        constant_values=0)
                elif full_stack.shape[1] < temp_stack.absdata.shape[1]:
                    full_stack = numpy.pad(full_stack,
                                           ((0, 0),
                                            (0, temp_stack.absdata.shape[1] -
                                             full_stack.shape[1]), (0, 0)),
                                           mode='constant',
                                           constant_values=0)
                full_stack = numpy.vstack((full_stack, temp_stack.absdata))
            stack_object.absdata = full_stack
            stack_object.x_dist = numpy.arange(full_stack.shape[0])
            stack_object.y_dist = numpy.arange(full_stack.shape[1])
            stack_object.n_cols = len(stack_object.x_dist)
            stack_object.n_rows = len(stack_object.y_dist)
            return
  def LoadShowImage(self):
    self.ui.status_bkgnorm.setText('status: running')
    QtGui.QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
    #initialization
    self.data_struct = data_struct.h5()
    self.stk_sam = data_stack.data(self.data_struct)
    self.stk_bkg = data_stack.data(self.data_struct)
    self.anlz_sam = analyze.analyze(self.stk_sam)
    self.anlz_bkg = analyze.analyze(self.stk_bkg)
    self.common = common()
    #load sample and background
    if self.ui.samTxrm.isChecked() == True:            
        #self.new_stack_refresh()  
        self.stk_sam.new_data()
        #self.stk.data_struct.delete_data()
        self.anlz_sam.delete_data()  
        self.stk_sam.read_txrm(self.sam_filepath, self.data_struct)                 
    if self.ui.samXrm.isChecked() == True:              
        self.stk_sam.new_data()
        self.anlz_sam.delete_data()
        #self.sam_filelist = os.path.basename(str(self.sam_filepaths))
        self.stk_sam.read_xrm_list(self.sam_filepaths) 
    if self.ui.bkgTxrm.isChecked() == True:
        self.stk_bkg.new_data()
        self.anlz_bkg.delete_data() 
        self.stk_bkg.read_txrm(self.bkg_filepath, self.data_struct)
    if self.ui.bkgXrm.isChecked() == True:
        self.stk_bkg.new_data()
        self.anlz_bkg.delete_data()
        #self.bkg_filelist = os.path.basename(str(self.bkg_filepaths))
        self.stk_bkg.read_xrm_list(self.bkg_filepaths)
    self.common.stack_loaded == 1
    #update image information
    self.iev = int(self.stk_sam.n_ev)
    self.currentSliderStep = self.iev - 1
    self.ev = self.data_struct.exchange.energy
    #calculate scaleimg
    sam_image_stack = self.stk_sam.absdata.copy() 
    bkg_image_stack = self.stk_bkg.absdata.copy()
    self.scale_image_stack = np.true_divide(sam_image_stack,bkg_image_stack)  
    #show image
    self.ShowImage(self.currentSliderStep,self.scale_min,self.scale_max,self.rawImagePosX,self.rawImagePosY,self.bin,self.edgeJump)
    QtGui.QApplication.restoreOverrideCursor()
    #refresh_widgets
    self.ui.slider_img_maxscale.setEnabled(True)
    self.ui.slider_img_minscale.setEnabled(True)
    self.ui.slider_img.setEnabled(True)
    self.ui.current_img.setEnabled(True)
    self.ui.current_img.setText(str(self.iev))
    self.ui.slider_img.setMinimum(1)
    self.ui.slider_img.setMaximum(self.iev)
    self.ui.total_img.setText(str(self.iev))
    self.ui.status_bkgnorm.setText('status: complete')
    self.ui.text_minscale.setText("Min   0   %")
    self.ui.text_maxscale.setText("Max  100  %")
    self.ui.select_point.setEnabled(True)
    self.ui.update_spectrum.setEnabled(True)
    self.ui.x_cord.setEnabled(True)
    self.ui.y_cord.setEnabled(True)
    self.ui.edit_edge_jump.setEnabled(True)

    self.ui.pre_start.setMinimum(1)
    self.ui.pre_start.setMaximum(self.iev)
    self.ui.pre_end.setMinimum(1)
    self.ui.pre_end.setMaximum(self.iev)
    self.ui.post_start.setMinimum(1)
    self.ui.post_start.setMaximum(self.iev)
    self.ui.post_end.setMinimum(1)
    self.ui.post_end.setMaximum(self.iev)
    self.ui.edge_start.setMinimum(1)
    self.ui.edge_start.setMaximum(self.iev)
    self.ui.edge_end.setMinimum(1)
    self.ui.edge_end.setMaximum(self.iev)

    self.ui.text_pre_start.setText('PreEstart')
    self.ui.text_pre_end.setText('PreEend')
    self.ui.text_post_start.setText('PostEstart')
    self.ui.text_post_end.setText('PostEend')
    self.ui.text_edge_start.setText('EdgeStart')
    self.ui.text_edge_end.setText('EdgeEnd')
Ejemplo n.º 5
0
def batch_mode():
    
    verbose  = 1
    
    settingsfile = 'Mantis_batch_settings.txt'     
    
    version = '2.0.5'
    wdir = ''
    outdir = 'MantisResults'
    filename = ''
    save_hdf5 = 0
    align_stack = 0
    i0_file = ''
    i0_histogram = 0
    run_pca = 0
    n_spca = 4
    run_ca = 0
    nclusters = 5
    ca_thickness = 0
    run_sa = 0 
    sa_spectra = []
    sa_use_clspectra = 0
    run_keyengs = 0
    kengs_thresh = 0.10
    save_png = 1
    save_pdf = 0
    save_svg = 0
    


    try:
        f = open(settingsfile, 'rt')
        for line in f:
            if ':' in line : 
                slist = line.split(':')
                tag = slist[0]
                value = ':'.join(slist[1:])
                
                if   tag == 'VERSION': version = float(value)
                elif tag == 'WORK_DIR' : wdir  =  value.strip()
                elif tag == 'OUTPUT_DIR_NAME' : outdir  =  value.strip()
                elif tag == 'FILENAME' : filename  =  value.strip()
                elif tag == 'ALIGN_STACK' : align_stack  =  value.strip()
                elif tag == 'I0_FILE' : i0_file  =  value.strip()
                elif tag == 'I0_HISTOGRAM' : i0_histogram = int(value)
                elif tag == 'SAVE_HDF5' : save_hdf5 = int(value)
                elif tag == 'RUN_PCA' : run_pca = int(value)
                elif tag == 'N_SPCA' : n_spca = int(value)
                elif tag == 'RUN_CLUSTER_ANALYSIS' : run_ca = int(value)
                elif tag == 'N_CLUSTERS' : nclusters = int(value)
                elif tag == 'THICKNESS_CORRECTION' : ca_thickness = int(value)
                elif tag == 'RUN_SPECTRAL_ANALYSIS' : run_sa = int(value)
                elif tag == 'SA_SPECTRUM' : 
                    spname = value.strip()
                    if len(spname) > 0 :
                        sa_spectra.append(spname)
                elif tag == 'SA_USE_CA_SPECTRA' : sa_use_clspectra = int(value)
                elif tag == 'RUN_KEY_ENGS' : run_keyengs = int(value)
                elif tag == 'KE_THRESHOLD' : kengs_thresh = float(value)
                elif tag == 'SAVE_PNG' : save_png = int(value)
                elif tag == 'SAVE_PDF' : save_pdf = int(value)
                elif tag == 'SAVE_SVG' : save_svg = int(value)


        f.close()
                  
    except: 
        print 'Error: Could not read in Mantis_batch_settings.txt.'
        return
    
    
    wdir = os.path.normpath(wdir)
    
    
    if verbose: 
        print 'Version: ', version
        print 'Working directory: ', wdir
        
    if not os.path.exists(wdir):
        print 'Error - Directory ', wdir, ' does not exist. Please specify working directory.'
        return
    
    outdir = os.path.join(wdir, outdir)
    if not os.path.exists(outdir):   
        os.makedirs(outdir)
        if not os.path.exists(outdir):
            print 'Error: Did not find and could not create a new output directory.'
            return 
                
    if save_png == 1:
        print "Save .png images"
        
    if save_pdf == 1:
        print "Save .pdf images"    
            
    datastruct = data_struct.h5()
    stk = data_stack.data(datastruct)
    anlz = analyze.analyze(stk)
    
    print 'Reading file:', filename
    basename, extension = os.path.splitext(filename)   
    filepath = os.path.join(wdir, filename)

    try: 
        if extension == '.hdf5':        
            stk.read_h5(filepath)
            
        if extension == '.hdr':             
            stk.read_sdf(filepath)                
        
        if extension == '.stk':               
            stk.read_stk(filepath)     
    
        if extension == '.txrm':                            
            stk.read_txrm(filepath)        
    
        if extension == '.xrm':              
            stk.read_xrm(filepath)        
            
        if extension == '.tif':              
            stk.read_tiff(filepath)    
    except:
        print "Error: Could not load stack."
        return
    
    
    if align_stack:
        print 'Aligning the stack'
        xshifts = np.zeros((stk.n_ev))
        yshifts = np.zeros((stk.n_ev))
        
        referenceimage = stk.absdata[:,:,0].copy()            

        for i in range(stk.n_ev):

            img2 = stk.absdata[:,:,i]  
 
               
            if i==0:     
                xshift, yshift, ccorr = stk.register_images(referenceimage, img2, 
                                                          have_ref_img_fft = False)        
            else:
                xshift, yshift, ccorr = stk.register_images(referenceimage, img2, 
                                                          have_ref_img_fft = True)
            
#             #Limit the shifts to MAXSHIFT chosen by the user
#             if (self.maxshift > 0):
#                 if (abs(xshift) > self.maxshift):
#                         xshift = npy.sign(xshift)*self.maxshift
#                 if (abs(yshift) > self.maxshift):
#                         yshift = npy.sign(yshift)*self.maxshift
            
            xshifts[i] = xshift
            yshifts[i] = yshift

                                       
        #Apply shifts
        for i in range(stk.n_ev):
            img = stk.absdata[:,:,i]
            if (abs(xshifts[i])>0.02) or (abs(yshifts[i])>0.02):
                shifted_img = stk.apply_image_registration(img, xshifts[i], yshifts[i])
                stk.absdata[:,:,i] = shifted_img

                    
    
    if datastruct.spectromicroscopy.normalization.white_spectrum is not None:
        print "I0 loaded"
    else:
        print "Loading I0"
        if i0_histogram == 1:
            print 'Getting I0 from the histogram'
            stk.calc_histogram()
            averagefluxmax = np.max(stk.histogram)
            histmin = 0.98*averagefluxmax
            histmax = averagefluxmax
            stk.i0_from_histogram(histmin, histmax)
        
        elif len(i0_file) > 0:
            print 'Reading I0 from file:', i0_file
            i0basename, i0extension = os.path.splitext(i0_file)   
            i0filepath = os.path.join(wdir, i0_file)
            stk.read_stk_i0(i0filepath, i0extension)
            
        else:
            print "Please either set I0_HISTOGRAM to 1 to calculate I0 or specify I0 file."
            return
        
    if datastruct.spectromicroscopy.normalization.white_spectrum is None:
        print 'Error: I0 not loaded'
        return
    
    if save_hdf5 == 1:
        fnameh5 =  os.path.join(wdir,basename+'_MantisBatch.hdf5')
        stk.write_h5(fnameh5, data_struct)  
        print 'Saving data to HDF5 file:', fnameh5
        
            
    pca_calculated = 0
    if run_pca == 1:
        print "Running PCA Analysis"
        anlz.calculate_pca()
        print "Chosen number of significant components:", n_spca
        print "Suggested number of significant components:", anlz.numsigpca
        pca_calculated = 1
        anlz.numsigpca = n_spca
        save_pca(outdir, filename, stk, anlz, save_png, save_pdf, save_svg)
        
    ca_calculated = 0
    if run_ca == 1:
        if pca_calculated == 0:
            anlz.calculate_pca()
        print "Running Cluster Analysis"
        print "Number of clusters",  nclusters 
        if ca_thickness == 1:
            print "Thickness correction enabled"
        nclusters = anlz.calculate_clusters(nclusters, ca_thickness)
        ca_calculated = 1
        save_ca(outdir, filename, stk, anlz, save_png, save_pdf, save_svg)

    if run_sa == 1:
        print "Running Spectral Analysis"
        if len(sa_spectra) > 0:
            print "Loading spectra:", sa_spectra
            for i in range(len(sa_spectra)):
                sppath = os.path.join(wdir, sa_spectra[i])
                anlz.read_target_spectrum(filename=sppath)
                
        if sa_use_clspectra == 1:
            if ca_calculated == 1:
                print "Loading cluster spectra"
                anlz.add_cluster_target_spectra()
            else:
                print "Please set RUN_CLUSTER_ANALYSIS to 1 to calculate cluster spectra."
                
        if anlz.n_target_spectra > 1:
            save_spa(outdir, filename, stk, anlz, save_png, save_pdf, save_svg)
        
    if run_keyengs == 1:
        if pca_calculated == 0:
            anlz.calculate_pca()
        print "Finding key energies"
        print "Threshold for finding key energies:", kengs_thresh
        key_engs= anlz.calc_key_engs(kengs_thresh)
        save_keyeng(key_engs, outdir, filename, stk, anlz, save_png, save_pdf, save_svg)
    
    if (save_hdf5 == 1) and (pca_calculated == 1) :
        fnameh5 =  os.path.join(wdir,basename+'_MantisBatch.hdf5')
        stk.write_results_h5(fnameh5, data_struct, anlz)    
    
        
    print "Finished doing Mantis analysis"
    return
  def ExportAthena(self):   
      self.scale_image_stack = None
      self.log_image_stack = None
      self.raw_bulk = None
      self.norm_image_stack = None
      self.norm_bulk = None
      QtGui.QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
      #initialization
      self.data_struct = data_struct.h5()
      self.stk_sam = data_stack.data(self.data_struct)
      self.stk_bkg = data_stack.data(self.data_struct)
      self.anlz_sam = analyze.analyze(self.stk_sam)
      self.anlz_bkg = analyze.analyze(self.stk_bkg)
      #load sample and background
      if self.ui.samTxrm.isChecked() == True:            
          #self.new_stack_refresh()  
          self.stk_sam.new_data()
          #self.stk.data_struct.delete_data()
          self.anlz_sam.delete_data()  
          self.stk_sam.read_txrm(self.sam_filepath, self.data_struct)                 
      if self.ui.samXrm.isChecked() == True:              
          self.stk_sam.new_data()
          self.anlz_sam.delete_data()
          #self.sam_filelist = os.path.basename(str(self.sam_filepaths))
          self.stk_sam.read_xrm_list(self.sam_filepaths) 
      if self.ui.bkgTxrm.isChecked() == True:
          self.stk_bkg.new_data()
          self.anlz_bkg.delete_data() 
          self.stk_bkg.read_txrm(self.bkg_filepath, self.data_struct)
      if self.ui.bkgXrm.isChecked() == True:
          self.stk_bkg.new_data()
          self.anlz_bkg.delete_data()
          #self.bkg_filelist = os.path.basename(str(self.bkg_filepaths))
          self.stk_bkg.read_xrm_list(self.bkg_filepaths)
      #update image information
      self.iev = int(self.stk_sam.n_ev)
      self.ev = self.data_struct.exchange.energy
      self.sam_image_stack = self.stk_sam.absdata.copy() 
      self.bkg_image_stack = self.stk_bkg.absdata.copy()
      self.stk_sam = None
      self.stk_bkg = None
      self.anlz_sam = None
      self.anlz_bkg = None
      X = self.rawImagePosX
      Y = self.rawImagePosY
      self.r_data = np.zeros(self.iev, dtype=np.int)
      if self.bin > 1 :
          sam_data = np.array(self.sam_image_stack[(X-self.bin/2):(X+self.bin/2+1),(Y-self.bin/2):(Y+self.bin/2+1),0:self.iev])          
          bkg_data = np.array(self.bkg_image_stack[(X-self.bin/2):(X+self.bin/2+1),(Y-self.bin/2):(Y+self.bin/2+1),0:self.iev])
          self.sam_image_stack = None
          self.bkg_image_stack = None
	  self.sam_data = np.mean(np.mean(sam_data, axis=0), axis=0)
          self.bkg_data = np.mean(np.mean(bkg_data, axis=0), axis=0)             
      else:
          self.sam_data = np.array(self.sam_image_stack[X,Y,0:self.iev])          
          self.bkg_data = np.array(self.bkg_image_stack[X,Y,0:self.iev])
	  self.sam_image_stack = None
          self.bkg_image_stack = None          

      wildcard =  "TXT (*.txt)" 
      filepath = QtGui.QFileDialog.getSaveFileName(self, 'Save Spectrum to Athena', '', wildcard)
      f = open(filepath,'w')
      f.write('    Energy:               I0            It            Ir\n')
      for i in range(self.iev):
          f.write("%14.5f%14.4f%14.4f%14.4f\n"%(self.ev[i],self.bkg_data[i],self.sam_data[i],self.r_data[i]))
      f.close()
      QtGui.QApplication.restoreOverrideCursor()