Ejemplo n.º 1
0
def noOption(ListOpt):
    List = ListOpt.copy()
    if '--log' in List:
        logFlag = True
        List.remove('--log')
    else:
        logFlag = False

    if '--noCal' in List:
        noCalFlag = True
        List.remove('--noCal')
    else:
        noCalFlag = False
    
    ListAux = List
    for arg in ListAux:
        if arg[0] == '-':
            List.remove(arg)

    plotFlag = False
    exitcode = 0

    if len(ListOpt) == 0:
        exitcode = helpFun(['None'],['.Txt','.SPA','.mca','.info'],extBool=False)
        return exitcode
    else:
        for arg in List:
            if isValidSpecFile(arg):
                if arg.endswith('.info'):
                    exitcode = energyFun(['--energyRanges',arg])
                else:
                    myFilename = arg
                    myExtension = myFilename.split(".")[-1]
                    mySubsDict = functionDictAdv[myExtension](myFilename)
                    # SPE no funciona con estas condiciones
                    # if not noCalFlag and mySubsDict['calBoolean']:
                    #     mySubsDict = functionDictAdv[myExtension](myFilename,noCalFlag=False)
                    # else:
                    #     mySubsDict = functionDictAdv[myExtension](myFilename,noCalFlag=True)
                    mySubsList = mySubsDict["theList"]
                    plotFlag = True
                    simplePlot(mySubsList,logFlag,mySubsDict['calBoolean'],Label=None,show=False,Title=None)
            else:
                print('WARNING: The file ' + arg + ' is invalid. Nothing to do with it.')
                return 90
    if plotFlag:
        plt.show()
    return 0
