Example #1
0
def DataFile2hgeFile(ListOpt):
    
    List = ListOpt.copy()
    List.pop(0)
    ValidFileList = []
    for File in List:
        if isValidSpectrumFile(File):
            ValidFileList.append(File)

    if len(ValidFileList) != 0:
        for File in ValidFileList:
            myExtension = File.split('.')[-1]
            mySpecialDict = functionDictAdv[myExtension](File)
            hgeFilename = File.split('.')[0] + '_factor.hge' 
            exitcode = WritehgeFile(hgeFilename,mySpecialDict)
    else:
        print('There is not a valid file to be converted to .hge file.')
        return 1050
    return exitcode
Example #2
0
def SumFun(ListOpt):
    List = ListOpt.copy()
    List.pop(0)
    #functionDict = {"SPE": getDictFromSPE,"mca": getDictFromMCA,"Txt": getDictFromGammaVision,"info":getDictFromInfoFile}
    if '--noCal' in List:
        noCalFlag = True
        List.remove('--noCal')
    else:
        noCalFlag = False

    if '--noPlot' in List:
        noPlotFlag = True
        List.remove('--noPlot')
    else:
        noPlotFlag = False

    if '--wof' in List:
        wofFlag = True
        List.remove('--wof')
    else:
        wofFlag = False

    if '--log' in List:
        logFlag = True
        List.remove('--log')
    else:
        logFlag = False

    if len(List) == 1:
        if isValidSpecFile(List[0]):
            print('----------------------------------------------')
            print(
                'WARNING: At least two files are needed to make the sum between them.'
            )
            print(
                'No sum was performed. If option --noPlot is disabled then plot is shown.'
            )
            print('Otherwise, nothing is shown.')
            print('----------------------------------------------')
            myFilename = List[0]
            myExtension = myFilename.split(".")[-1]
            if noCalFlag:
                mySubsDict = functionDict[myExtension](myFilename, False)
            else:
                mySubsDict = functionDict[myExtension](myFilename)
            mySubsList = mySubsDict["theList"]
            if noPlotFlag:
                print('----------------------------------------------')
                print('--noPlot is activated, so there is no figure display.')
            else:
                simplePlot(mySubsList,
                           logFlag,
                           noCalFlag,
                           Label=None,
                           show=True,
                           Title=myFilename.split('/')[-1])
        else:
            print('----------------------------------------------')
            print('WARNING: No .mca, .Txt or .SPE files was indicated.')
            print('Please, introduce two or more valid files.')
            return 41

    elif len(List) > 1:
        count = 0
        Title = ''
        for myFilename in List:
            count += 1
            Title += myFilename.split('/')[-1] + '+'
            if isValidSpecFile(myFilename):
                myExtension = myFilename.split(".")[-1]
            if noCalFlag:
                mySubsDict = functionDict[myExtension](myFilename, False)
                if count == 1:
                    mySubsDictOut = mySubsDict.copy()
            else:
                mySubsDict = functionDict[myExtension](myFilename)
                if count == 1:
                    mySubsDictOut = mySubsDict.copy()
            if count != 1:
                mySubsDictOut = SumSpectra(mySubsDictOut, mySubsDict)

        if not noPlotFlag:
            simplePlot(mySubsDictOut["theList"],
                       logFlag,
                       noCalFlag,
                       Label=None,
                       show=True,
                       Title=Title[:-1])
        if wofFlag:
            myOutFile = myFilename.strip(
                myFilename.split('/')[-1]) + Title + '.txt'
            try:
                WritehgeFile(myOutFile, mySubsDictOut)
                print('-----------------------------------------')
                print('The file was saved as:')
                print(myOutFile)
                print('-----------------------------------------')
            except:
                try:
                    WriteOutputFile(mySubsDictOut, myOutFile, Title)
                    print('-----------------------------------------')
                    print('The file was saved as:')
                    print(myOutFile)
                    print('-----------------------------------------')
                except IOError:
                    print(
                        'An unexpected error ocurred while saving the data to file.'
                    )
                    return 44

    else:
        print('ERROR: Not a valid argument in "Sum" function.')
        return 40

    return 0
