Exemple #1
0
    def getCR(self,
              outfile,
              mode='kcode',
              tallydic=None,
              cell=None,
              matnum=None,
              volume=None):
        if mode == 'kcode':
            totratedic = self.readNeutronActivity(outfile)
            totfission = totratedic['lossfission']
            activitydic = self.readNeutronActivity(outfile,
                                                   nuclides=[
                                                       '90232', '92234',
                                                       '94240', '91233',
                                                       '92238', '92233',
                                                       '92235', '94239',
                                                       '94241'
                                                   ])

            # CR=Rc(Th232 + U234 + U238 + Pu240 -Pa233) / Ra(U233 + U235 + Pu239 + Pu241)
            CR = (activitydic['90232']['capture'] +
                  activitydic['92234']['capture'] +
                  activitydic['94240']['capture'] +
                  activitydic['92238']['capture'] -
                  activitydic['91233']['capture']) / (
                      activitydic['92233']['capture'] +
                      activitydic['92235']['capture'] +
                      activitydic['94239']['capture'] +
                      activitydic['94241']['capture'] + totfission)
            print(activitydic)
        elif mode == 'fixed':
            nuclidelist = [
                '90232', '91233', '94239', '94240', '94241', '92233', '92234',
                '92235', '92238'
            ]
            captureratedic = {}
            fissratedic = {}
            atomdensitydic = {}
            if not (tallydic and cell and matnum and volume):
                raise CustomError(
                    'Lack cell number, material number, fm tally dictionary and volume of cell!'
                )
            for nuclide in nuclidelist:
                atomdensitydic[nuclide] = self.getNuclideDensity(
                    outfile, cell, matnum, nuclide)
            for tallynum, nuclide in tallydic.items():
                capturetally = self._readFmtally(outfile, tallynum, '102')
                fisstally = self._readFmtally(outfile, tallynum, '-6')
                captureratedic[
                    nuclide] = volume * atomdensitydic[nuclide] * capturetally
                fissratedic[
                    nuclide] = volume * atomdensitydic[nuclide] * fisstally
            CR = (captureratedic['90232']+captureratedic['92234']+captureratedic['92238']+\
                captureratedic['94240']-captureratedic['91233']) / (captureratedic['92233']+\
                captureratedic['92235']+captureratedic['94239']+captureratedic['94241']+\
                fissratedic['92233']+fissratedic['92235']+fissratedic['94239']+\
                fissratedic['94241'])
        else:
            raise CustomError('Only kcode and fixed mode are allowed!')
        return CR
Exemple #2
0
 def getRR(self,
           outfile,
           tallydic=None,
           cell=None,
           matnum=None,
           volume=None):
     nuclidelist = [
         '90232', '91233', '94239', '94240', '94241', '92233', '92234',
         '92235', '92238'
     ]
     captureratedic = {}
     fissratedic = {}
     atomdensitydic = {}
     if not (tallydic and cell and matnum and volume):
         raise CustomError(
             'Lack cell number, material number, fm tally dictionary and volume of cell!'
         )
     for nuclide in nuclidelist:
         atomdensitydic[nuclide] = self.getNuclideDensity(
             outfile, cell, matnum, nuclide)
     for tallynum, nuclide in tallydic.items():
         capturetally = self._readFmtally(outfile, tallynum, '102')
         fisstally = self._readFmtally(outfile, tallynum, '-6')
         captureratedic[
             nuclide] = volume * atomdensitydic[nuclide] * capturetally
         fissratedic[nuclide] = volume * atomdensitydic[nuclide] * fisstally
     # RR=Rc(Th232-Pa233)/Ra(U233)
     if (captureratedic['92233'] + fissratedic['92233']) == 0:
         return 0
     RR = (captureratedic['90232']-captureratedic['91233']) / (captureratedic['92233']\
         +fissratedic['92233'])
     return RR
 def postProcessing(self, mcnpfile, outfilename):
     outputfile = ''.join([mcnpfile, 'o'])
     if os.path.isfile(outputfile):
         print('MCNP5 run finished!')
         keff = self.mtr.readKeff(outputfile)['keff']
         self.mh.deleteFiles(outfilename)
         os.rename(outputfile, outfilename)
     else:
         raise CustomError('MCNP5 did not run successful!')
     return keff
