advancedWITec.py 8.3 KB
Newer Older
Josef Brandt's avatar
Josef Brandt committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
"""
GEPARD - Gepard-Enabled PARticle Detection
Copyright (C) 2018  Lars Bittrich and Josef Brandt, Leibniz-Institut für 
Polymerforschung Dresden e. V. <bittrich-lars@ipfdd.de>    

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program, see COPYING.  
If not, see <https://www.gnu.org/licenses/>.
"""

import os
import numpy as np

class AdvancedWITecSpectra(object):
    """
    Handles Spectra formatting and storage when using the advanced "silent spectrum" option in the WITec COM interface
    :return:
    """
    def __init__(self):
        super(AdvancedWITecSpectra, self).__init__()
        self.dsetpath = None
        self.tmpspecpath = None
        self.curSpecIndex = None
        self.excitWavel = None
        self.spectraBatchSize = None
    
    def setDatasetPath(self, path):
        self.dsetpath = path
    
    def setSpectraBatchSize(self, batchSize):
        self.spectraBatchSize = batchSize
        
    def createTmpSpecFolder(self):
        assert self.dsetpath is not None
        self.tmpspecpath = os.path.join(self.dsetpath, 'spectra')
        if not os.path.exists(self.tmpspecpath):
            os.mkdir(self.tmpspecpath)
    
    def registerNewSpectrum(self, specString, specIndex):
        wavenumbers, averaged_counts = self.deassembleSpecString(specString)
        if specIndex == 0:
            fname = os.path.join(self.tmpspecpath, 'Wavenumbers.npy')
            np.save(fname, wavenumbers)
            
        fname = os.path.join(self.tmpspecpath, f'Spectrum ({specIndex}).npy')
        np.save(fname, averaged_counts)
        self.curSpecIndex = specIndex
        
    def createSummarizedSpecFiles(self):
        allSpectra = self.getAllSpectra()
        allspecfname = os.path.join(self.dsetpath, 'spectra.npy')
        np.save(allspecfname, allSpectra)
        self.createTrueMatchTxt(allSpectra, self.excitWavel)
    
    def deassembleSpecString(self, specString):
        keywordLines = self.getKeyWordLines(specString)
        
        try:
            specSize = self.getSpecSize(specString, keywordLines['SpectrumSize'][0])
        except:
            print(keywordLines)
            raise
        wavenumbers = self.getWavenumbers(specString, keywordLines['[XData]'][0], specSize)
        xDataKind = self.getXDataKind(specString, keywordLines['XDataKind'][0])
        self.excitWavel = self.getExcitationWavelength(specString, keywordLines['ExcitationWavelength'][0])
        
        if xDataKind == 'nm':
            wavenumbers = self.convertWavenumbersFrom_nm_to_Percm(wavenumbers, self.excitWavel)
        else:
            print('warning, unexpected xDataKind:', xDataKind)
            print('please check how to deal with it!!!')
            assert False
        
        averaged_counts = self.getAveragedSpectra(specString, keywordLines['SpectrumData'], specSize)
        return wavenumbers, averaged_counts
    
    def getKeyWordLines(self, specString):
        keywordLines = {'[WITEC_TRUEMATCH_ASCII_HEADER]': [],
                        '[XData]': [],
                        'ExcitationWavelength': [],
                        'SpectrumSize': [], 
                        'XDataKind': [], 
                        'SpectrumHeader': [],
                        'SampleMetaData': [],
                        'SpectrumData': []}
        
        for index, line in enumerate(specString):
            for key in keywordLines.keys():
                if line.find(key) != -1:
                    keywordLines[key].append(index)
        return keywordLines
    
    def getSpecSize(self, specString, specSizeIndex):
        line = specString[specSizeIndex]
        specSize = [int(s) for s in line.split() if self.isNumber(s)]
        assert len(specSize) == 1
        return specSize[0]
    
    def getExcitationWavelength(self, specString, excitWavenumIndex):
        line = specString[excitWavenumIndex]
        excitWavel = [float(s) for s in line.split() if self.isNumber(s)]
        assert len(excitWavel) == 1
        return excitWavel[0]
    
    def getXDataKind(self, specString, xDataKindIndex):
        line = specString[xDataKindIndex]
        return line.split()[-1]
    
    def getWavenumbers(self, specString, startXDataIndex, specSize):
        wavenumbers = []
        curIndex = startXDataIndex+1
        curLine = specString[curIndex]
        
        while self.isNumber(curLine):
            wavenumbers.append(float(curLine))
            curIndex += 1
            curLine = specString[curIndex]
        
        assert len(wavenumbers) == specSize
        return wavenumbers
    
    def convertWavenumbersFrom_nm_to_Percm(self, wavenumbers, excit_nm):
        newWavenumbers = []
        for abs_nm in wavenumbers:
            raman_shift = 1E7/excit_nm - 1E7/abs_nm
            newWavenumbers.append(raman_shift)
        return newWavenumbers
    
    def getAveragedSpectra(self, specString, startIndices, specSize):
        startIndices = [i+1 for i in startIndices] #the spectrum starts one line AFTER the SpectrumData-Tag
        spectrum = []
        for index in range(specSize):
            curSlice = [float(specString[index + startIndex]) for startIndex in startIndices]
            spectrum.append(np.mean(curSlice))
        return spectrum
    
    def getAllSpectra(self):
        numSpectra = self.curSpecIndex + 1
        wavenumbers = np.load(os.path.join(self.tmpspecpath, 'Wavenumbers.npy'))
        allSpectra = np.zeros((wavenumbers.shape[0], numSpectra+1))
        allSpectra[:, 0] = wavenumbers
        for i in range(numSpectra):
            curSpecPath = os.path.join(self.tmpspecpath, f'Spectrum ({i}).npy')
            allSpectra[:, i+1] = np.load(curSpecPath )
            os.remove(curSpecPath)
        return allSpectra
    
    def createTrueMatchTxt(self, allSpectra, wavelength):
        def writeHeader(fp):
            fp.write('[WITEC_TRUEMATCH_ASCII_HEADER]\n\r')
            fp.write('Version = 2.0\n\r\n\r')
        
        def writeWavenumbers(fp, wavenumbers):
            fp.write('[XData]\n\r')
            for line in wavenumbers:
                fp.write(str(line) + '\n\r')
                
        def writeSpectrum(fp, intensities):
            fp.write('\n\r')
            fp.write('[SpectrumHeader]\n\r')
            fp.write(f'Title = Spectrum {specIndex} \n\r')
            fp.write(f'ExcitationWavelength = {wavelength}\n\r')
            fp.write(f'SpectrumSize = {specSize}\n\r')
            fp.write('XDataKind = 1/cm\n\r\n\r')
            fp.write('[SampleMetaData]\n\r')
            fp.write(f'int Spectrum_Number = {specIndex}\n\r\n\r')
            fp.write('[SpectrumData]\n\r')
            for line in intensities:
                    fp.write(str(line) + '\n\r')
            
        wavenumbers = allSpectra[:, 0]
        spectra = allSpectra[:, 1:]
        specSize = allSpectra.shape[0]
        del allSpectra
        numSpectra = spectra.shape[1]
        numBatches = int(np.ceil(numSpectra/self.spectraBatchSize))
        
        for batchIndex in range(numBatches):
            outName = os.path.join(self.dsetpath, f'SpectraForTrueMatch {batchIndex}.txt')
            if os.path.exists(outName):
                os.remove(outName)
            
            if batchIndex < numBatches-1:
                specIndicesInBatch = np.arange(batchIndex*self.spectraBatchSize, (batchIndex+1)*self.spectraBatchSize)
            else:
                specIndicesInBatch = np.arange(batchIndex*self.spectraBatchSize, numSpectra)
            
            with open(outName, 'w') as fp:
                writeHeader(fp)
                writeWavenumbers(fp, wavenumbers)
                
                for specIndex in specIndicesInBatch:
                    spec = spectra[:, specIndex]
                    writeSpectrum(fp, spec)
            
    def isNumber(self, string):
        isNumber = False
        try:
            float(string)
            isNumber = True
        except ValueError:
            pass
        return isNumber