Example #3
0
def efficencyFun(Command):
    List = Command.copy()
    List.pop(0)
    PlotFlag = False
    if '--Plot' in List or '--plot' in List:
        PlotFlag = True
        List.remove('--Plot')
    
    ValidFileList = []
    EffFile = ''
    for File in List:
        if isValidSpectrumFile(File):
            ValidFileList.append(File)
        elif '.eff' in File:
            EffFile = File

    if EffFile == '':
        sys.stderr.write('An efficiency file for the detector is required.\n')
        return 2000
    else:
        try:
            Effdf = pd.read_csv(EffFile,header=None,names=['energy','eff'])
        except IOError:
            sys.stderr.write('ERROR: The .eff file could not be read.\n')
            return 2001
        else:
            Effenernp = Effdf['energy'].values
            Effnp = Effdf['eff'].values
            PolyCoeff = curve_fit(PolyFun,Effenernp,Effnp,absolute_sigma=True)
            R2PolyCoeff = R2PolyFun(Effenernp,Effnp,PolyCoeff[0])
            Fun1Coeff = curve_fit(Fun1,Effenernp,Effnp,absolute_sigma=True,bounds=([-np.inf,-np.inf,-np.inf,-np.inf],[np.inf,np.inf,np.inf,np.inf]))
            R2Fun1Coeff = R2Fun1(Effenernp,Effnp,Fun1Coeff[0])
            LinearCoeff = curve_fit(LinearFun,Effenernp,Effnp,absolute_sigma=True)
            R2LinearCoeff = R2LinearFun(Effenernp,Effnp,LinearCoeff[0]) 
                
    if PlotFlag:
        XPoly = np.linspace(min(Effenernp),max(Effenernp),num=len(Effenernp)*50)
        R2List = [R2PolyCoeff,R2Fun1Coeff,R2LinearCoeff]
        R2max = max(R2List)
        if R2max == R2PolyCoeff:
            Ypoly = np.polyval(PolyCoeff[0],XPoly)
        elif R2max == R2Fun1Coeff:
            Ypoly = Fun1(XPoly,Fun1Coeff[0][0],Fun1Coeff[0][1],Fun1Coeff[0][2],Fun1Coeff[0][3])
        elif R2max == R2LinearCoeff:
            Ypoly = LinearFun(XPoly,LinearCoeff[0][0],LinearCoeff[0][1])
        plt.plot(XPoly,Ypoly,label='Curve fitting')
        plt.scatter(Effenernp,Effnp,label='Data')
        plt.xscale('log')
        plt.yscale('log')
        plt.xlabel('Energy/keV')
        plt.ylabel('Efficiency')
        plt.title('Detector Efficiency')
        plt.legend(loc='upper right')
        if R2max == R2PolyCoeff:
            textstr = f'Eight grade polynomial.\na1={str(PolyCoeff[0][0])},a2={str(PolyCoeff[0][1])}\na3={str(PolyCoeff[0][2])},a4={str(PolyCoeff[0][3])}\na5={str(PolyCoeff[0][4])},a6={str(PolyCoeff[0][5])}\na7={str(PolyCoeff[0][6])},a8={str(PolyCoeff[0][7])}\nR²={str(R2PolyCoeff)}'
        elif R2max == R2Fun1Coeff:
            textstr = f'f(x) = (ax+b)/(x²+cx+d)\na={str(Fun1Coeff[0][0])}\nb={str(Fun1Coeff[0][1])}\nc={str(Fun1Coeff[0][2])}\nd={str(Fun1Coeff[0][3])}\nR²={str(R2Fun1Coeff)}'
        elif R2max == R2LinearCoeff:
            textstr = f'f(x) = (ax+b)\na={str(LinearCoeff[0][0])}\nb={str(LinearCoeff[0][1])}\nR²={str(R2LinearCoeff)}'
        plt.annotate(textstr,xy=(0, 0.1), xytext=(12, -12),va='bottom',xycoords='axes fraction', textcoords='offset points',fontsize=10)
        plt.show()
        return 0
        
    elif not PlotFlag:
        for File in ValidFileList:
            myExtension = File.split('.')[-1]
            mySpecialDict = functionDictAdv[myExtension](File)
            xVals = np.array(mySpecialDict['theList'][0])
            yVals = np.array(mySpecialDict['theList'][1])
            R2List = [R2PolyCoeff,R2Fun1Coeff,R2LinearCoeff]
            R2max = max(R2List)
            if R2max == R2PolyCoeff:
                EffGe = np.polyval(PolyCoeff[0],xVals)
            elif R2max == R2Fun1Coeff:
                EffGe = Fun1(xVals,Fun1Coeff[0][0],Fun1Coeff[0][1],Fun1Coeff[0][2],Fun1Coeff[0][3])
            elif R2max == R2LinearCoeff:
                EffGe = LinearFun(xVals,LinearCoeff[0][0],LinearCoeff[0][1])
            
            CorrectedSpec = mySpecialDict.copy()
            CorrectedSpec['theList'][1] = yVals/EffGe
            filename = File.split('.')[0] + '_corrected.hge'
            exitcode = WritehgeFile(filename,CorrectedSpec)



        return exitcode