Exemple #4
0
 def copyinp(self, inpname, newinpname):
     try:
         if inpname == newinpname:
             raise CustomError(
                 'The copied file and the the target file are same!')
     except TypeError as e:
         print(e)
         return -1
     with open(inpname, 'r') as fread, open(newinpname, 'w') as fwrite:
         for eachline in fread:
             fwrite.write(eachline)
Exemple #5
0
def mainFunc(filename, toxicitytype='Ac'):
    try:
        if toxicitytype not in ['Ac', 'FP']:
            raise CustomError('Unrecognizedtoxicity type!')
    except TypeError as e:
        print(e)
        return -1

    time = [1, 5]
    totHM = 0
    # read input-dose.inp
    with open(filename, 'r') as fid:
        listfromfile = fid.readlines()
        numoffile = int(listfromfile[1].strip())
        print(numoffile)
        burnup = float(listfromfile[3].strip())
        print(burnup)
        prefixofinp = listfromfile[5].strip().split()[0]
        inpname = '.'.join([prefixofinp, 'txt'])
        print(inpname)
    # create time list
    jj = 1
    for ii in range(4, 23, 3):
        time.append(1 * 10**jj)
        time.append(2 * 10**jj)
        time.append(5 * 10**jj)
        jj += 1
    time = time[:-2]
    # read mass of nuclide and calculate the total HM.
    with open(inpname, 'r') as fid1, open('sum_HM.dat', 'w') as fid2:
        for eachline in fid1:
            linelist = eachline.strip().split()
            if linelist:
                tagofnuclide = int(linelist[0])
                massofnuclide = float(linelist[1])
                if tagofnuclide > 890000:
                    totHM += massofnuclide
        fid2.write('{:}\n'.format('总重金属质量(g)'))
        fid2.write('{:.7e}'.format(totHM))

    #create file 'com_nucl.inp' (nuclide tag, atomnumber, massnumber and mass per total hm in this file).
    with open(inpname, 'r') as fid1, open('com_nucl.inp', 'w') as fid3:
        fid3.write("nuclear  concent(g/MTHN)\n")
        for eachline in fid1:
            linelist = eachline.strip().split()
            if linelist:
                tagofnuclide = int(linelist[0])
                massofnuclide = float(linelist[1])
                atomnumber = int(tagofnuclide / 10000)
                massnumber = int(tagofnuclide / 10) - atomnumber * 1000
                fid3.write('{:^10d} {:^10d} {:^10d} {:^20.7e}\n'.format(
                    tagofnuclide, atomnumber, massnumber,
                    massofnuclide / totHM * 1e6))

    if toxicitytype == 'Ac':
        # for uranium
        basemassnumberofuranium = 231
        atomnumber = 92
        numofnuclideinuranium = 7

        svdata = calculateSVofNuclide(atomnumber, basemassnumberofuranium,
                                      numofnuclideinuranium + 1)
        nuclidelist = ['U-232', 'U-233', 'U-234', 'U-235', 'U-236', 'U-237', \
                        'U-238']
        output(''.join(['SVMTHN_', prefixofinp, '_', 'U', '.dat']),
               nuclidelist,
               time,
               svdata,
               unit='Sv/MTHN')
        output(''.join(['SVGWy_', prefixofinp, '_', 'U', '.dat']),
               nuclidelist,
               time,
               covert2SvperGWy(svdata, burnup),
               unit='Sv/GWy')

        # for plutonium
        basemassnumberofplutonium = 237
        atomnumber = 94
        numofnuclideinplutonium = 7

        svdata = calculateSVofNuclide(atomnumber, basemassnumberofplutonium,
                                      numofnuclideinplutonium + 1)
        nuclidelist = ['Pu-238', 'Pu-239', 'Pu-240', 'Pu-241', 'Pu-242', 'Pu-243',\
            'Pu-244']
        output(''.join(['SVMTHN_', prefixofinp, '_', 'Pu', '.dat']),
               nuclidelist,
               time,
               svdata,
               unit='Sv/MTHN')
        output(''.join(['SVGWy_', prefixofinp, '_', 'Pu', '.dat']),
               nuclidelist,
               time,
               covert2SvperGWy(svdata, burnup),
               unit='Sv/GWy')

        # #for Th
        # basemassnumberofthorium  = 226
        # atomnumber = 90
        # numofnuclideinthorium = 9

        # svdata = calculateSVofNuclide(atomnumber, basemassnumberofthorium, numofnuclideinthorium+1)
        # nuclidelist = ['Th-226', 'Th-227', 'Th-228', 'Th-229', 'Th-230', 'Th-231', 'Th-232', 'Th-233', 'Th-234']
        # output(''.join(['SVMTHN_', prefixofinp,'_', 'Th', '.dat']), nuclidelist, time, svdata, unit='Sv/MTHN')
        # output(''.join(['SVGWy_', prefixofinp,'_', 'Th', '.dat']), nuclidelist, time, covert2SvperGWy(svdata, burnup), unit='Sv/GWy')

        #for Th-Cf
        baseatomnumber = 89
        numofelement = 10
        svdata = []
        for ii in range(1, numofelement):
            atomnumber = ii + baseatomnumber
            # print(atomnumber)
            sv = calculateSVofElement(atomnumber)
            svdata.append(sv)
        tot = [0 * ii for ii in range(len(svdata[0]))]
        for sv in svdata:
            for ii, data in enumerate(sv):
                tot[ii] += data

        svdata.append(tot)
        nuclidelist = [
            'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'total'
        ]
        output(''.join(['SVMTHN_', prefixofinp, '_', 'Ac', '.dat']),
               nuclidelist,
               time,
               svdata,
               unit='Sv/MTHN')
        output(''.join(['SVGWy_', prefixofinp, '_', 'Ac', '.dat']),
               nuclidelist,
               time,
               covert2SvperGWy(svdata, burnup),
               unit='Sv/GWy')
    else:
        #for FP
        baseatomnumber = 1
        numofelement = 80
        skiplist = [48, 52, 67, 76]
        svdata = []
        for ii in range(1, numofelement):
            atomnumber = ii + baseatomnumber
            print("starting atom number: {:}".format(atomnumber))
            if atomnumber in skiplist:
                continue
            sv = calculateSVofElement(atomnumber)
            svdata.append(sv)
        tot = [0 * ii for ii in range(len(svdata[0]))]
        for sv in svdata:
            for ii in range(len(tot)):
                tot[ii] += sv[ii]
        svdata.append(tot)
        nuclidelist = ['total']
        output(''.join(['SVMTHN_', prefixofinp, '_', 'FP', '.dat']),
               nuclidelist,
               time, [svdata[-1]],
               unit='Sv/MTHN')
        output(''.join(['SVGWy_', prefixofinp, '_', 'FP', '.dat']),
               nuclidelist,
               time,
               covert2SvperGWy([svdata[-1]], burnup),
               unit='Sv/GWy')
