Exemple #1
0
def QueryFun(ListOpt):
    #print(String)
    List = ListOpt.copy()
    List.pop(0)
    pathfile = os.path.realpath(__file__)
    pathfile = pathfile.strip('query.py')
    conexion = OpenDatabase(pathfile)
    if '--all' in List:
        allflag = True
        List.remove('--all')
    else:
        allflag = False
    if len(List) == 2:
        iEner = List[0]
        fEner = List[1]
    else:
        print('')
        return 30

    try:
        iEner = float(iEner)
        fEner = float(fEner)
    except ValueError:
        print('ERROR: Argument or arguments cannot be converted to float.')
        return 31
    if iEner > fEner:
        iEnerAux = iEner
        iEner = fEner
        fEner = iEnerAux
        del iEnerAux

    DBInfo = EnergyRange(conexion, iEner, fEner)
    print('\nThe energy range consulted is %.2f keV to %.2f keV.\n' %
          (iEner, fEner))
    if len(DBInfo) != 0:
        Eg, Ig, Decay, Half, Parent = [], [], [], [], []
        for Ele in DBInfo:
            Eg.append(str(Ele[1]) + ' (' + str(Ele[2]) + ')')
            Ig.append(str(Ele[3]) + ' (' + str(Ele[4]) + ')')
            Decay.append(Ele[5])
            Half.append(
                str(Ele[6]) + ' ' + str(Ele[7]) + ' (' + str(Ele[8]) + ')')
            Parent.append(Ele[10])
        pd.set_option('display.max_rows', 30)  #imprime todas las filas

        if allflag:
            pd.set_option('display.max_rows', None)  #imprime todas las filas
        else:
            pd.set_option('display.max_rows', len(Ele))

        df = pd.DataFrame(list(zip(Eg, Ig, Decay, Half, Parent)),
                          columns=[
                              'Eg [keV]', 'Ig (%)', 'Decay mode', 'Half Life',
                              'Parent'
                          ])  #crea  la tabla
        print(df)  #imprime la tabla

    print("\n%d results were found" % (len(DBInfo)))
    CloseDatabase(conexion)
    return 0
Exemple #2
0
def isotopeFun(ListOpt):

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

    List = ListOpt.copy()
    List.pop(0)

    try:
        conexion = OpenDatabase(pathfile)
    except:
        sys.stderr.write(
            '------------------------------------------------------\n')
        sys.stderr.write(
            'ERROR: Database cannot be read. Please, be sure that database is in the folder myDatabase.\n'
        )
        sys.stderr.write(
            '------------------------------------------------------\n')
        return 20
    for element in List:
        Isotope = LookForElement(conexion, element, order='ASC')
        if len(Isotope) == 0:
            print('\nThe isotope consulted is ' + element)
            print('The query did not give any result.')
        else:
            Eg, Ig, Decay, Half, Parent = [], [], [], [], []
            for Ele in Isotope:
                Eg.append(str(Ele[1]) + ' (' + str(Ele[2]) + ')')
                Ig.append(str(Ele[3]) + ' (' + str(Ele[4]) + ')')
                Decay.append(Ele[5])
                Half.append(
                    str(Ele[6]) + ' ' + str(Ele[7]) + ' (' + str(Ele[8]) + ')')
                Parent.append(Ele[10])
            pd.set_option('display.max_rows', None)
            df = pd.DataFrame(list(zip(Eg, Ig, Decay, Half, Parent)),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay mode',
                                  'Half Life', 'Parent'
                              ])  #crea  la tabla
            print('For the isotope ' + element +
                  ' the gamma decays found are: \n')
            print(df)
            print('\n')

    CloseDatabase(conexion)
    return 0
Exemple #3
0
def NormIntensity(ListOpt):

    pathfile = os.path.realpath(__file__)
    pathfile = pathfile.strip('normintensity.py')
    List = ListOpt.copy()
    List.pop(0)

    try:
        conexion = OpenDatabase(pathfile)
    except:
        print('------------------------------------------------------')
        print(
            'ERROR: Database cannot be read. Please, be sure that database is in the folder myDatabase.'
        )
        print('------------------------------------------------------')
        return 20
    for element in List:
        Isotope = GetIntensities2(conexion, element, order='ASC')
        if len(Isotope) == 0:
            print('\nThe isotope consulted is ' + element)
            print('The query did not give any result.')
        else:
            Eg, Ig, IgR, Parent = [], [], [], []
            for Ele in Isotope:
                Eg.append(str(Ele[1]) + ' (' + str(Ele[2]) + ')')
                Ig.append(str(Ele[3]) + ' (' + str(Ele[4]) + ')')
                IgR.append(str(Ele[5]))
                Parent.append(Ele[6])
            pd.set_option('display.max_rows', None)  #imprime todas las filas
            df = pd.DataFrame(list(zip(Eg, Ig, IgR, Parent)),
                              columns=[
                                  'Eg [keV]', 'Ig (%)',
                                  'Normalized Intensities', 'Parent'
                              ])  #crea  la tabla
            print('For the isotope ' + element +
                  ' the gamma decays found are: \n')
            print(df)  #imprime la tabla
            print('\n')

    CloseDatabase(conexion)
    return 0