Example #4
0
def SubFun(ListOpt):
    List = ListOpt.copy()
    List.pop(0)
    if '--noCal' in List:
        noCalFlag = True
        List.remove('--noCal')
    else:
        noCalFlag = False
    if '--noPlot' in List:
        noPlotFlag = True
        List.remove('--noPlot')
    else:
        noPlotFlag = False
    if '--wof' in List:
        wofFlag = True
        List.remove('--wof')
    else:
        wofFlag = False
    if '--log' in List:
        logFlag = True
        List.remove('--log')
    else:
        logFlag = False
    if '--rebin' in List:
        rebinFlag = True
        List.remove('--rebin')
        rebinNum = None
        for Arg in List:
            try:
                rebinNum = float(Arg)
                break
            except:
                continue
        if rebinNum == None:
            return 64

    else:
        rebinFlag = False

    FileName1 = List[0]
    FileName2 = List[1]
    if len(List) == 0:
        sys.stderr.write(
            'ERROR: "-r" option needs 2 arguments: File1 and File2, which will be substracted to File1.'
        )
        return 60

    if not os.path.isfile(FileName1):
        sys.stderr.write("ERROR: %s does not exist.\n" % (FileName1))
        return 61

    if not os.path.isfile(FileName2):
        sys.stderr.write("ERROR: %s does not exist.\n" % (FileName2))
        return 62
    File1Ext = FileName1.split('.')[-1]
    File2Ext = FileName2.split('.')[-1]
    if File1Ext != File2Ext:
        sys.stderr.write(
            "Errror: background substraction needs the same extension as the main file. (for now)"
        )
        return 65

    if noCalFlag:
        File1Dict = functionDict[File1Ext](FileName1, True)
        File2Dict = functionDict[File2Ext](FileName2, True)
    else:
        File1Dict = functionDict[File1Ext](FileName1, False)
        File2Dict = functionDict[File2Ext](FileName2, False)

    if rebinFlag:
        File1Dict["theRebinedList"] = getRebinedList(File1Dict["theList"],
                                                     rebinNum)
        File2Dict["theRebinedList"] = getRebinedList(File2Dict["theList"],
                                                     rebinNum)
        myLen1 = len(File1Dict["theRebinedList"][1])
        myLen2 = len(File2Dict["theRebinedList"][1])
    else:
        myLen1 = len(File1Dict["theList"][1])
        myLen2 = len(File2Dict["theList"][1])

    if myLen1 != myLen2:
        sys.stderr.write(
            "ERROR: histograms do not have the same length and histoGe cannot continue.\n"
        )
        return 63

    time1 = File1Dict["expoTime"]
    time2 = File2Dict["expoTime"]
    tRatio = time1 / time2
    rescaledList = getRescaledList(File2Dict['theList'], tRatio)

    if File1Dict['calBoolean'] == File2Dict['calBoolean']:
        subsTractedL = getSubstractedList(File1Dict['theList'], rescaledList)
    else:
        print('--------------------------------------------')
        sys.stderr.write(
            'ERROR: All files must be calibrated or non-calibrated.\n')
        print('Sub cannot be performed between different types of files')
        print('--------------------------------------------')
        exit(43)
        pass

    allData = subsTractedL
    allData.append(rescaledList[1])
    allData.append(File1Dict['theList'][1])
    Title = FileName1.split('/')[-1].rstrip(
        '.' + File1Ext) + '-' + FileName2.split('/')[-1].rstrip('.' + File2Ext)
    IdFile = FileName1.rfind('/')
    myOutFile = FileName1[:IdFile + 1] + Title + '.txt'

    Labels = [
        FileName1.split('/')[-1].rstrip('.' + File1Ext),
        FileName2.split('/')[-1].rstrip('.' + File1Ext), Title
    ]

    if not noPlotFlag:
        simplePlot(allData,
                   logFlag,
                   File1Dict['calBoolean'] and File2Dict['calBoolean'],
                   Label=Labels,
                   show=True,
                   Title=Title,
                   figTitle=Title)  #simple plot of subtracted
    if wofFlag:
        try:
            WritehgeFile(myOutFile, subsTractedL)
            print('-----------------------------------------')
            print('The file was saved as:')
            print(myOutFile)
            print('-----------------------------------------')
        except:
            try:
                WriteOutputFile(subsTractedL, myOutFile, Title)
                print('-----------------------------------------')
                print('The file was saved as:')
                print(myOutFile)
                print('-----------------------------------------')
            except IOError:
                sys.stderr.write(
                    'An unexpected error ocurred while saving the data to file.\n'
                )
                return 66

    return 0