Exemple #6
0
    def readNeutronActivity(self, outfile, cell=None, nuclides=None):
        """
        Fuction:
            读取mcnp输出文件中的俘获率,泄漏率以及裂变率(归一到一个源中子)
            case1: cell=None, nuclides=None 返回 总的俘获率,泄漏率以及裂变率(loss to fission);
            case2: cell!=None, nuclides=None 返回 cell内的俘获率;
            case3: cell!=None, nuclides!=None 返回 cell内 的nulides 的俘获率, wgt. gain by fission, wgt. gain by (n,xn);
            case4: cell=None, nuclides!=None 返回 nulides 的俘获率, wgt. gain by fission, wgt. gain by (n,xn);

        Input parameter:
            需要读取的 mcnp输出文件名:outfile
            需要读取俘获率的 cell 类型为lists
            需要读取俘获率的 nuclides 类型为lists
        Return:
            case1:返回俘获率,泄漏率以及裂变率,'photonuclear', '(n,xn)', 'loss to (n,xn)', 'prompt fission', 'delayed fission'。返回类型为字典
            case2,3,4:仅返回俘获率,返回类型为字典
        """
        if nuclides:
            try:
                if type(nuclides) != list:
                    raise CustomError('Input type of nuclides should be list!')
            except TypeError as e:
                print(e)
                return -1
        results = {}
        tag = False
        physical_quantity_to_be_read = ['escape', 'loss to fission', 'capture', \
            'photonuclear', '(n,xn)', 'loss to (n,xn)', 'prompt fission', 'delayed fission', 'nucl. interaction']
        if cell is None and nuclides is None:
            with open(outfile, 'r') as fid:
                for eachline in fid:
                    lists = eachline.strip().split()
                    if 'neutron creation' in eachline:
                        tag = True
                    if 'photon creation' in eachline:
                        tag = False
                    if tag:
                        for physiclquantity in physical_quantity_to_be_read:
                            if 'total' in eachline:
                                tag = False
                            elif physiclquantity in eachline:
                                if physiclquantity == 'loss to fission':
                                    results['lossfission'] = float(
                                        lists[lists.index('loss') + 4])
                                elif physiclquantity == 'loss to (n,xn)':
                                    results['loss(n,xn)'] = float(
                                        lists[lists.index('loss') + 4])
                                elif physiclquantity == 'prompt fission':
                                    results['pfission'] = float(
                                        lists[lists.index('prompt') + 3])
                                elif physiclquantity == 'delayed fission':
                                    results['dfission'] = float(
                                        lists[lists.index('delayed') + 3])
                                elif physiclquantity == 'nucl. interaction':
                                    if lists[0] == 'nucl.':
                                        results['nuclinteraction'] = float(
                                            lists[lists.index('interaction') +
                                                  2])
                                    else:
                                        results['lossnuclinteraction'] = float(
                                            lists[lists.index('interaction') +
                                                  2])
                                else:
                                    results[physiclquantity] = float(
                                        lists[lists.index(physiclquantity) +
                                              2])
                            else:
                                pass

            return results
        # cell is not None and nuclides is None:
        elif nuclides is None:
            start = 0
            content = []
            capturelists = []
            with open(outfile, 'r') as fid:
                for eachline in fid:
                    lists = eachline.strip().split()
                    if "neutron activity of each nuclide in each cell, per source particle" in eachline:
                        tag = True
                    if "total" in eachline and lists[0] == 'total':
                        tag = False
                    if tag:
                        content.append(lists)

            for ind, ll in enumerate(content):
                if ll and ll[1] == str(cell):
                    start = ind
            try:
                if start == 0:
                    raise CustomError('Cell {:} not found!'.format(cell))
            except TypeError as e:
                print(e)
                return -1

            for ind, ll in enumerate(content[start:]):
                if ll:
                    if ind == 0:
                        capturelists.append(float(ll[6]))
                    else:
                        capturelists.append(float(ll[4]))
                else:
                    break

            results['capture'] = np.array(capturelists).sum()
            return results

        # cell is None and nuclides is not None:
        elif cell is None:
            results = {}
            content = []
            for nuclide in nuclides:
                results[str(nuclide)] = defaultdict(lambda: 0)

            with open(outfile, 'r') as fid:
                for eachline in fid:
                    lists = eachline.strip().split()
                    if "total over all cells by nuclide" in eachline:
                        tag = True
                    if tag:
                        if len(lists) == 9 and lists[1].isnumeric():
                            # print(lists)
                            content.append(lists)
                        if content and len(lists) != 9:
                            tag = False

            for ll in content:
                for nuclide in nuclides:
                    if str(nuclide) in ll[0]:
                        results[str(nuclide)]['capture'] = float(ll[3])
                        results[str(nuclide)]['fission'] = float(ll[4])
                        results[str(nuclide)]['n,xn'] = float(ll[5])
                    # else:
                    #     results[str(nuclide)]['capture'] = 0

            return results

        # cell is not None and nuclides is not None:
        else:
            start = 0
            content = []
            capturelists = []
            results = {}
            for nuclide in nuclides:
                results[str(nuclide)] = defaultdict(lambda: 0)
            with open(outfile, 'r') as fid:
                for eachline in fid:
                    lists = eachline.strip().split()
                    if "neutron activity of each nuclide in each cell, per source particle" in eachline:
                        tag = True
                    if "total" in eachline and lists[0] == 'total':
                        tag = False
                    if tag:
                        content.append(lists)

            for ind, ll in enumerate(content):
                if ll and ll[1] == str(cell):
                    start = ind

            try:
                if start == 0:
                    raise CustomError('Cell {:} not found!'.format(cell))
            except TypeError as e:
                print(e)
                return -1

            content = content[start:]
            filtercontent = []
            for ind, ll in enumerate(content):
                if ll:
                    if ind == 0:
                        filtercontent.append(ll[2:])
                    else:
                        filtercontent.append(ll)
                else:
                    break

            for line in filtercontent:
                for nuclide in nuclides:
                    if str(nuclide) in line[0]:
                        results[str(nuclide)]['capture'] = float(line[4])
                        results[str(nuclide)]['fission'] = float(line[5])
                        results[str(nuclide)]['n,xn'] = float(line[6])
            return results