Exemple #4
0
def Parent(ListOpt):
    List = ListOpt.copy()
    List.pop(0)

    if len(List) == 0:
        print("error: --parent option needs an argument")
        return 400

    pathfile = os.path.realpath(__file__)
    pathfile = pathfile.strip('isoparent.py')
    conexion = OpenDatabase(pathfile)

    for Isotope in List:
        MainChainIso, Child = GetChainAndChild(conexion, Isotope)
        if MainChainIso == None or Child == None:

            print('Isotope: ' + Isotope + ' -- Parent: ' + 'None' +
                  ' --Child: ' + 'None' + '\n')
            print(
                'There is not enough information in the database or the isotope '
                + Isotope + ' do not have Child or parents isotopes. \n')

        else:

            MainChain = GetMainChain(conexion, MainChainIso)
            if '+' in MainChain:
                AuxStr = MainChain.split('+')[1]
                Parentiso = AuxStr.split('#')[0]
            else:
                Parentiso = MainChain[0].split('#')[0]

            print('Isotope: ' + Isotope + ' -- Parent: ' + Parentiso +
                  ' --Child: ' + Child + '\n')

    CloseDatabase(conexion)
    return 0
Exemple #5
0
def Parent(ListOpt):
    List = ListOpt.copy()
    List.pop(0)  
    
    if len(List) == 0:
        sys.stderr.write("error: --parent option needs an argument\n")
        return 400
    
    pathfile = os.path.realpath(__file__)
    if operatingSystem == 'Linux' or operatingSystem == 'Darwin':
        pathfile = pathfile.replace('/modules/isoparent.py','')
    elif operatingSystem == 'Windows':
        pathfile = pathfile.replace('\\modules\\isoparent.py','')

    conexion = OpenDatabase(pathfile)

    for Isotope in List:
        MainChainIso,Child = GetChainAndChild(conexion,Isotope)
        if MainChainIso == None or Child == None:
        
            print('Isotope: ' + Isotope + ' -- Parent: ' + 'None' + ' --Child: ' + 'None' +  '\n')
            print('There is not enough information in the database or the isotope ' + Isotope + ' do not have Child or parents isotopes. \n')
        
        else:
        
            MainChain = GetMainChain(conexion,MainChainIso)
            if '+' in MainChain:
                AuxStr = MainChain.split('+')[1]
                Parentiso = AuxStr.split('#')[0]
            else:
                Parentiso = MainChain[0].split('#')[0]

            print('Isotope: ' + Isotope + ' -- Parent: ' + Parentiso + ' --Child: ' + Child + '\n')
        
    CloseDatabase(conexion)
    return 0