Ejemplo n.º 2
0
def rankProb(ListOpt):
    List = ListOpt.copy()
    List.pop(0)
    i = 0  #for rank op
    rankOp = []
    rankOp2 = [None, None, None]

    if '--noCal' in List:
        noCalFlag = True
        List.remove('--noCal')
    else:
        noCalFlag = False

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

    if '--all' in List:
        allFlag = True
        List.remove('--all')
    else:
        allFlag = False

    for Arg in List:
        try:
            if int(Arg) > 0 and int(Arg) < 4:
                rankOp.append(int(Arg))
            else:
                continue
        except:
            if len(List) <= 1:
                rankOp.append(3)
            continue

    if len(rankOp) == 0:
        rankOp.append(3)
        rankOp.append(2)
    elif len(rankOp) == 1:
        if rankOp[0] == 3:
            rankOp.append(2)
        else:
            rankOp.append(3)

    rankOp = removeDuplicates(rankOp)
    #rankOp2 = [x-4 for x in rankOp]
    rankOp2 = [-2, -3]
    if len(List) == 0:
        print("error: --rank option needs an argument")
        return 0

    infoFile = List[0]
    if not os.path.isfile(infoFile):
        print("error: %s does not exist, are you in the right path?" %
              (infoFile))
        return 10000
    if not infoFile.endswith('.info'):
        print("error: %s needs a .info extension" % (infoFile))
        return 10001
    infoDict = getDictFromInfoFile(infoFile)

    for arg in List:
        if isValidSpecFile(arg):
            if arg.endswith('.info'):
                pass  #infoFile = arg
            else:
                FileName = arg

    try:
        if isValidSpecFile(FileName):
            FileExt = FileName.split('.')[-1]
    except:
        print('ERROR: Unexpected error. Not a valid file used.')
        return 110

    if noCalFlag:
        FileDict = functionDictAdv[FileExt](FileName, False)
    else:
        FileDict = functionDictAdv[FileExt](FileName)

    try:
        minRange = infoDict['Range']['start']
        maxRange = infoDict['Range']['end']
        del infoDict['Range']
    except:
        minRange, maxRange = findRangeInfoDict(infoDict)

    idxPairL = []
    for DictEle in infoDict.values():
        idxPairL.append([DictEle['start'], DictEle['end']])

    DBInfoL = []
    pathfile = os.path.realpath(__file__)
    pathfile = pathfile.rstrip('rank_prob.py')
    conexion = OpenDatabase(pathfile)

    memoLenDict = {}

    isoCountD = {}
    DBInfoL = []
    DBInfoDL = []
    tMinEL = []
    tMaxEL = []
    ProbLL = []
    DiffLL = []
    ProbDL = {}
    DiffDL = {}
    if True:
        for infoPair in infoDict.values():
            tMinEL.append(infoPair['start'])
            tMaxEL.append(infoPair['end'])
        tMinE = min(tMinEL)
        tMaxE = max(tMaxEL)
    else:
        tMinE = minRange
        tMaxE = maxRange

    myDataList = FileDict['theList']
    #print("")
    #print("Gilmore statistics\n[variables in counts]")
    fittingDict = doFittingStuff(infoDict, myDataList)
    #gaussData4Print=[]
    #fig, ax = plt.subplots()
    #for e in fittingDict:
    #a,mean,sigma,c,minIdx,maxIdx,myFWHM=fittingDict[e]
    #    a,mean,sigma,c=fittingDict[e][:-3]
    #    if a == None:
    #        print("Skipping failed fit")
    #        continue
    #    gaussData4Print.append([e,a,mean,sigma,c])

    #plt.annotate(e, xy=[mean,a])
    #myGaussRows=['#tags','a','mean','sigma','c']
    #pd.set_option('display.max_rows', None)
    #dfG = pd.DataFrame(gaussData4Print, columns = myGaussRows)

    #gilmoreDict=doGilmoreStuff(infoDict,myDataList)
    #data4print=[]
    #for e in gilmoreDict:
    #    gL=gilmoreDict[e]
    #    data4print.append(gL[0:6])
    #realXVals=myDataList[0]

    #myHStr4=['Tags','NetArea','Area+ExtBkgd','GrossInt','Background','Sigma_A']
    #pd.set_option('display.max_rows', len(data4print))#imprime todas las filas
    #df = pd.DataFrame([data for data in data4print], columns = myHStr4)
    #print(df)
    #print('\nGauss Parameters')
    #print(dfG)
    fittingDictKeys = list(fittingDict.keys())

    PeakNum = -1
    IdxRemove = []
    #idxPairL_copy=idxPairL.copy()
    for idxR in idxPairL:
        PeakNum += 1
        iEner = idxR[0]
        fEner = idxR[1]
        # DBInfoL.append(GetIntensities(conexion,iEner,fEner))
        # DBInfo = DBInfoL[-1]
        DBInfo = GetIntensities(conexion, iEner, fEner)
        DiffL, ProbL = MeanDistance(DBInfo,
                                    fittingDict[fittingDictKeys[PeakNum]])
        if DiffL == None or ProbL == None:
            continue
        else:
            IdxRemove.append(PeakNum)
            DBInfoL.append(DBInfo)
            DiffLL.append(DiffL)
            ProbLL.append(ProbL)
            DBInfoD = {}
            for e, fs, gs in zip(DBInfo, DiffL, ProbL):
                if e[-1] not in DBInfoD:
                    DBInfoD[e[-1]] = [e]
                    ProbDL[gs[0]] = [gs]
                    DiffDL[fs[0]] = [fs]
                else:
                    DBInfoD[e[-1]].append(e)
                    ProbDL[gs[0]].append(gs)
                    DiffDL[fs[0]].append(fs)
            DBInfoDL.append(DBInfoD)

            for Ele in DBInfo:
                iso = Ele[-1]
                if iso not in memoLenDict:
                    memoLenDict[iso] = [
                        len(GetIntensities(conexion, tMinE, tMaxE, iso)), 1,
                        Ele[10], [PeakNum]
                    ]
                    isoCountD[iso] = [Ele]
                else:
                    memoLenDict[iso][1] += 1
                    memoLenDict[iso][2] += Ele[10]
                    memoLenDict[iso][3].append(PeakNum)
                    isoCountD[iso].append(Ele)

    idxPairL = list(map(idxPairL.__getitem__, IdxRemove))
    memoLenDictKeys = memoLenDict.copy().keys()
    for Ele in memoLenDictKeys:
        if memoLenDict[Ele][0] == 0 or memoLenDict[Ele][2] == 0:
            del memoLenDict[Ele]
            del isoCountD[Ele]
            for DBInfoD in DBInfoDL:
                try:
                    del DBInfoD[Ele]
                except KeyError:
                    continue

    memoLenDictKeys = memoLenDict.keys()

    Ranges = []
    rankList = []

    try:
        if rankOp[0] == 1:
            myfilename = infoFile.strip('.info') + '_rank_B.txt'

        elif rankOp[0] == 2:
            myfilename = infoFile.strip('.info') + '_rank_C.txt'

        elif rankOp[0] == 3:
            myfilename = infoFile.strip('.info') + '_rank_Prob.txt'

        else:
            myfilename = infoFile.strip('.info') + '_rank_Prob.txt'
    except:
        myfilename = 'FileNameCouldNotBeRecovered.txt'

    for idxR, DBInfoD in zip(idxPairL, DBInfoDL):
        iEner = idxR[0]
        fEner = idxR[1]
        Ranges.append([iEner, fEner])
        Eg , Ig , Decay, Half , Parent, rank, rank2, rank3, ProbRank, DiffRank  = [],[],[],[],[],[],[],[],[],[]
        for Key in DBInfoD:
            #Ele = DBInfoD[Key]
            for Ele, DiffEle, ProbEle in zip(DBInfoD[Key], DiffDL[Key],
                                             ProbDL[Key]):
                Eg.append(Ele[1])
                Ig.append(round(Ele[3], 2))
                Decay.append(Ele[5])
                x = halfLifeUnit(Ele)
                if x == 0:
                    y = str(x)
                else:
                    y = str('{0:.2e}'.format(x))
                Half.append(y + ' [s] ')
                Parent.append(Ele[-1])
                rank.append(memoLenDict[Ele[-1]][1])
                rank2.append(
                    round(memoLenDict[Ele[-1]][1] / memoLenDict[Ele[-1]][0],
                          3))
                rank3.append(round(memoLenDict[Ele[-1]][2], 3))
                ProbRank.append(ProbEle[1])
                DiffRank.append(DiffEle[1])

        Eg, Ig, Decay, Half, Parent, rank3, ProbRank, DiffRank = (
            list(t) for t in zip(*sorted(zip(Eg, Ig, Decay, Half, Parent,
                                             rank3, ProbRank, DiffRank),
                                         key=itemgetter(*rankOp2),
                                         reverse=True)))

        print(
            '\nThe energy range consulted is between %.2f keV and %.2f keV.\n'
            % (iEner, fEner))

        if allFlag:
            pd.set_option('display.max_rows', None)  #imprime todas las filas
            pd.options.display.float_format = '{:,.5f}'.format
            df = pd.DataFrame(list(
                zip(Eg, Ig, Decay, Half, Parent, rank3, ProbRank, DiffRank)),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay m', 'Half Life',
                                  'Parent', 'Rank3', 'Probability', 'Distance'
                              ])  #crea  la tabla
            print(df)

        else:
            pd.set_option('display.max_rows', len(Ele))
            df = pd.DataFrame(list(
                zip(Eg, Ig, Decay, Half, Parent, rank3, ProbRank, DiffRank)),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay mode',
                                  'Half Life', 'Parent', 'Rank3',
                                  'Probability', 'Distance'
                              ])  #crea  la tabla
            print(df)

        if wofFlag:
            try:
                if allFlag:
                    WriteOutputFileRR(myfilename, df, iEner, fEner)

                else:
                    WriteOutputFileRR(myfilename, df.head(10), iEner, fEner)

            except IOError:
                print(
                    'ERROR: An unexpected error ocurrs. Data could not be saved.'
                )
                break

    if wofFlag:
        print('-----------------------------------------')
        print('The file was saved as:')
        print(myfilename)
        print('-----------------------------------------')

    return 0