Exemple #7
0
    def readNuclideFraction(self, filename, mode):
        '''
        Fuction:
            读取 table 40 中的核素份额
            
        Input parameter:
            需要读取的 mcnp输出文件名:filename
            模式:mode 两种模式质量密度(mass) 和 原子数密度(atom)
        Return:
            返回类型dict, 核素份额 {m: {nuclide: fraction}}
            
        '''

        try:
            if mode != 'atom' and mode != 'mass':
                raise CustomError('Mode should be mass or atom!')
        except TypeError as e:
            print(e)
            return -1

        if mode == 'atom':
            keywords = 'component nuclide, atom fraction'
        else:
            keywords = 'component nuclide, mass fraction'

        tag = False
        emptyline = 0
        content = ''
        with open(filename, 'r') as fid:
            for line in fid:
                if keywords in line:
                    tag = True
                if emptyline == 2:
                    tag = False
                if tag:
                    linelist = line.strip().split()
                    if linelist:
                        if emptyline == 1:
                            content = ''.join([content, line])
                    else:
                        emptyline += 1
        content_list = content.split('\n')
        filterd_content_list = []
        for content in content_list:
            test_list = content.strip().split()
            if test_list:
                if re.fullmatch('\d+', test_list[0]) or re.fullmatch(
                        '\d+,', test_list[0]):
                    filterd_content_list.append(content.strip())

        result = defaultdict(lambda: 0)
        fraction_dict = defaultdict(lambda: 0)
        m_num = 0
        for string in filterd_content_list:
            test_list = string.split()
            for index, substring in enumerate(test_list):
                if re.fullmatch('\d+', substring):
                    result[m_num] = fraction_dict
                    m_num = substring
                    fraction_dict = defaultdict(lambda: 0)
                if re.fullmatch('\d+,', substring):
                    fraction_dict[substring[:-1]] = test_list[index + 1]

    # print(string_list)
    # with open('tt.txt', 'w') as fid:
    #     fid.write(content)
    # contentlist = content.strip().split()
    # splitpos = []
    # for ii, data in enumerate(contentlist):
    #     if data.isdecimal():
    #         splitpos.append(ii)
    # splitpos.append(len(contentlist))
    # for ii in range(len(splitpos)-1):
    #     content_list_with_no_comma = self.deleteComma(contentlist[(splitpos[ii]+1):splitpos[ii+1]])
    #     content_dict = self.list2dict(content_list_with_no_comma)
    #     result[contentlist[splitpos[ii]]] = content_dict

        return result