Exemple #6
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
Exemple #7
0
def fuzzyrankFun(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:
        print("error: --fuzzyRank 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)
    minRange = infoDict['Range']['start']
    maxRange = infoDict['Range']['end']
    del infoDict['Range']

    myFileDict=getMyFileDictRankAdv(List)
    
    myFilename=myFileDict['specFiles'][0]
              
    if len(myFileDict['specFiles']) > 1:
       
        print(' Error: to many files to do autopeak\n')

    #elif not myFilename.endswith('.info'):       
    else:   
        myExtension = myFilename.split(".")[-1] #verifies the file extention
        if myExtension == 'info':
            print('The file cannot be an info file.')
            return 120

    noCalFlag = False
    mySpecialDict = functionDictAdv[myExtension](myFilename,noCalFlag) #fill de dictionary
                                                                #from data file
    myDataList = mySpecialDict['theList']
    #fittingDict = doFittingStuff(infoDict,myDataList)
    gilmoreDict = doGilmoreStuff(infoDict,myDataList)
    gilmoreDictKeys = list(gilmoreDict.keys())

    idxPairL = []
    for DictEle in infoDict.values():
        ####
        if op1Flag:
            deltaEle = (DictEle['end']-DictEle['start'])*.1 #peak +/- % of the infoFile range
            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__)
    pathfile = pathfile.rstrip('fuzzyrank.py')
    conexion = OpenDatabase(pathfile)

    memoLenDict={}

    isoCountD = {}
    DBInfoL = []
    DBInfoDL = []
    #tMinE,tMaxE = infoDict['theList'][0],infoDict['theList'][-1]
    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(EnergyRange(conexion,iEner,fEner))
        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)
        #DBInfoDLshortKeys = list(DBInfoDLshort.keys())
    else:
        DBInfoDLshort = DBInfoDL.copy()
    fuzzyMax = fuzzyinference(1,1,0)
    DevRankD = {}
    fuzzyRank = {}
    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])
            fuzzyRank[Key] = fuzzyinference(memoLenDict[Key][1]/memoLenDict[Key][0],memoLenDict[Key][2],DevRankD[Key])
        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
                #ECM += ((NormPeakIntensity/MultiPeakIntensity)-(gilmoreDict[gilmoreDictKeys[Peak]][1]/NetAreaTot))**2 
            DevRankD[Key] = (memoLenDict[Key][0]/memoLenDict[Key][1])*sqrt(ECM/len(memoLenDict[Key][3]))
            fuzzyRank[Key] = fuzzyinference(memoLenDict[Key][1]/memoLenDict[Key][0],memoLenDict[Key][2],DevRankD[Key])/fuzzyMax

    Ranges = []
    for idxR, DBInfoD in zip(idxPairL,DBInfoDL):
        iEner = idxR[0]
        fEner = idxR[1]
        Ranges.append([iEner,fEner])
        Eg , Ig , Decay, Half , Parent, rank, rank2 = [],[],[],[],[],[],[]
        for Key in DBInfoD:
            #Ele = DBInfoD[Key]
            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] ')# + str(Ele[6]) +' ' +str(Ele[7]) + ' ('+str(Ele[8])+')')
                Parent.append(Ele[-1])
                rank.append(DevRankD[Key])
                rank2.append(fuzzyRank[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) #imprime todas las filas
            df = pd.DataFrame(sorted(list(zip(Eg,Ig,Decay,Half,Parent,rank,rank2)),key=lambda x: (x[6],-x[5]),reverse=True),columns=['Eg [keV]','Ig (%)','Decay m','Half Life','Parent','Adj MSE','Membership'])#crea  la tabla
            print(df)
            #print(df.sort_values(by=['Membership'], ascending=False))
        else:
            pd.set_option('display.max_rows', 10)
            df = pd.DataFrame(sorted(list(zip(Eg,Ig,Decay,Half,Parent,rank,rank2)),key=lambda x: (x[6],-x[5]),reverse=True),columns=['Eg [keV]','Ig (%)','Decay mode','Half Life','Parent','Adj MSE','Membership'])#crea  la tabla
            print(df.head(10))
            #print(df.sort_values(by=['Membership'], ascending=False).head(10)) #print('\nOnly the first 10')
            
        if wofFlag:
            try:
                if filterFlag:
                    myfilename = infoFile.strip('.info') + '_RankFuzz_filter.txt'
                else:
                    myfilename = infoFile.strip('.info') + '_RankFuzz.txt'
                
                WriteOutputFileRR(myfilename,df,iEner,fEner)
                print('-----------------------------------------')
                print('The file was saved as:')
                print(myfilename)
                print('-----------------------------------------')
            except IOError:
                print('ERROR: An unexpected error ocurrs. Data could not be saved.')
    
    return 0
Exemple #8
0
def halfSortFun(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 len(List) == 0:
        sys.stderr.write("error: --energyRanges option needs an argument\n")
        return 0

    infoFile = List[0]

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

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

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

    conexion = OpenDatabase(pathfile)

    for idxR in idxPairL:
        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)

        Eg, Ig, Decay, Half, Parent = [], [], [], [], []
        for Element in DBInfoD:
            for ps in range(0, len(DBInfoD[Element]), 1):
                Eg.append(
                    str(DBInfoD[Element][ps][1]) + ' (' +
                    str(DBInfoD[Element][ps][2]) + ')')
                Ig.append(round(DBInfoD[Element][ps][3], 2))
                Decay.append(DBInfoD[Element][ps][5])
                x = halfLifeUnit(DBInfoD[Element][ps])
                if x == 0:
                    y = str(x)
                else:
                    y = str('{0:.2e}'.format(x))

                Half.append(y + ' [s] ')
                Parent.append(DBInfoD[Element][ps][-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)
            pd.options.display.float_format = '{:,.5f}'.format
            df = pd.DataFrame(sorted(list(zip(Eg, Ig, Decay, Half, Parent)),
                                     key=lambda x: float(x[3][:-4]),
                                     reverse=True),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay m', 'Half Life',
                                  'Parent'
                              ])  #crea  la tabla
            print(df)
        else:
            pd.set_option('display.max_rows', None)
            df = pd.DataFrame(sorted(list(zip(Eg, Ig, Decay, Half, Parent)),
                                     key=lambda x: float(x[3][:-4]),
                                     reverse=True),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay m', 'Half Life',
                                  'Parent'
                              ])  #crea  la tabla
            print(df.head(10))

        if wofFlag:
            try:
                myfilename = infoFile.strip('.info') + '_rank_C.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'
                )
                break

    return 0