Ejemplo n.º 3
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
Ejemplo n.º 4
0
def rankAdvFun(ListOpt):
    List = ListOpt.copy()
    List.pop(0)

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

    if '--all' in List:
        allFlag = True
        List.remove('--all')
    else:
        allFlag = False
#####
    if '--filter' in List:
        filterFlag = True
        List.remove('--filter')
        IntensityFilter = 5 / 100
    else:
        filterFlag = False

#####

    if '--op1' in List:
        op1Flag = True
        List.remove('--op1')
    else:
        op1Flag = False

    if len(List) == 0:
        sys.stderr.write("error: --energyRanges option needs an argument\n")
        return 0

    for arg in List:
        if isValidSpecFile(arg):
            if arg.endswith('.info'):
                infoFile = arg
            else:
                myFilename = arg

    try:
        if isValidSpecFile(myFilename):
            myExtension = myFilename.split('.')[-1]
    except:
        sys.stderr.write('ERROR: Unexpected error. Not a valid file used.\n')
        return 120

    if not os.path.isfile(infoFile):
        sys.stderr.write(
            "error: %s does not exist, are you in the right path?\n" %
            (infoFile))
        return 10000
    if not infoFile.endswith('.info'):
        sys.stderr.write("error: %s needs a .info extension\n" % (infoFile))
        return 10001
    infoDict = getDictFromInfoFile(infoFile)
    try:
        minRange = infoDict['Range']['start']
        maxRange = infoDict['Range']['end']
        del infoDict['Range']
    except:
        minRange, maxRange = findRangeInfoDict(infoDict)

    myFileDict = getMyFileDictRankAdv(List)

    noCalFlag = False
    mySpecialDict = functionDictAdv[myExtension](myFilename, noCalFlag)
    myDataList = mySpecialDict['theList']

    gilmoreDict = doGilmoreStuff(infoDict, myDataList)
    gilmoreDictKeys = list(gilmoreDict.keys())

    idxPairL = []
    for DictEle in infoDict.values():
        ####
        if op1Flag:
            deltaEle = (DictEle['end'] - DictEle['start']) * .1
            meanEle = (DictEle['start'] + DictEle['end']) / 2
            DictEle['start'] = meanEle - deltaEle
            DictEle['end'] = meanEle + deltaEle
            idxPairL.append([DictEle['start'], DictEle['end']])
        else:
            idxPairL.append([DictEle['start'], DictEle['end']])
        ####
    #Energy range of the histogram

    DBInfoL = []
    pathfile = os.path.realpath(__file__)
    if operatingSystem == 'Linux' or operatingSystem == 'Darwin':
        pathfile = pathfile.replace('/modules/rankAdv.py', '')
    elif operatingSystem == 'Windows':
        pathfile = pathfile.replace('\\modules\\rankAdv.py', '')

    conexion = OpenDatabase(pathfile)

    memoLenDict = {}

    isoCountD = {}
    DBInfoL = []
    DBInfoDL = []
    tMinEL = []
    tMaxEL = []

    if True:
        for infoPair in infoDict.values():
            tMinEL.append(infoPair['start'])
            tMaxEL.append(infoPair['end'])
        tMinE = min(tMinEL)
        tMaxE = max(tMaxEL)
    else:
        tMinE = minRange
        tMaxE = maxRange

    PeakNum = -1
    for idxR in idxPairL:
        PeakNum += 1
        iEner = idxR[0]
        fEner = idxR[1]
        DBInfoL.append(GetIntensities(conexion, iEner, fEner))
        DBInfo = DBInfoL[-1]
        DBInfoD = {}
        for e in DBInfo:
            #Filling dict with isotope name each isotope has only one tupple
            if e[-1] not in DBInfoD:
                DBInfoD[e[-1]] = [e]
            else:
                DBInfoD[e[-1]].append(e)
        DBInfoDL.append(DBInfoD)

        for Ele in DBInfo:
            iso = Ele[-1]
            if iso not in memoLenDict:
                if filterFlag:
                    IntInRange = GetIntensities(conexion, tMinE, tMaxE, iso)
                    Count = 0
                    for Element in IntInRange:
                        if Element[10] >= IntensityFilter:
                            Count += 1
                    if Ele[10] >= IntensityFilter:
                        memoLenDict[iso] = [Count, 1, Ele[10], [PeakNum]]
                    else:
                        memoLenDict[iso] = [Count, 1, 0, [PeakNum]]

                else:
                    memoLenDict[iso] = [
                        len(GetIntensities(conexion, tMinE, tMaxE, iso)), 1,
                        Ele[10], [PeakNum]
                    ]

                isoCountD[iso] = [Ele]
            else:
                if filterFlag:
                    if Ele[10] >= IntensityFilter:
                        memoLenDict[iso][1] += 1
                        memoLenDict[iso][2] += Ele[10]
                        memoLenDict[iso][3].append(PeakNum)
                        isoCountD[iso].append(Ele)
                else:
                    memoLenDict[iso][1] += 1
                    memoLenDict[iso][2] += Ele[10]
                    memoLenDict[iso][3].append(PeakNum)
                    isoCountD[iso].append(Ele)

    memoLenDictKeys = memoLenDict.copy().keys()
    for Ele in memoLenDictKeys:
        if memoLenDict[Ele][0] == 0 or memoLenDict[Ele][2] == 0:
            del memoLenDict[Ele]
            del isoCountD[Ele]
            for DBInfoD in DBInfoDL:
                try:
                    del DBInfoD[Ele]
                except KeyError:
                    continue

    memoLenDictKeys = memoLenDict.keys()

    if filterFlag:
        DBInfoDLshort = []
        for DBInfoD in DBInfoDL:
            DBInfoDKeys = DBInfoD.copy().keys()
            for KeyDB in DBInfoDKeys:
                if KeyDB not in memoLenDictKeys:
                    del DBInfoD[KeyDB]
            DBInfoDLshort.append(DBInfoD)

    else:
        DBInfoDLshort = DBInfoDL.copy()

    DevRankD = {}

    for Key in memoLenDictKeys:
        NetAreaTot = 0
        NormPeakIntensity = 0
        for Peak in removeDuplicates(memoLenDict[Key][3]):
            NetAreaTot += gilmoreDict[gilmoreDictKeys[Peak]][1]
            for MultiPeak in DBInfoDLshort[Peak][Key]:
                NormPeakIntensity += MultiPeak[10]

        ECM = 0

        if len(removeDuplicates(memoLenDict[Key][3])) == 1:
            DevRankD[Key] = (memoLenDict[Key][0] / memoLenDict[Key][1])
        else:

            for Peak in removeDuplicates(memoLenDict[Key][3]):
                MultiPeakIntensity = 0
                for MultiPeak in DBInfoDLshort[Peak][Key]:
                    MultiPeakIntensity += MultiPeak[10]
                ECM += (
                    (MultiPeakIntensity / NormPeakIntensity) -
                    (gilmoreDict[gilmoreDictKeys[Peak]][1] / NetAreaTot))**2

            DevRankD[Key] = (memoLenDict[Key][0] / memoLenDict[Key][1]) * sqrt(
                ECM / len(memoLenDict[Key][3]))

    Ranges = []
    for idxR, DBInfoD in zip(idxPairL, DBInfoDL):
        iEner = idxR[0]
        fEner = idxR[1]
        Ranges.append([iEner, fEner])
        Eg, Ig, Decay, Half, Parent, rank = [], [], [], [], [], []
        for Key in DBInfoD:
            for Ele in DBInfoD[Key]:
                Eg.append(Ele[1])
                Ig.append(round(Ele[3], 2))
                Decay.append(Ele[5])
                x = halfLifeUnit(Ele)
                if x == 0:
                    y = str(x)
                else:
                    y = str('{0:.2e}'.format(x))
                Half.append(y + ' [s] ')
                Parent.append(Ele[-1])
                rank.append(DevRankD[Key])

        print(
            '\nThe energy range consulted is between %.2f keV and %.2f keV.\n'
            % (iEner, fEner))

        if allFlag:
            pd.set_option('display.max_rows', None)
            if filterFlag:
                df = pd.DataFrame(sorted(list(
                    zip(Eg, Ig, Decay, Half, Parent, rank)),
                                         key=lambda x: (x[5], -x[1])),
                                  index=None,
                                  columns=[
                                      'Eg [keV]', 'Ig (%)', 'Decay m',
                                      'Half Life', 'Parent', 'Rank G Filter'
                                  ])  #crea  la tabla
            else:
                df = pd.DataFrame(sorted(list(
                    zip(Eg, Ig, Decay, Half, Parent, rank)),
                                         key=lambda x: (x[5], -x[1])),
                                  index=None,
                                  columns=[
                                      'Eg [keV]', 'Ig (%)', 'Decay m',
                                      'Half Life', 'Parent', 'Rank G'
                                  ])  #crea  la tabla

            print(df)
        else:
            pd.set_option('display.max_rows', 10)
            if filterFlag:
                df = pd.DataFrame(sorted(list(
                    zip(Eg, Ig, Decay, Half, Parent, rank)),
                                         key=lambda x: (x[5], -x[1])),
                                  index=None,
                                  columns=[
                                      'Eg [keV]', 'Ig (%)', 'Decay m',
                                      'Half Life', 'Parent', 'Rank G Filter'
                                  ])  #crea  la tabla
            else:
                df = pd.DataFrame(sorted(list(
                    zip(Eg, Ig, Decay, Half, Parent, rank)),
                                         key=lambda x: (x[5], -x[1])),
                                  index=None,
                                  columns=[
                                      'Eg [keV]', 'Ig (%)', 'Decay mode',
                                      'Half Life', 'Parent', 'Rank G'
                                  ])  #crea  la tabla
            print(df.head(10))

        if wofFlag:
            try:
                if filterFlag:
                    myfilename = infoFile.strip('.info') + '_rank_G_filter.txt'
                else:
                    myfilename = infoFile.strip('.info') + '_rank_G.txt'

                if allFlag:
                    WriteOutputFileRR(myfilename, df, iEner, fEner)

                else:
                    WriteOutputFileRR(myfilename, df.head(10), iEner, fEner)

                print('-----------------------------------------')
                print('The file was saved as:')
                print(myfilename)
                print('-----------------------------------------')
            except IOError:
                sys.stderr.write(
                    'ERROR: An unexpected error ocurrs. Data could not be saved.\n'
                )

    return 0
