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
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
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
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
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: 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 10000 if not infoFile.endswith('.info'): print("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) 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('rankAdv.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() 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 #ECM += ((NormPeakIntensity/MultiPeakIntensity)-(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: #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]) 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)), key=lambda x:x[5] ),index = None,columns=['Eg [keV]','Ig (%)','Decay m','Half Life','Parent','Adj MSE'])#crea la tabla print(df)#.sort_values(by=['Adj MSE'], ascending=True)) else: pd.set_option('display.max_rows', 10) df = pd.DataFrame(sorted(list(zip(Eg,Ig,Decay,Half,Parent,rank)), key=lambda x:x[5] ),index = None ,columns=['Eg [keV]','Ig (%)','Decay mode','Half Life','Parent','Adj MSE'])#crea la tabla print(df.head(10)) #print(df.sort_values(by=['Adj MSE'], ascending=True).head(10)) #print('\nOnly the first 10') if wofFlag: try: if filterFlag: myfilename = infoFile.strip('.info') + '_RankAdv_filter.txt' else: myfilename = infoFile.strip('.info') + '_RankAdv.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