Exemple #9
0
def ChainRankFun(ListOpt):
    List = ListOpt.copy()
    List.pop(0)
    i = 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 '--peak' in List:
        addFlag = True
        List.remove('--peak')
        xId = -2
    else:
        addFlag = False
        xId = -1

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

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

    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/chainRank.py', '')
    elif operatingSystem == 'Windows':
        pathfile = pathfile.replace('\\modules\\chainRank.py', '')

    conexion = OpenDatabase(pathfile)

    ChainDict = {}

    memoLenDict = {}
    isoPeakLL = []
    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

    for idxR in idxPairL:
        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
            DBInfoD[e[-1]] = e
        DBInfoDL.append(DBInfoD)
        isoPeakL = []
        for Ele in DBInfo:
            iso = Ele[-1]
            if [iso, 1, 0, 0] not in isoPeakL:
                isoPeakL.append([
                    iso, 1, 0, Ele[10]
                ])  #So that there is only one count of each isotope per peak
                if iso not in isoCountD:  #Considering the number of entries in the energy range of the histogram
                    if iso not in memoLenDict:
                        memoLenDict[iso] = len(
                            GetIntensities(conexion, tMinE, tMaxE, iso))
                    nInRange = memoLenDict[iso]
                    isoCountD[iso] = [0, nInRange, 0]
                isoCountD[iso][0] += 1

            MainChainIso, _ = GetChainAndChild(conexion, Ele[-1])
            if MainChainIso not in ChainDict and MainChainIso is not None:
                ChainDict[MainChainIso] = [
                    chaintoList(GetMainChain(conexion, MainChainIso)[0]),
                    [0, 0]
                ]

        isoPeakLL.append(isoPeakL)

    IgRDict = {}

    for DBInfo in DBInfoL:
        for Ele in DBInfo:
            iso = Ele[-1]
            if iso not in IgRDict:
                IgRDict[iso] = Ele[10]
            else:
                IgRDict[iso] += Ele[10]

    for isoLL in isoPeakLL:
        for isoL in isoLL:
            iso = isoL[0]
            isoC = isoCountD[iso][0]
            isoL[1] = isoC
            isoL[2] = isoC / isoCountD[iso][1]
            isoCountD[iso][2] += isoL[-1]
            isoL[3] = IgRDict[iso]

    for keyChain in ChainDict.keys():
        for chainList in ChainDict[keyChain][0]:
            try:
                ChainDict[keyChain][1][
                    0] += isoCountD[chainList][0] / isoCountD[chainList][1]
            except:
                continue

            try:
                ChainDict[keyChain][1][1] += IgRDict[chainList]
            except:
                continue

        ChainDict[keyChain][1][0] /= len(ChainDict[keyChain][0]) - 1
        ChainDict[keyChain][1][1] /= len(ChainDict[keyChain][0]) - 1

    Ranges = []
    chainRankIso = {}

    for ChainAnsestor in ChainDict:
        ChainList = ChainDict[ChainAnsestor]
        for ChainMember in ChainList[0]:
            if ChainMember not in chainRankIso:
                chainRankIso[ChainMember] = ChainList[1]

    for idxR, isoPeakL, DBInfoD in zip(idxPairL, isoPeakLL, DBInfoDL):
        iEner = idxR[0]
        fEner = idxR[1]
        Ranges.append([iEner, fEner])

        print(
            '\nThe energy range consulted is between %.2f keV and %.2f keV.\n'
            % (iEner, fEner))
        Eg , Ig , Decay, Half , Parent, rank, rank2,rank3, CR2, CR3 = [],[],[],[],[],[],[],[],[],[]
        for pInfo in isoPeakL:
            iso = pInfo[0]
            if iso not in chainRankIso:
                cr2, cr3 = [0, 0]
            else:
                cr2, cr3 = chainRankIso[iso]

            CR2.append(cr2)
            CR3.append(cr3)

            Ele = DBInfoD[iso]
            Eg.append(str(Ele[1]))  #+' ('+str(Ele[2])+')')
            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(pInfo[1])
            rank2.append(round(pInfo[2], 3))
            rank3.append(round(pInfo[-1], 3))

            pd.set_option('display.max_rows', None)
            pd.options.display.float_format = '{:,.5f}'.format
            df = pd.DataFrame(sorted(list(
                zip(Eg, Ig, Decay, Half, Parent, rank, rank2, rank3, CR2,
                    CR3)),
                                     key=lambda x: (x[xId], x[1]),
                                     reverse=True),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay m', 'Half Life',
                                  'Parent', 'Rank C', 'Rank D', 'Rank E',
                                  'Rank I', 'Rank J'
                              ])  #crea  la tabla

        if allFlag:
            print(df)
        else:
            print(df.head(10))

        if wofFlag:
            try:
                if addFlag:
                    myfilename = infoFile.strip('.info') + '_rank_I.txt'
                else:
                    myfilename = infoFile.strip('.info') + '_rank_J.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'
                )
                break

    return 0