Example #5
0
def SubFun(ListOpt):
    List = ListOpt.copy()
    List.pop(0)
    if '--noCal' in List:
        noCalFlag = True
        List.remove('--noCal')
    else:
        noCalFlag = False
    if '--noPlot' in List:
        noPlotFlag = True
        List.remove('--noPlot')
    else:
        noPlotFlag = False
    if '--wof' in List:
        wofFlag = True
        List.remove('--wof')
    else:
        wofFlag = False
    if '--log' in List:
        logFlag = True
        List.remove('--log')
    else:
        logFlag = False
    if '--rebin' in List:
        rebinFlag = True
        List.remove('--rebin')
        rebinNum = None
        for Arg in List:
            try:
                rebinNum = float(Arg)
                break
            except:
                continue
        if rebinNum == None:
            return 64

    else:
        rebinFlag = False

    FileName1 = List[0]
    FileName2 = List[1]
    if len(List) == 0:
        print(
            'ERROR: "-r" option needs 2 arguments: File1 and File2, which will be substracted to File1.'
        )
        return 60

    if not os.path.isfile(FileName1):
        print("ERROR: %s does not exist." % (FileName1))
        return 61

    if not os.path.isfile(FileName2):
        print("ERROR: %s does not exist." % (FileName2))
        return 62
    File1Ext = FileName1.split('.')[-1]
    File2Ext = FileName2.split('.')[-1]
    if File1Ext != File2Ext:
        print(
            "Errror: background substraction needs the same extension as the main file. (for now)"
        )
        return 65

    if noCalFlag:
        File1Dict = functionDict[File1Ext](FileName1, False)
        File2Dict = functionDict[File2Ext](FileName2, False)
    else:
        File1Dict = functionDict[File1Ext](FileName1)
        File2Dict = functionDict[File2Ext](FileName2)

    if rebinFlag:
        File1Dict["theRebinedList"] = getRebinedList(File1Dict["theList"],
                                                     rebinNum)
        File2Dict["theRebinedList"] = getRebinedList(File2Dict["theList"],
                                                     rebinNum)
        myLen1 = len(File1Dict["theRebinedList"][1])
        myLen2 = len(File2Dict["theRebinedList"][1])
    else:
        myLen1 = len(File1Dict["theList"][1])
        myLen2 = len(File2Dict["theList"][1])

    if myLen1 != myLen2:
        print(
            "ERROR: histograms do not have the same length and histoGe cannot continue."
        )
        return 63

    time1 = File1Dict["expoTime"]
    time2 = File2Dict["expoTime"]
    tRatio = time1 / time2
    rescaledList = getRescaledList(File2Dict['theList'], tRatio)
    subsTractedL = getSubstractedList(File1Dict['theList'], rescaledList)

    Title = FileName1.split('/')[-1].rstrip(
        '.' + File1Ext) + '-' + FileName2.split('/')[-1].rstrip('.' + File2Ext)
    IdFile = FileName1.rfind('/')
    myOutFile = FileName1[:IdFile + 1] + Title + '.txt'

    if not noPlotFlag:
        simplePlot(subsTractedL,
                   logFlag,
                   noCalFlag,
                   Label=None,
                   show=True,
                   Title=Title)
    if wofFlag:
        try:
            WritehgeFile(myOutFile, subsTractedL)
            print('-----------------------------------------')
            print('The file was saved as:')
            print(myOutFile)
            print('-----------------------------------------')
        except:
            try:
                WriteOutputFile(subsTractedL, myOutFile, Title)
                print('-----------------------------------------')
                print('The file was saved as:')
                print(myOutFile)
                print('-----------------------------------------')
            except IOError:
                print(
                    'An unexpected error ocurred while saving the data to file.'
                )
                return 66

    return 0