Ejemplo n.º 5
0
def statsFun(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 = int(Arg)
                List.remove(Arg)
                break
            except:
                continue

        # if rebinNum == None and :
        #     return 120

    else:
        rebinFlag = False

    #infoFile=List[0]
    
    for arg in List:
        if isValidSpecFile(arg):
            if arg.endswith('.info'):
                infoFile = arg
            else:
                FileName = arg
    
    try:
        if isValidSpecFile(FileName):
            FileExt = FileName.split('.')[-1]
    except:
        print('ERROR: Unexpected error. Not a valid file used.')
        return 110

    if not os.path.isfile(infoFile):
        print("ERROR: %s does not exist, are you in the right path?" %(infoFile))
        return 111
    if not infoFile.endswith('.info'):
        print("ERROR: %s needs a .info extension" % (infoFile))
        return 112   
    
    infoDict=getDictFromInfoFile(infoFile)
    try:
         del infoDict['Range']
    except:
        pass
   
    
    if noCalFlag:
        FileDict = functionDictAdv[FileExt](FileName,False)
    else:
        FileDict = functionDictAdv[FileExt](FileName)

    #####
    if rebinFlag:
            
            if isinstance(rebinNum, int) == False:
                rebinNum=5
                print("There was no rebin integer detected, the default rebin value used was 5")
                

            if "theRebinedList" not in FileDict:
                FileDict["theRebinedList"]=getRebinedList(FileDict["theList"],rebinNum)
                myDataList = FileDict["theRebinedList"]
                myDataList[0] = list(myDataList[0])
                myDataList[1] = list(myDataList[1])
                               
    else:
        print("There was no rebin option detected, the rebin option is --rebin")
        myDataList = FileDict['theList']
    
    #####
    

    print("")
    print("Gilmore statistics\n[variables in counts]")
    fittingDict=doFittingStuff(infoDict,myDataList)
    gaussData4Print=[]
    #fig, ax = plt.subplots()
    for e in fittingDict:
        #a,mean,sigma,c,minIdx,maxIdx,myFWHM=fittingDict[e]
        a,mean,sigma,c=fittingDict[e][:-3]
        if a == None:
            print("Skipping failed fit")
            continue
        gaussData4Print.append([e,a,mean,sigma,c])
        
        #plt.annotate(e, xy=[mean,a])
    myGaussRows=['#tags','a','mean','sigma','c']
    pd.set_option('display.max_rows', None)
    dfG = pd.DataFrame(gaussData4Print, columns = myGaussRows)

    gilmoreDict=doGilmoreStuff(infoDict,myDataList)
    data4print=[]
    for e in gilmoreDict:
        gL=gilmoreDict[e]
        data4print.append(gL[0:6])
    realXVals=myDataList[0]

    myHStr4=['Tags','NetArea','Area+ExtBkgd','GrossInt','Background','Sigma_A']
    pd.set_option('display.max_rows', len(data4print))#imprime todas las filas
    df = pd.DataFrame([data for data in data4print], columns = myHStr4)
    print(df)
    print('\nGauss Parameters')
    print(dfG)
    #keyboard.press_and_release('\n')
    if wofFlag:
        doOutputFile(FileName,df,dfG)

    count = 0
    AnnotateArg = []
    idxPairL = []
    for e in gilmoreDict:
        #tag,netArea,G,B,sigma_A,EBA,extSigma_A,myFWHMSigma_A,myFWHMExtSigma_A,max_index,max_value=gilmoreDict[e]
        a,mean,sigma,c,_,_=[str(val) for val in fittingDict[e][:-1]]
        #a,mean,sigma,c,minIdx,maxIdx=[str(val) for val in fittingDict[e][:-1]]
        max_index = gilmoreDict[e][-2]
        max_value = gilmoreDict[e][-1]
        floatMean=fittingDict[e][1]
        idxPairL.append([infoDict[e]['start'],infoDict[e]['end']])
        AnnotateArg.append(["%s,%2.1f"%(e,floatMean),[realXVals[max_index],max_value]])
        count += 1
        #if None != floatMean:
        #    plt.annotate("%s,%2.1f" %(e,floatMean),xy=[realXVals[max_index],max_value])
        #else:
        #    plt.annotate(e, xy=[realXVals[max_index],max_value])
    #erase this part?
    # plt.hist(myArr, bins=16384)
    # plt.bar(np.arange(len(li)),li)
    # plt.yscale('log', nonposy='clip')
    #print("exposure time = ", FileDict["expoTime"])
    
    complexPlot(FileDict,idxPairL,fittingDict,AnnotateArg,logFlag=logFlag,noCalFlag=noCalFlag,Show=not(noPlotFlag),FitCurve=True, rebinFlag=rebinFlag)

    return 0
Ejemplo n.º 6
0
def rankDist(ListOpt):
    List = ListOpt.copy()
    List.pop(0)  
    i = 0 #for rank op
    rankOp = []
    rankOp2 = [None,None,None]
    
    if '--noCal' in List:
        noCalFlag = True
        List.remove('--noCal')
    else:
        noCalFlag = False
    
    if '--wof' in List:
        wofFlag = True
        List.remove('--wof')
    else:
        wofFlag = False

    if '--all' in List:
        allFlag = True
        List.remove('--all')
    else:
        allFlag = False

    for Arg in List:
        try:
            if int(Arg) > 0 and int(Arg) < 4:
                rankOp.append(int(Arg))
            else:
                continue
        except:
            if len(List) <= 1:
                rankOp.append(3)
            continue
    
    if len(rankOp) == 0:
        rankOp.append(3)
        rankOp.append(2) 
    elif len(rankOp) == 1:
        if rankOp[0] == 3:
            rankOp.append(2)
        else:
            rankOp.append(3)

    rankOp = removeDuplicates(rankOp)    
    rankOp2 = [-1,-3,1]
    if len(List) == 0:
        sys.stderr.write("error: --rank option needs an argument\n")
        return 0

    for arg in List:
        if isValidSpecFile(arg):
            if arg.endswith('.info'):
                infoFile = arg
            else:
                FileName = arg
    
    try:
        if isValidSpecFile(FileName):
            FileExt = FileName.split('.')[-1]
    except:
        sys.stderr.write('ERROR: Unexpected error. Not a valid file used.\n')
        return 110

    if not os.path.isfile(infoFile):
        sys.stderr.write("error: %s does not exist, are you in the right path?\n" %(infoFile))
        return 10000
    if not infoFile.endswith('.info'):
        sys.stderr.write("error: %s needs a .info extension\n" % (infoFile))
        return 10001
    infoDict=getDictFromInfoFile(infoFile)
    
    if noCalFlag:
        FileDict = functionDictAdv[FileExt](FileName,False)
    else:
        FileDict = functionDictAdv[FileExt](FileName)

    try:
        minRange = infoDict['Range']['start']
        maxRange = infoDict['Range']['end']
        del infoDict['Range']
    except:
        minRange, maxRange = findRangeInfoDict(infoDict)
    
    idxPairL = []
    for DictEle in infoDict.values():
        idxPairL.append([DictEle['start'],DictEle['end']])

    DBInfoL = []
    pathfile = os.path.realpath(__file__)
    if operatingSystem == 'Linux' or operatingSystem == 'Darwin':
        pathfile = pathfile.replace('/modules/rank_dist.py','')
    elif operatingSystem == 'Windows':
        pathfile = pathfile.replace('\\modules\\rank_dist.py','')

    conexion = OpenDatabase(pathfile)

    memoLenDict={}

    isoCountD = {}
    DBInfoL = []
    DBInfoDL = []
    ProbDL = []
    DiffDL = []
    tMinEL = []
    tMaxEL = []
    ProbLL = []
    DiffLL = []
    if True:
        for infoPair in infoDict.values():
            tMinEL.append(infoPair['start'])
            tMaxEL.append(infoPair['end'])
        tMinE = min(tMinEL)
        tMaxE = max(tMaxEL)
    else:
        tMinE = minRange
        tMaxE = maxRange

    myDataList = FileDict['theList']
    
    fittingDict=doFittingStuff(infoDict,myDataList)
    fittingDictKeys = list(fittingDict.keys())

    PeakNum = -1
    IdxRemove=[]
    
    for idxR in idxPairL:
        PeakNum += 1
        iEner = idxR[0]
        fEner = idxR[1]
        DBInfo = GetIntensities(conexion,iEner,fEner)
        DiffL, ProbL = MeanDistance(DBInfo,fittingDict[fittingDictKeys[PeakNum]])
        if DiffL == None or ProbL == None:
            continue
        else:
            IdxRemove.append(PeakNum)
            DBInfoL.append(DBInfo)
            DiffLL.append(DiffL)
            ProbLL.append(ProbL)
            DBInfoD = {}
            ProbD= {}
            DiffD = {}
            for e,fs,gs in zip(DBInfo,DiffL,ProbL): 
                if e[-1] not in DBInfoD:
                    DBInfoD[e[-1]] = [e]
                    ProbD[gs[0]] = [gs]
                    DiffD[fs[0]] = [fs]
                else:
                    DBInfoD[e[-1]].append(e)
                    ProbD[gs[0]].append(gs)
                    DiffD[fs[0]].append(fs)
            DBInfoDL.append(DBInfoD)   
            ProbDL.append(ProbD)
            DiffDL.append(DiffD)

            for Ele in DBInfo:
                iso = Ele[-1]
                if iso not in memoLenDict:
                    memoLenDict[iso]=[len(GetIntensities(conexion,tMinE,tMaxE,iso)),1,Ele[10],[PeakNum]]
                    isoCountD[iso] = [Ele]
                else:
                    memoLenDict[iso][1] += 1 
                    memoLenDict[iso][2] += Ele[10]
                    memoLenDict[iso][3].append(PeakNum)
                    isoCountD[iso].append(Ele)
    
    idxPairL=list(map(idxPairL.__getitem__,IdxRemove))
    memoLenDictKeys = memoLenDict.copy().keys()
    for Ele in memoLenDictKeys:
        if memoLenDict[Ele][0] == 0 or memoLenDict[Ele][2] == 0:
            del memoLenDict[Ele]
            del isoCountD[Ele]
            for DBInfoD in DBInfoDL:
                try:
                    del DBInfoD[Ele]
                except KeyError:
                    continue

    memoLenDictKeys = memoLenDict.keys()

    Ranges = []
    rankList = []

    try:
        if rankOp[0] == 1:
            myfilename = infoFile.strip('.info') + '_rank_B.txt'
        
        elif rankOp[0] == 2:
            myfilename = infoFile.strip('.info') + '_rank_C.txt'
        
        elif rankOp[0] == 3:
            myfilename = infoFile.strip('.info') + '_rank_A.txt'

        else:
            myfilename = infoFile.strip('.info') + '_rank_A.txt'
    except:
        myfilename = 'FileNameCouldNotBeRecovered.txt'

    for idxR,DBInfoD,DiffD,ProbD in zip(idxPairL,DBInfoDL,DiffDL,ProbDL):
        iEner = idxR[0]
        fEner = idxR[1]
        Ranges.append([iEner,fEner])
        Eg , Ig , Decay, Half , Parent, rank, rank2, rank3, ProbRank, DiffRank  = [],[],[],[],[],[],[],[],[],[]
        for Key in DBInfoD:
            #Ele = DBInfoD[Key]
            for Ele,DiffEle,ProbEle in zip(DBInfoD[Key],DiffD[Key],ProbD[Key]):
                Eg.append(Ele[1])
                Ig.append(round(Ele[3],2))
                Decay.append(Ele[5])
                x=halfLifeUnit(Ele)
                if x == 0:
                    y = str(x)
                else:
                    y = str('{0:.2e}'.format(x))
                Half.append(y+ ' [s] ')
                Parent.append(Ele[-1])
                rank.append(memoLenDict[Ele[-1]][1])
                rank2.append(round(memoLenDict[Ele[-1]][1]/memoLenDict[Ele[-1]][0],3))
                rank3.append(round(memoLenDict[Ele[-1]][2],3))
                ProbRank.append(ProbEle[1])
                DiffRank.append(DiffEle[1])

        print('\nThe energy range consulted is between %.2f keV and %.2f keV.\n' % (iEner,fEner))
        
        if allFlag:
            pd.set_option('display.max_rows', None) #imprime todas las filas
            pd.options.display.float_format = '{:,.5f}'.format
            df = pd.DataFrame(list(zip(Eg,Ig,Decay,Half,Parent,rank3,ProbRank,DiffRank)),columns=['Eg [keV]','Ig (%)','Decay m','Half Life','Parent','Rank F','Probability','Distance'])#crea  la tabla
            df = df.sort_values(by=['Distance','Rank F','Ig (%)'],ascending=[True,False,False],ignore_index=True)
            print(df)
            
        else:
            pd.set_option('display.max_rows', len(Ele))
            df = pd.DataFrame(list(zip(Eg,Ig,Decay,Half,Parent,rank3,ProbRank,DiffRank)),columns=['Eg [keV]','Ig (%)','Decay mode','Half Life','Parent','Rank F','Probability','Distance'])#crea  la tabla
            df = df.sort_values(by=['Distance','Rank F','Ig (%)'],ascending=[True,False,False],ignore_index=True)
            print(df.head(n=10))
            
        if wofFlag:
            try:
                if allFlag:
                    WriteOutputFileRR(myfilename,df,iEner,fEner)
                    
                else:
                    WriteOutputFileRR(myfilename,df.head(10),iEner,fEner)    
            
            except IOError:
                sys.stderr.write('ERROR: An unexpected error ocurrs. Data could not be saved.\n')
                break
    
    if wofFlag:
        print('-----------------------------------------')
        print('The file was saved as:')
        print(myfilename)
        print('-----------------------------------------')  

    return 0
Ejemplo n.º 7
0
def signal2noise(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 = int(Arg)
                List.remove(Arg)
                break
            except:
                continue

    else:
        rebinFlag = False
    FileName = ''
    for arg in List:
        if isValidSpecFile(arg):
            if arg.endswith('.info'):
                infoFile = arg
            else:
                FileName = arg

    try:
        if isValidSpecFile(FileName):
            FileExt = FileName.split('.')[-1]

    except:
        sys.stderr.write('\nERROR: Unexpected error. Not a valid file used.\n')
        return 12010

    if not os.path.isfile(infoFile):
        sys.stderr.write(
            "\nERROR: %s does not exist, are you in the right path?" %
            (infoFile) + "\n")
        return 12011
    if not infoFile.endswith('.info'):
        sys.stderr.write("\nERROR: %s needs a .info extension" % (infoFile) +
                         "\n")
        return 12012

    infoDict = getDictFromInfoFile(infoFile)
    try:
        del infoDict['Range']
    except:
        pass

    if noCalFlag:
        FileDict = functionDictAdv[FileExt](FileName, False)
    else:
        FileDict = functionDictAdv[FileExt](FileName)

    if rebinFlag:

        if isinstance(rebinNum, int) == False:
            rebinNum = 5
            sys.stderr.write(
                "\nThere was no rebin integer detected, the default rebin value used was 5\n"
            )

        if "theRebinedList" not in FileDict:
            FileDict["theRebinedList"] = getRebinedList(
                FileDict["theList"], rebinNum)
            myDataList = FileDict["theRebinedList"]
            myDataList[0] = list(myDataList[0])
            myDataList[1] = list(myDataList[1])

    else:
        sys.stderr.write(
            "\nThere was no rebin option detected, the rebin option is --rebin\n"
        )
        myDataList = FileDict['theList']

    print("")
    print("Gilmore statistics\n[variables in counts]")
    fittingDict = doFittingStuff(infoDict, myDataList, typeSpec='s')
    gaussData4Print = []
    areaSpectrum = []
    areaUnderPeak = []
    underPeakDict = {}

    for e in fittingDict:
        underPeakDict[e] = fittingDict[e].copy()

    for e in underPeakDict:
        underPeakDict[e][0] = 0
        underPeakDict[e][1] = 0
        underPeakDict[e][2] = 0

    for e in fittingDict:
        k, mean, sigma, a, b, c = fittingDict[e][:-3]
        areaSpectrum.append(
            calculateIntegral(fittingDict[e],
                              infoDict[e]['start'],
                              infoDict[e]['end'],
                              type='s'))
        areaUnderPeak.append(
            calculateIntegral(underPeakDict[e],
                              infoDict[e]['start'],
                              infoDict[e]['end'],
                              type='s'))
        if k == None:
            sys.stderr.write("Fit failed for " + str(e) + " in fiting.py" +
                             "\n")
            continue
        gaussData4Print.append([e, k, mean, sigma, a, b, c])

    myGaussRows = ['#tags', 'k', 'mean', 'sigma', 'a', 'b', 'c']
    pd.set_option('display.max_rows', None)
    dfG = pd.DataFrame(gaussData4Print, columns=myGaussRows)

    gaussData4Print = []

    gilmoreDict = doGilmoreStuff(infoDict, myDataList)
    data4print = []
    for e in gilmoreDict:
        gL = gilmoreDict[e]
        data4print.append(gL[0:6])
    realXVals = myDataList[0]

    myHStr4 = [
        'Tags', 'NetArea', 'Area+ExtBkgd', 'GrossInt', 'Background', 'Sigma_A'
    ]
    pd.set_option('display.max_rows', len(data4print))
    df = pd.DataFrame([data for data in data4print], columns=myHStr4)
    print('\nSpectra information')
    print(df)
    print('\nGaussian Parameters + 2nd Order Polynomial')
    print(dfG)

    SNratio = [aS / aB for aS, aB in zip(areaSpectrum, areaUnderPeak)]
    SNratiodB = [10 * log10(SNR) for SNR in SNratio]

    print('\nSignal to Noise ratio per Peak')
    SNdf = pd.DataFrame(
        [[tag, SNR, SNRdB]
         for tag, SNR, SNRdB in zip(fittingDict.keys(), SNratio, SNratiodB)],
        columns=['#tags', 'SNR', 'SNR[dB]'])
    print(SNdf)

    if wofFlag:
        doOutputFile(FileName, df, dfG)

    count = 0
    AnnotateArg = []
    idxPairL = []
    for e in gilmoreDict:
        k, mean, sigma, a, b, c, _, _ = [
            str(val) for val in fittingDict[e][:-1]
        ]
        max_index = gilmoreDict[e][-2]
        max_value = gilmoreDict[e][-1]
        floatMean = fittingDict[e][1]
        idxPairL.append([infoDict[e]['start'], infoDict[e]['end']])
        try:
            AnnotateArg.append([
                "%s,%2.1f" % (e, floatMean), [realXVals[max_index], max_value]
            ])
        except:
            pass

        count += 1

    complexPlot(FileDict,
                idxPairL,
                fittingDict,
                AnnotateArg,
                logFlag=logFlag,
                noCalFlag=noCalFlag,
                Show=not (noPlotFlag),
                FitCurve=True,
                rebinFlag=rebinFlag)

    return 0
Ejemplo n.º 8
0
def noOption(ListOpt):
    labels = []
    List = ListOpt.copy()
    if '--log' in List:
        logFlag = True
        List.remove('--log')
    else:
        logFlag = False

    if '--noCal' in List:
        noCalFlag = True
        List.remove('--noCal')
    else:
        noCalFlag = False

    if '--rebin' in List:
        rebinFlag = True
        List.remove('--rebin')
        rebinNum = None
        for Arg in List:
            try:
                rebinNum = int(Arg)
                List.remove(Arg)
                break
            except:
                continue
    else:
        rebinFlag = False

    ListAux = List
    for arg in ListAux:
        if arg[0] == '-':
            List.remove(arg)

    plotFlag = False
    exitcode = 0

    if len(ListOpt) == 0:
        exitcode = helpFun(['None'], ['.Txt', '.SPE', '.mca', '.info'],
                           extBool=False)
        return exitcode
    else:
        for arg in List:
            if isValidSpecFile(arg):
                if arg.endswith('.info'):
                    exitcode = energyFun(['--energyRanges', arg])

                try:
                    if isValidSpecFile(arg):
                        FileExt = arg.split('.')[-1]
                except:
                    sys.stderr.write(
                        'ERROR: Unexpected error. Not a valid file used.')
                    return 110

                ######
                fileName = arg

                if noCalFlag:
                    FileDict = functionDictAdv[FileExt](fileName, True)
                else:
                    FileDict = functionDictAdv[FileExt](fileName)

                if rebinFlag:

                    if isinstance(rebinNum, int) == False:
                        rebinNum = 5
                        sys.stderr.write(
                            "There was no rebin integer detected, the default rebin value used was 5"
                        )

                    if "theRebinedList" not in FileDict:
                        FileDict["theRebinedList"] = getRebinedList(
                            FileDict["theList"], rebinNum)
                        myDataList = FileDict["theRebinedList"]
                        myDataList[0] = list(myDataList[0])
                        myDataList[1] = list(myDataList[1])

                    else:
                        sys.stderr.write(
                            "There was no rebin option detected, the rebin option is --rebin"
                        )

                    figName = os.path.splitext(arg)[0].split('/')[-1]
                    mySubsList = myDataList
                    plotFlag = True
                    labels.append(figName)
                    simplePlot(mySubsList,
                               logFlag,
                               FileDict['calBoolean'],
                               Label=labels,
                               show=False,
                               Title=fileName,
                               ExpoTime=FileDict['expoTime'],
                               figTitle=figName)

                ######
                else:
                    figName = os.path.splitext(arg)[0].split('/')[-1]
                    labels.append(figName)
                    myExtension = fileName.split(".")[-1]
                    if myExtension != 'info':
                        mySubsList = FileDict["theList"]
                        plotFlag = True
                        simplePlot(mySubsList,
                                   logFlag,
                                   FileDict['calBoolean'],
                                   Label=labels,
                                   show=False,
                                   Title=fileName,
                                   ExpoTime=FileDict['expoTime'],
                                   figTitle=figName)
            else:
                sys.stderr.write('WARNING: The file ' + arg +
                                 ' is invalid. Nothing to do with it.')
                return 90
    if plotFlag:
        plt.show()
    return 0