Exemple #10
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
Exemple #11
0
def rankFun(ListOpt):
    List = ListOpt.copy()
    List.pop(0)
    i = 0  #for rank op
    rankOp = []

    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 'and' in List:
        addFlag = True
        List.remove('and')
    else:
        addFlag = False

    for Arg in List:
        try:
            rankOp.append(int(Arg))
            if rankOp[i] > 0 and rankOp[i] < 4:

                if type(rankOp[i]) == int:
                    i += 1

            #break
        except:
            rankOp.append(3)
            continue

    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 100
    if not infoFile.endswith('.info'):
        print("error: %s needs a .info extension" % (infoFile))
        return 101
    infoDict = getDictFromInfoFile(infoFile)
    minRange = infoDict['Range']['start']
    maxRange = infoDict['Range']['end']
    del infoDict['Range']

    idxPairL = []
    for DictEle in infoDict.values():

        if addFlag:
            if rankOp[2] == 1:
                rankSort = 'Rank'

                idxPairL.append([DictEle['start'], DictEle['end']])

            elif rankOp[2] == 2:
                rankSort = 'Rank2'

                idxPairL.append([DictEle['start'], DictEle['end']])

            elif rankOp[2] == 3:
                rankSort = 'Rank3'

                idxPairL.append([DictEle['start'], DictEle['end']])

            else:
                idxPairL.append([DictEle['start'], DictEle['end']])
                print(
                    'theres n|o rank op {}, please try an option between 1 and 3'
                    .format(rankOp))
                break
        else:
            rankSort = 'Rank3'

            idxPairL.append([DictEle['start'], DictEle['end']])

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

    memoLenDict = {}
    isoPeakLL = []
    isoCountD = {}
    DBInfoL = []
    DBInfoDL = []
    #tMinE,tMaxE = infoDict['theList'][0],infoDict['theList'][-1]
    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

    for idxR in idxPairL:
        iEner = idxR[0]
        fEner = idxR[1]
        #DBInfoL.append(EnergyRange(conexion,iEner,fEner))
        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
            DBInfoD[e[-1]] = e
        DBInfoDL.append(DBInfoD)
        isoPeakL = []
        for Ele in DBInfo:
            iso = Ele[-1]
            if [iso, 1, 0, 0] not in isoPeakL:
                isoPeakL.append([
                    iso, 1, 0, Ele[10]
                ])  #So that there is only one count of each isotope per peak
                if iso not in isoCountD:  #Considering the number of entries in the energy range of the histogram
                    if iso not in memoLenDict:
                        #memoLenDict[iso]=len(EnergyRange(conexion,tMinE,tMaxE,iso))
                        memoLenDict[iso] = len(
                            GetIntensities(conexion, tMinE, tMaxE, iso))
                    nInRange = memoLenDict[iso]
                    isoCountD[iso] = [0, nInRange, 0]
                isoCountD[iso][0] += 1
        isoPeakLL.append(isoPeakL)

    IgRDict = {}

    for DBInfo in DBInfoL:
        for Ele in DBInfo:
            iso = Ele[-1]
            if iso not in IgRDict:
                IgRDict[iso] = Ele[10]
            else:
                IgRDict[iso] += Ele[10]

    for isoLL in isoPeakLL:
        for isoL in isoLL:
            iso = isoL[0]
            isoC = isoCountD[iso][0]
            isoL[1] = isoC
            isoL[2] = isoC / isoCountD[iso][1]
            isoCountD[iso][2] += isoL[-1]
            isoL[3] = IgRDict[iso]

        if addFlag:
            isoLL.sort(key=lambda x: x[rankOp[1]],
                       reverse=True)  # Main Sort of RANK HGE
        else:
            if i:
                isoLL.sort(key=lambda x: x[rankOp[1]],
                           reverse=True)  # Main Sort of RANK HGE
            else:
                isoLL.sort(key=lambda x: x[rankOp[0]],
                           reverse=True)  # Main Sort of RANK HGE

    Ranges = []
    for idxR, isoPeakL, DBInfoD in zip(idxPairL, isoPeakLL, DBInfoDL):
        iEner = idxR[0]
        fEner = idxR[1]
        Ranges.append([iEner, fEner])

        print(
            '\nThe energy range consulted is between %.2f keV and %.2f keV.\n'
            % (iEner, fEner))
        Eg , Ig , Decay, Half , Parent, rank, rank2,rank3 = [],[],[],[],[],[],[],[]
        for pInfo in isoPeakL:
            iso = pInfo[0]
            Ele = DBInfoD[iso]
            Eg.append(str(Ele[1]) + ' (' + str(Ele[2]) + ')')
            Ig.append(round(Ele[3],
                            2))  #+' ('+str(Ele[4])+')') #Normalized Intensity
            Decay.append(Ele[5])
            #Half.append(str(Ele[6])+' '+Ele[7]+' ('+str(Ele[8])+')')
            x = halfLifeUnit(Ele)
            if x == 0:
                y = str(x)
            else:
                y = str('{0:.2e}'.format(x))
            Half.append(
                y + ' [s] '
            )  # + str(Ele[6]) +' ' +str(Ele[7]) + ' ('+str(Ele[8])+')')
            Parent.append(Ele[-1])
            rank.append(pInfo[1])
            rank2.append(round(pInfo[2], 3))
            rank3.append(round(pInfo[-1], 3))

        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, rank, rank2, rank3)),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay m', 'Half Life',
                                  'Parent', 'Rank', 'Rank2', 'Rank3'
                              ])  #crea  la tabla
            if addFlag:
                print(df.sort_values(by=[rankSort], ascending=False))
            else:
                print(df)  #.sort_values(by=['Rank2'], ascending=False))
        else:
            pd.set_option('display.max_rows', len(Ele))
            df = pd.DataFrame(
                list(zip(Eg, Ig, Decay, Half, Parent, rank, rank2, rank3)),
                columns=[
                    'Eg [keV]', 'Ig (%)', 'Decay mode', 'Half Life', 'Parent',
                    'Rank', 'Rank2', 'Rank3'
                ])  #crea  la tabla
            if addFlag:
                print(df.head(10).sort_values(
                    by=[rankSort],
                    ascending=False))  #print('\nOnly the first 10')
            else:
                print(
                    df.head(10)
                )  #.sort_values(by=[rankSort], ascending=False)) #print('\nOnly the first 10')

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

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

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

                else:
                    myfilename = infoFile.strip('.info') + '_rank_D.txt'

                if allFlag:
                    if addFlag:
                        WriteOutputFileRR(
                            myfilename,
                            df.sort_values(by=[rankSort], ascending=False),
                            iEner, fEner)
                    else:
                        WriteOutputFileRR(myfilename, df, iEner, fEner)
                else:
                    if addFlag:
                        WriteOutputFileRR(
                            myfilename,
                            df.head(10).sort_values(by=[rankSort],
                                                    ascending=False), iEner,
                            fEner)
                    else:
                        WriteOutputFileRR(myfilename, df.head(10), iEner,
                                          fEner)

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

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

    return 0
Exemple #12
0
def energyFun(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 len(List) == 0:
        print("error: --energyRanges 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 False
    if not infoFile.endswith('.info'):
        print("error: %s needs a .info extension" % (infoFile))
        return False
    infoDict = getDictFromInfoFile(infoFile)
    del infoDict['Range']
    idxPairL = []
    for DictEle in infoDict.values():
        idxPairL.append([DictEle['start'], DictEle['end']])
    #Energy range of the histogram

    DBInfoL = []
    pathfile = os.path.realpath(__file__)
    pathfile = pathfile.strip('energy.py')
    conexion = OpenDatabase(pathfile)
    for idxR in idxPairL:
        iEner = idxR[0]
        fEner = idxR[1]
        DBInfoL.append(EnergyRange(conexion, iEner, fEner))
        DBInfo = DBInfoL[-1]

        print(
            '\nThe energy range consulted is between %.2f keV and %.2f keV.\n'
            % (iEner, fEner))
        Eg, Ig, Decay, Half, Parent = [], [], [], [], []
        for Ele in DBInfo:
            Eg.append(str(Ele[1]) + ' (' + str(Ele[2]) + ')')
            Ig.append(str(Ele[3]) + ' (' + str(Ele[4]) + ')')
            Decay.append(Ele[5])
            Half.append(halfLifeUnit(Ele))
            Parent.append(Ele[10])

        if allFlag:
            pd.set_option('display.max_rows', None)
        else:
            pd.set_option('display.max_rows', len(Ele))

        df = pd.DataFrame(list(zip(Eg, Ig, Decay, Half, Parent)),
                          columns=[
                              'Eg [keV]', 'Ig (%)', 'Decay mode',
                              'Half Life (s)', 'Parent'
                          ])
        if allFlag:
            print(df)
        else:
            print(df.head(10))

        if wofFlag:
            try:
                myfilename = infoFile.strip('.info') + '_energyRanges.txt'
                WriteOutputFileRR(myfilename, df, iEner, fEner)
                print('-----------------------------------------')
                print('The file was saved as:')
                print(myfilename)
                print('-----------------------------------------')
            except IOError:
                print(
                    'ERROR: An unexpected error ocurrs. Data could not be saved.'
                )

    CloseDatabase(conexion)
    return 0
Exemple #13
0
def rankImp(ListOpt):
    List = ListOpt.copy()
    List.pop(0)
    i = 0  #for rank op
    rankOp = []
    rankOp2 = [None, None, None]
    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:
            if Arg == 'D':
                #rankOp.append(int(Arg))
                rankOp.append(1)

            elif Arg == 'E':
                #rankOp.append(int(Arg))
                rankOp.append(2)

            elif Arg == 'F':
                #rankOp.append(int(Arg))
                rankOp.append(3)
            else:
                continue
        except:
            if len(List) <= 1:
                rankOp.append(3)
            continue

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

    rankOp = removeDuplicates(rankOp)
    rankOp2 = [x - 4 for x in rankOp]
    rankOp2.append(1)

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

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

    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_imp.py', '')
    elif operatingSystem == 'Windows':
        pathfile = pathfile.replace('\\modules\\rank_imp.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:
            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:
                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)

    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_D.txt'

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

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

        else:
            myfilename = infoFile.strip('.info') + '_rank_F.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 = [],[],[],[],[],[],[],[]
        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(memoLenDict[Ele[-1]][1])
                rank2.append(
                    round(memoLenDict[Ele[-1]][1] / memoLenDict[Ele[-1]][0],
                          3))
                rank3.append(round(memoLenDict[Ele[-1]][2], 3))

        Eg, Ig, Decay, Half, Parent, rank, rank2, rank3 = (
            list(t) for t in zip(
                *sorted(zip(Eg, Ig, Decay, Half, Parent, rank, rank2, rank3),
                        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)
            pd.options.display.float_format = '{:,.5f}'.format
            df = pd.DataFrame(list(
                zip(Eg, Ig, Decay, Half, Parent, rank, rank2, rank3)),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay m', 'Half Life',
                                  'Parent', 'Rank D', 'Rank E', 'Rank F'
                              ])  #crea  la tabla
            print(df)

        else:
            pd.set_option('display.max_rows', len(Ele))
            df = pd.DataFrame(
                list(zip(Eg, Ig, Decay, Half, Parent, rank, rank2, rank3)),
                columns=[
                    'Eg [keV]', 'Ig (%)', 'Decay mode', 'Half Life', 'Parent',
                    'Rank D', 'Rank E', 'Rank F'
                ])  #crea  la tabla
            print(df.head(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.'
                )
                break

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

    return 0
Exemple #14
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
Exemple #15
0
def ChainRankFun(ListOpt):
    List = ListOpt.copy()
    List.pop(0)
    i = 0  #for rank op
    #rankOp = []

    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 '--peak' in List:
        addFlag = True
        List.remove('--peak')
        xId = -2
    else:
        addFlag = False
        xId = -1

    # for Arg in List:
    #     try:
    #         rankOp.append(int(Arg))
    #         if rankOp[i] > 0 and rankOp[i] < 4:

    #             if type(rankOp[i]) == int:
    #                 i += 1

    #         #break
    #     except:
    #         rankOp.append(3)
    #         continue

    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 100
    if not infoFile.endswith('.info'):
        print("error: %s needs a .info extension" % (infoFile))
        return 101
    infoDict = getDictFromInfoFile(infoFile)
    minRange = infoDict['Range']['start']
    maxRange = infoDict['Range']['end']
    del infoDict['Range']

    idxPairL = []
    for DictEle in infoDict.values():

        # if addFlag :
        #     if rankOp[2] == 1:
        #         rankSort = 'Rank'

        #         idxPairL.append([DictEle['start'],DictEle['end']])

        #     elif rankOp[2] == 2:
        #         rankSort = 'Rank2'

        #         idxPairL.append([DictEle['start'],DictEle['end']])

        #     elif rankOp[2] == 3:
        #         rankSort = 'Rank3'

        #         idxPairL.append([DictEle['start'],DictEle['end']])

        #     else:
        #         idxPairL.append([DictEle['start'],DictEle['end']])
        #         print('theres n|o rank op {}, please try an option between 1 and 3'.format(rankOp))
        #         break
        # else:
        #     rankSort = 'Rank3'

        idxPairL.append([DictEle['start'], DictEle['end']])

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

    ChainDict = {}

    memoLenDict = {}
    isoPeakLL = []
    isoCountD = {}
    DBInfoL = []
    DBInfoDL = []
    #tMinE,tMaxE = infoDict['theList'][0],infoDict['theList'][-1]
    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

    for idxR in idxPairL:
        iEner = idxR[0]
        fEner = idxR[1]
        #DBInfoL.append(EnergyRange(conexion,iEner,fEner))
        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
            DBInfoD[e[-1]] = e
        DBInfoDL.append(DBInfoD)
        isoPeakL = []
        for Ele in DBInfo:
            iso = Ele[-1]
            if [iso, 1, 0, 0] not in isoPeakL:
                isoPeakL.append([
                    iso, 1, 0, Ele[10]
                ])  #So that there is only one count of each isotope per peak
                if iso not in isoCountD:  #Considering the number of entries in the energy range of the histogram
                    if iso not in memoLenDict:
                        #memoLenDict[iso]=len(EnergyRange(conexion,tMinE,tMaxE,iso))
                        memoLenDict[iso] = len(
                            GetIntensities(conexion, tMinE, tMaxE, iso))
                    nInRange = memoLenDict[iso]
                    isoCountD[iso] = [0, nInRange, 0]
                isoCountD[iso][0] += 1

            MainChainIso, _ = GetChainAndChild(conexion, Ele[-1])
            if MainChainIso not in ChainDict and MainChainIso is not None:
                ChainDict[MainChainIso] = [
                    chaintoList(GetMainChain(conexion, MainChainIso)[0]),
                    [0, 0]
                ]

        isoPeakLL.append(isoPeakL)

    IgRDict = {}

    for DBInfo in DBInfoL:
        for Ele in DBInfo:
            iso = Ele[-1]
            if iso not in IgRDict:
                IgRDict[iso] = Ele[10]
            else:
                IgRDict[iso] += Ele[10]

    for isoLL in isoPeakLL:
        for isoL in isoLL:
            iso = isoL[0]
            isoC = isoCountD[iso][0]
            isoL[1] = isoC
            isoL[2] = isoC / isoCountD[iso][1]
            isoCountD[iso][2] += isoL[-1]
            isoL[3] = IgRDict[iso]

    for keyChain in ChainDict.keys():
        for chainList in ChainDict[keyChain][0]:
            try:
                ChainDict[keyChain][1][
                    0] += isoCountD[chainList][0] / isoCountD[chainList][1]
            except:
                continue

            try:
                ChainDict[keyChain][1][1] += IgRDict[chainList]
            except:
                continue

        ChainDict[keyChain][1][0] /= len(ChainDict[keyChain][0]) - 1
        ChainDict[keyChain][1][1] /= len(ChainDict[keyChain][0]) - 1

        # if addFlag:
        #     isoLL.sort(key = lambda x: x[rankOp[1]],reverse = True) # Main Sort of RANK HGE
        # else:
        #     if i:
        #         isoLL.sort(key = lambda x: x[rankOp[1]],reverse = True) # Main Sort of RANK HGE
        #     else:
        #         isoLL.sort(key = lambda x: x[rankOp[0]],reverse = True) # Main Sort of RANK HGE

    Ranges = []
    chainRankIso = {}

    for ChainAnsestor in ChainDict:
        ChainList = ChainDict[ChainAnsestor]
        for ChainMember in ChainList[0]:
            if ChainMember not in chainRankIso:
                chainRankIso[ChainMember] = ChainList[1]

    for idxR, isoPeakL, DBInfoD in zip(idxPairL, isoPeakLL, DBInfoDL):
        iEner = idxR[0]
        fEner = idxR[1]
        Ranges.append([iEner, fEner])

        print(
            '\nThe energy range consulted is between %.2f keV and %.2f keV.\n'
            % (iEner, fEner))
        Eg , Ig , Decay, Half , Parent, rank, rank2,rank3, CR2, CR3 = [],[],[],[],[],[],[],[],[],[]
        for pInfo in isoPeakL:
            iso = pInfo[0]
            if iso not in chainRankIso:
                cr2, cr3 = [0, 0]
            else:
                cr2, cr3 = chainRankIso[iso]

            CR2.append(cr2)
            CR3.append(cr3)

            Ele = DBInfoD[iso]
            Eg.append(str(Ele[1]) + ' (' + str(Ele[2]) + ')')
            Ig.append(round(Ele[3],
                            2))  #+' ('+str(Ele[4])+')') #Normalized Intensity
            Decay.append(Ele[5])
            #Half.append(str(Ele[6])+' '+Ele[7]+' ('+str(Ele[8])+')')
            x = halfLifeUnit(Ele)
            if x == 0:
                y = str(x)
            else:
                y = str('{0:.2e}'.format(x))
            Half.append(
                y + ' [s] '
            )  # + str(Ele[6]) +' ' +str(Ele[7]) + ' ('+str(Ele[8])+')')
            Parent.append(Ele[-1])
            rank.append(pInfo[1])
            rank2.append(round(pInfo[2], 3))
            rank3.append(round(pInfo[-1], 3))

            pd.set_option('display.max_rows', None)  #imprime todas las filas
            pd.options.display.float_format = '{:,.5f}'.format
            df = pd.DataFrame(sorted(list(
                zip(Eg, Ig, Decay, Half, Parent, rank, rank2, rank3, CR2,
                    CR3)),
                                     key=lambda x: x[xId],
                                     reverse=True),
                              columns=[
                                  'Eg [keV]', 'Ig (%)', 'Decay m', 'Half Life',
                                  'Parent', 'Rank', 'Rank2', 'Rank3', 'CR2',
                                  'CR3'
                              ])  #crea  la tabla

        if allFlag:
            print(df)
        else:
            print(df.head(10))

        if wofFlag:
            try:
                if addFlag:
                    myfilename = infoFile.strip(
                        '.info') + '_Rank_Hdecay_Chain.txt'
                else:
                    myfilename = infoFile.strip(
                        '.info') + '_Rank_Gdecay_Chain.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:
                print(
                    'ERROR: An unexpected error ocurrs. Data could not be saved.'
                )
                break

    return 0


# def ChainRankFun(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 len(List) == 0:
#         print("error: --chainRank option needs an argument")
#         return 3500

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

#     infoDict=getDictFromInfoFile(infoFile)
#     minRange = infoDict['Range']['start']
#     maxRange = infoDict['Range']['end']
#     #del infoDict['Range']

#     pathfile = os.path.realpath(__file__)
#     pathfile = pathfile.strip('chainRank.py')
#     conexion = OpenDatabase(pathfile)

#     ChainDict = {}

#     memoLenDict={}
#     isoPeakLL = []
#     isoCountD = {}
#     DBInfoL = []
#     DBInfoDL = []
#     #tMinE,tMaxE = infoDict['theList'][0],infoDict['theList'][-1]
#     tMinEL = []
#     tMaxEL = []
#     idxPairL = []

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

#     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

#     for idxR in idxPairL:
#         iEner = idxR[0]
#         fEner = idxR[1]
#         #DBInfoL.append(EnergyRange(conexion,iEner,fEner))
#         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
#             DBInfoD[e[-1]] = e
#         DBInfoDL.append(DBInfoD)
#         isoPeakL = []
#         for Ele in DBInfo:
#             MainChainIso, _ = GetChainAndChild(conexion,Ele[-1])
#             if MainChainIso not in ChainDict and MainChainIso is not None:
#                 ChainDict[MainChainIso] = [chaintoList(GetMainChain(conexion,MainChainIso)[0]),0]

#             pass

#         #     iso = Ele[-1]
#         #     if [iso,1,0,0] not in isoPeakL:
#         #         isoPeakL.append([iso,1,0,Ele[10]]) #So that there is only one count of each isotope per peak
#         #         if iso not in isoCountD: #Considering the number of entries in the energy range of the histogram
#         #             if iso not in memoLenDict:
#         #                 #memoLenDict[iso]=len(EnergyRange(conexion,tMinE,tMaxE,iso))
#         #                 memoLenDict[iso]=len(GetIntensities(conexion,tMinE,tMaxE,iso))
#         #             nInRange=memoLenDict[iso]
#         #             isoCountD[iso] = [0,nInRange,0]
#         #         isoCountD[iso][0] += 1
#         # isoPeakLL.append(isoPeakL)

#     # for Isotope in List:
#     #     MainChainIso,Child = GetChainAndChild(conexion,Isotope)
#     #     if MainChainIso == None or Child == None:

#     #         print('Isotope: ' + Isotope + ' -- Parent: ' + 'None' + ' --Child: ' + 'None' +  '\n')
#     #         print('There is not enough information in the database or the isotope ' + Isotope + ' do not have Child or parents isotopes. \n')

#     #     else:

#     #         MainChain = GetMainChain(conexion,MainChainIso)
#     #         if '+' in MainChain:
#     #             AuxStr = MainChain.split('+')[1]
#     #             Parentiso = AuxStr.split('#')[0]
#     #         else:
#     #             Parentiso = MainChain[0].split('#')[0]

#     #         print('Isotope: ' + Isotope + ' -- Parent: ' + Parentiso + ' --Child: ' + Child + '\n')

#     CloseDatabase(conexion)
#     return 0