Beispiel #1
0
def changeMcnpLine(inp, step, designator, section='cell'):
    mh = McnpinpHandler()
    line = mh.readContent(inp, designator, section)
    data = line.strip().split()[2]
    if float(data) > 0:
        replacedata = str(float(data) + step)
    else:
        replacedata = str(float(data) - step)
    newline = line.replace(data, replacedata)
    mh.modifyinp(inp, designator, newline, section)
Beispiel #2
0
    def findTMP(self, inp, designator):
        mh = McnpinpHandler()
        mcnpcontent = mh.readContent(inp, designator)

        if '$' in mcnpcontent:
            mcnpcontent = mcnpcontent[:mcnpcontent.find('$')]
        if mcnpcontent.find('tmp') > 0 or mcnpcontent.find('TMP') > 0:
            return True
        else:
            return False
Beispiel #3
0
def inital(inp, diff, surflist=None):
    mh = McnpinpHandler()

    for surf in surflist:
        line1 = mh.readContent(inp, surf, section='surface')
        oldsurf = float(line1.strip().split()[2])
        if oldsurf > 0:
            newsurf = oldsurf - diff
        else:
            newsurf = oldsurf + diff

        newline = line1.replace(line1.strip().split()[2], "{:.1f}".format(newsurf))
        mh.modifyinp(inp, surf, newline, section='surface')
Beispiel #4
0
    def readTMP(self, inp, designator):
        mh = McnpinpHandler()
        mcnpcontent = mh.readContent(inp, designator)
        if '$' in mcnpcontent:
            mcnpcontent = mcnpcontent[:mcnpcontent.find('$')]

        inplist = mcnpcontent.strip().split()
        tmp = None
        for ii, eachstr in enumerate(inplist):
            if 'tmp' in eachstr or 'TMP' in eachstr:
                tmp = float(inplist[ii][4:])

        return tmp
Beispiel #5
0
    def hasMtnumIninp(self, inpfile, matnum):
        mh = McnpinpHandler()
        cellcards = mh.readCellCards(inpfile)

        matincellcard = []
        for line in cellcards:
            lists = line.strip().split()
            matincellcard.append(lists[1])
        for mat in matnum:
            if mat not in matincellcard:
                mh.errorMessage(' material number {:} do not exists!\n'.format(mat))
                return False

        return True
Beispiel #6
0
    def isTMPIdentical(self, filename, workpath=None):
        inpfile = filename
        tmpdic = {}
        if workpath:
            inpfile = os.path.join(workpath, filename)
        mh = McnpinpHandler()
        cellcards = mh.readCellCards(inpfile)
        for line in cellcards:
            lists = line.strip().split()
            mat = lists[1]
            if mat not in tmpdic.keys():
                tmpdic[mat] = []
            for ii, eachstr in enumerate(lists):
                if 'tmp' in eachstr or 'TMP' in eachstr:
                    tmp = lists[ii][4:]
                    tmpdic[mat].append(tmp)

        for key, tmps in tmpdic.items():
            if len(set(tmps)) > 1:
                mh.errorMessage('The TMP card of material {:} is inconsistent!\n'.format(key))
                return False

        return True
Beispiel #7
0
    def isTemEqMtnum(self, filename, workpath=None):

        inpfile = filename
        if workpath:
            inpfile = os.path.join(workpath, filename)
        mh = McnpinpHandler()
        cellcards = mh.readCellCards(inpfile)
        tmpnum = 0
        matnum = 0

        for cellcard in cellcards:
            if '$' in cellcard:
                cellcard = cellcard[:cellcard.find('$')]
            if cellcard.find('tmp')>0 or cellcard.find('TMP')>0:
                tmpnum += 1
            if cellcard.strip().split()[1] != '0':
                matnum += 1
        if tmpnum == matnum:
            print ('matnum is ', matnum, ' tmpnum is ', tmpnum)
            return True
        else:
            print ('matnum is ', matnum, ' tmpnum is ', tmpnum)
            print ('The number of tmp and the number of  material are not  identical !')
            return False
class SearchRodCriticalPos(object):
    def __init__(self):
        self.mh = McnpinpHandler()
        self.mtr = McnpTallyReader()

    def preProcessing(self, mcnpfile, rod_postion, rods):
        self.mh.cleanup(mcnpfile)
        for key, rod in rods.items():
            print(key)
            print(type(rod))
            rod.setInsertPosition(rod_postion)
            self.mh.modifyinp(mcnpfile,
                              rod.getTrCardNo(),
                              rod.ouputforMcnpinp(),
                              section='data')

    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

    def startSearch(self,
                    mcnpfile,
                    num_node=1,
                    num_processor=16,
                    reference_keff=1.0,
                    eps=1e-4,
                    **rods):
        inputfile = mcnpfile
        for key, rod in rods.items():
            if type(rod) != ControlRod:
                raise TypeError(
                    'The function parameter requires an instance of class ControlRod!'
                )
            else:
                rod_range = rod.getRodRange()

        low = 0
        high = rod_range
        with open('results.out', 'w') as fid:
            fid.write('{:^12} {:^10}\n'.format('Rod position', 'keff'))

        while high - low > 0.1:
            mid = (low + high) / 2.0
            self.preProcessing(inputfile, mid, rods)

            os.system('  mpirun -r ssh -np ' +
                      str(int(num_node * num_processor)) +
                      ' /home/daiye/bin/mcnp5.mpi n=' + inputfile)
            # os.system('  mcnp5 '+' n='+inputfile)
            keff = self.postProcessing(inputfile,
                                       ''.join([inputfile, 'o',
                                                str(mid)]))
            with open('results.out', 'a') as fid:
                fid.write('{:^12.6f} {:^10.5f}\n'.format(mid, keff))
            if abs(keff - reference_keff) < eps:
                return mid
            if keff > reference_keff:
                high = mid
            else:
                low = mid

        return -1
Beispiel #9
0
# inp = 'co25'
cardlist = ['naclsets', 'uclsets', 'coresizesets', 'reflectorsets']

volume = 2.12058E+07
tallydic = {
    '1004': '94240',
    '1003': '94239',
    '1005': '94241',
    '1007': '90232',
    '1016': '91233',
    '1018': '92233',
    '1020': '92235',
    '1019': '92234',
    '1023': '92238'
}
mh = McnpinpHandler()
paralists = []
newcardlist = []
for card in cardlist:
    line = mh.readContent(inp, card, section='data')
    if line:
        lists = line.strip().split()
        newcardlist.append(card)
        paralists.append(
            [int(x) if type(eval(x)) == int else float(x) for x in lists[1:]])

para = {card: para for card, para in zip(newcardlist, paralists)}

deleteNonMcnpCard(inp, cardlist)
print(para)
initalornot = True
Beispiel #10
0
class Preprocesser(object):
    def __init__(self):
        self._cardlist = [
            'Naclsets', 'Pucl3sets', 'coresizesets', 'reflectorsets',
            'Thcl4sets', 'Ucl3sets', 'Ucl4sets', 'Na', 'Cl', 'U', 'Th'
        ]
        self.mcnpinphandler = McnpinpHandler()

    def getParameter(self, mcnpinp, materialcard):

        paralists = []
        newcardlist = []
        for card in self._cardlist:
            line = self.mcnpinphandler.readContent(mcnpinp,
                                                   card,
                                                   section='data')
            if line:
                lists = line.strip().split()
                newcardlist.append(card)
                paralists.append([
                    int(x) if type(eval(x)) == int else float(x)
                    for x in lists[1:]
                ])

        parameter = {card: para for card, para in zip(newcardlist, paralists)}
        line = self.mcnpinphandler.readContent(mcnpinp,
                                               materialcard,
                                               section='data')
        linelist = line.strip().split()
        parameter['mcardcontent'] = linelist
        return parameter

    def copyInitalMcnpinp(self, initalinp, mcnpinp):
        with open(initalinp, 'r') as fid1, open(mcnpinp, 'w') as fid2:
            for line in fid1:
                fid2.write(line)

    def deleteNonMcnpCard(self, mcnpinp):
        shadow = False
        with open(mcnpinp, 'r') as fid, open(mcnpinp + 'bp', 'w') as fid2:
            for line in fid:
                shadow = False
                lists = line.strip().split()
                if bool(lists):
                    for card in self._cardlist:
                        if re.fullmatch(card, lists[0], re.I) is not None:
                            shadow = True
                            break
                if not shadow:
                    fid2.write(line)
        os.remove(mcnpinp)
        os.rename(mcnpinp + 'bp', mcnpinp)

    def cleanupFolder(self, mcnpinp):
        self.mcnpinphandler.cleanup(mcnpinp)

    def modfiyMaterial(self, mcnpinp, cellnum, newdensity, mcard,
                       newmcardcontent):
        line = self.mcnpinphandler.readContent(mcnpinp, cellnum)
        newline = line.replace(line.strip().split()[2],
                               '-{:.5f}'.format(newdensity))
        self.mcnpinphandler.modifyinp(mcnpinp, cellnum, newline)
        self.mcnpinphandler.modifyinp(mcnpinp, mcard, newmcardcontent, 'data')

    def changeMode(self, mcnpinp, mode, test=False):
        with open(mcnpinp, 'r', encoding="utf-8") as fid:
            content = fid.readlines()
        if test:
            fixedSource = 'sdef  axs=0 0 1 pos=0 0 0 ext=d1 rad=d2  erg=d3 par=1\
                \nsi1    -10 10\nsp1   0   1\nsi2    0  10\nsp2    -21 1\nSI3   L  \
                0.151 0.248 0.410 0.675 1.11 1.84 3.03 4.99 19.64\nSP3      \
            0.0 5.45e-2 5.0e-2 8.0e-2 0.122 0.165 0.178 0.157 0.1985\nnps 50\n'

            kcodeSource = 'kcode    200 1.0 5 50\nksrc   50. 0. 0. -50 0 0  -0 \
                    0 0  0 0 20\n'

        else:
            fixedSource = 'sdef  axs=0 0 1 pos=0 0 0 ext=d1 rad=d2  erg=d3 par=1\
                    \nsi1    -10 10\nsp1   0   1\nsi2    0  10\nsp2    -21 1\nSI3   L  \
                    0.151 0.248 0.410 0.675 1.11 1.84 3.03 4.99 19.64\nSP3      \
                0.0 5.45e-2 5.0e-2 8.0e-2 0.122 0.165 0.178 0.157 0.1985\nnps 50000\n'

            kcodeSource = 'kcode    20000 1.0 30 250\nksrc   50. 0. 0. -50 0 0  -0 \
                    0 0  0 0 20\n'

        if re.fullmatch('fixed', mode, re.I):

            with open(mcnpinp, 'w', encoding="utf-8") as f:
                for line in content:
                    lists = line.strip().split()
                    if lists and re.fullmatch('kcode', lists[0],
                                              re.I) is not None:
                        f.write(fixedSource)
                    elif lists and re.fullmatch('ksrc', lists[0],
                                                re.I) is not None:
                        pass
                    else:
                        f.write(line)
        elif re.fullmatch('kcode', mode, re.I):
            with open(mcnpinp, 'w', encoding="utf-8") as f:
                for line in content:
                    lists = line.strip().split()
                    if lists and re.fullmatch('sdef', lists[0],
                                              re.I) is not None:
                        f.write(kcodeSource)
                    elif lists and re.fullmatch('si|sp|sc|ds[0-9]{1,3}', lists[0], \
                                            re.I) is not None:
                        pass
                    elif lists and re.fullmatch('nps', lists[0],
                                                re.I) is not None:
                        pass
                    else:
                        f.write(line)
        else:
            raise NameError('No such mode!')

    def changeMcnpLine(self, inp, increment, designator, section='cell'):
        line = self.mcnpinphandler.readContent(inp, designator, section)
        data = line.strip().split()[2]
        if float(data) > 0:
            replacedata = str(float(data) + increment)
        else:
            replacedata = str(float(data) - increment)
        newline = line.replace(data, replacedata)
        self.mcnpinphandler.modifyinp(inp, designator, newline, section)
Beispiel #11
0
def maxPowerPeakFactorSearch(mcnpinp, node, ppn, trforrod, mode, rodstep=10):
    """
        Function: under different rod position, compute the power distribution, power peak factor and find the 
        maximum power peak factor, finally write all results to a filename of inp+'results.out'.
        Parameters: 
            inp: the name of mcnp output file.
            node: the node for parallel computing.
            ppn: the core for parallel computing.
            trforrod: dict for rod, key is 'tr' card, value is rod num.
            mode: mode for rod withdrawal accident or rod drop accident, 'w' stands for withdrawal and
            'd' stands for drop.
            rodstep: rod move step everytime.
        Return: none
    
    """
    cr = {}
    rodlists = {}
    powerfactorresults = {}
    mh = McnpinpHandler()
    # read initial rod position of burnup mcnp input
    for key, value in trforrod.items():
        rodmessage = mh.readContent(mcnpinp, key, 'data')
        lists = rodmessage.strip().split()
        rodxcoordinate = float(lists[1])
        rodycoordinate = float(lists[2])
        rodinsertpostion = float(lists[3])
        cr[value] = ControlRod(rod=value,
                               trCard=key,
                               rodRange=180.0,
                               rodXCoordinate=rodxcoordinate,
                               rodYCoordinate=rodycoordinate)
        cr[value].setInsertPosition(rodinsertpostion)
        rodlists[value] = key
        powerfactorresults[value] = []
    print(rodlists)
    print(powerfactorresults)
    mh.cleanup(mcnpinp)
    if re.match('w', mode, re.I) is not None:
        limit = 180.
        factor = 1
    elif re.match('d', mode, re.I) is not None:
        limit = 0
        factor = -1
    else:
        print("Mode set error! Should be w or d!")
        exit(0)

    for rod in rodlists:
        ii = 0
        initinsertposition = cr[rod].getInsertPosition()
        while (cr[rod].getInsertPosition() * factor < limit):
            instertposition = initinsertposition + rodstep * ii * factor
            if instertposition * factor > limit:
                instertposition = limit
            cr[rod].setInsertPosition(instertposition)
            ### modify mcnp inp
            mh.modifyinp(mcnpinp, cr[rod].getTrCardNo(),
                         cr[rod].ouputforMcnpinp(), 'data')
            ii = ii + 1
            ### run mcnp
            print('  mpirun -r ssh -np ' + str(int(node * ppn)) +
                  ' /home/daiye/bin/mcnp5.mpi n=' + mcnpinp)
            os.system('  mpirun -r ssh -np ' + str(int(node * ppn)) +
                      ' /home/daiye/bin/mcnp5.mpi n=' + mcnpinp)

            if os.path.isfile(mcnpinp + 'o'):
                print('MCNP5 run finished!')
            else:
                print('error!!!,MCNP5 run failed!')
                exit(0)
            ### read results and write to results file

            keff = readKeff(mcnpinp + 'o')
            meshfilename = mcnpinp + '_mesh_' + rod + '_' + str(
                instertposition)
            original_meshfilename = getMeshFilename(mcnpinp + 'o')
            if os.path.isfile(original_meshfilename):
                mh.deleteFiles(meshfilename)
                os.rename(original_meshfilename, meshfilename)
                print("Rename meshtal to {:}\n".format(meshfilename))

            resultsfilename = mcnpinp + rod + '_' + str(
                instertposition) + '.csv'
            uncertainty = 1.1 * 1.1
            radialPowerPeakFactor, axialPowerPeakFactor, totPowerPeakFactor = computePowerDesityDistribution(
                meshfilename, resultsfilename, uncertainty)
            powerfactorresults[rod].append(
                (instertposition, keff[0], radialPowerPeakFactor,
                 axialPowerPeakFactor, totPowerPeakFactor))
            mh.cleanup(mcnpinp)
        ## set rod insertposition to inital
        cr[rod].setInsertPosition(initinsertposition)
        mh.modifyinp(mcnpinp, cr[rod].getTrCardNo(), cr[rod].ouputforMcnpinp(),
                     'data')

    maxradialPowerPeakFactor = 0
    maxaxialPowerPeakFactor = 0
    maxtotPowerPeakFactor = 0
    maxrod1 = ''
    maxrod2 = ''
    maxrod3 = ''
    #print(powerfactorresults)
    with open(mcnpinp + 'results.out', 'w') as fid:
        fid.write('{:^5}{:^20}{:^8}{:^20}{:^20}{:^20}\n'.format\
                ('Rod', 'Insert position', 'Keff', 'Radial peak factor', 'Axial peak factor', 'Tot peak factor'))
        for rod in powerfactorresults:
            for ii in range(len(powerfactorresults[rod])):
                radialpowerfactor = powerfactorresults[rod][ii][2]
                axialpowerfactor = powerfactorresults[rod][ii][3]
                totpowerfactor = powerfactorresults[rod][ii][4]
                instertposition = powerfactorresults[rod][ii][0]
                keff = powerfactorresults[rod][ii][1]
                if maxradialPowerPeakFactor < radialpowerfactor:
                    maxrod1 = rod
                    maxradialPowerPeakFactor = radialpowerfactor
                if maxaxialPowerPeakFactor < axialpowerfactor:
                    maxrod2 = rod
                    maxaxialPowerPeakFactor = axialpowerfactor
                if maxtotPowerPeakFactor < totpowerfactor:
                    maxrod3 = rod
                    maxtotPowerPeakFactor = totpowerfactor
                fid.write('{:^5}{:^20.3f}{:^8.5f}{:^20.4f}{:^20.4f}{:^20.4f}\n'.format\
                (rod, instertposition, keff, radialpowerfactor, axialpowerfactor, totpowerfactor))

        fid.write('{:}:  {:}\n'.format('Rod', maxrod1))
        fid.write('{:}:  {:.4}\n'.format('Max radial power peak factor',
                                         maxradialPowerPeakFactor))
        fid.write('{:}:  {:}\n'.format('Rod', maxrod2))
        fid.write('{:}:  {:.4}\n'.format('Max axial power peak factor',
                                         maxaxialPowerPeakFactor))
        fid.write('{:}:  {:}\n'.format('Rod', maxrod3))
        fid.write('{:}:  {:.4}\n'.format('Max total power peak factor',
                                         maxtotPowerPeakFactor))
Beispiel #12
0
 def __init__(self):
     self.mcnptallyreader = McnpTallyReader()
     self.mcnpinphandler = McnpinpHandler()
Beispiel #13
0
class Postprocesser(object):
    def __init__(self):
        self.mcnptallyreader = McnpTallyReader()
        self.mcnpinphandler = McnpinpHandler()

    def outputResults(self, filename, content, writeingmode='a'):
        with open(filename, writeingmode) as fid:
            fid.write(content)

    def renameFile(self, oldfilename, newfilename):
        self.mcnpinphandler.deleteFiles(newfilename)
        os.rename(oldfilename, newfilename)

    def readVolume(self, filename):
        volume = None
        with open(filename, 'r') as fid:
            context = fid.readlines()
        context = [line for line in context if len(line.strip().split()) == 1]
        line = re.findall("                         \d\.\d{5}E[+-]\d{2}",
                          ''.join(context))[0]
        volume = float(line)
        return volume

    def getKeff(self, mcnpout):
        if os.path.isfile(mcnpout):
            print('MCNP5 run finished!')
            return self.mcnptallyreader.readKeff(mcnpout)['keff']
        else:
            raise FileNotFoundError('No such file: {:}!'.format(mcnpout))

    def getEscape(self, mcnpout, mode='fixed'):
        if os.path.isfile(mcnpout):
            print('MCNP5 run finished!')
            if re.fullmatch('kcode', mode, re.I):
                k_totrate = self.mcnptallyreader.readNeutronActivity(mcnpout)
                escaperate = k_totrate['escape']/(k_totrate['escape']\
                        +k_totrate['lossfission']+k_totrate['capture'])
            elif re.fullmatch('fixed', mode, re.I):
                f_totrate = self.mcnptallyreader.readNeutronActivity(mcnpout)
                escaperate = f_totrate['escape'] / (f_totrate['escape'] +
                                                    f_totrate['lossfission'] +
                                                    f_totrate['capture'])
            else:
                raise NameError('No such mode: {:}'.format(mode))
            return escaperate  # escape of kcode mode

        else:
            raise FileNotFoundError('No such file: {:}'.format(mcnpout))

    def getCR(self,
              mcnpout,
              mode='kcode',
              tallydic=None,
              cell=None,
              matnum=None):
        if os.path.isfile(mcnpout):
            print('MCNP5 run finished!')
            if re.fullmatch('kcode', mode, re.I):
                cr = self.mcnptallyreader.getCR(mcnpout)
            elif re.fullmatch('fixed', mode, re.I):
                cr = self.mcnptallyreader.getCR(
                    PurePath.joinpath(Path(os.getcwd()), mcnpout),
                    mode='fixed',
                    tallydic=tallydic,
                    cell=cell,
                    matnum=matnum,
                    volume=self.readVolume(mcnpout))
            else:
                raise NameError('No such mode: {:}'.format(mode))
            return cr  # escape of kcode mode

        else:
            raise FileNotFoundError('No such file: {:}'.format(mcnpout))
Beispiel #14
0
 def __init__(self):
     self._cardlist = [
         'Naclsets', 'Pucl3sets', 'coresizesets', 'reflectorsets',
         'Thcl4sets', 'Ucl3sets', 'Ucl4sets', 'Na', 'Cl', 'U', 'Th'
     ]
     self.mcnpinphandler = McnpinpHandler()
 def __init__(self):
     self.mh = McnpinpHandler()
     self.mtr = McnpTallyReader()
Beispiel #16
0
                    required=True,
                    type=str)
parser.add_argument('--step',
                    '-s',
                    help='step lenth for calculation',
                    metavar="",
                    default=1e-5,
                    type=float)
args = parser.parse_args()
print("input file is {:}, step lenth is {:}".format(args.input, args.step))
mcnpinp = args.input
node = args.node
ppn = args.ppn
step = args.step

mh = McnpinpHandler()
mtr = McnpTallyReader()
end = 5.0000e-04
resultfile = mcnpinp + 'results.out'

with open(resultfile, 'w') as fid:
    fid.write("{:^10} {:^10}\n".format('Added Th', 'keff'))
mh.cleanup(mcnpinp)
resultfile = mcnpinp + 'results.out'

for ii in np.arange(0, end, step):
    #modify density
    mcnpcontent = mh.readContent(mcnpinp, '4')
    density = mcnpcontent.strip().split()[2]
    mh.modifyinp(
        mcnpinp, '4',
Beispiel #17
0
stepmolpucl = args.stepmolpucl

if stepmolnacl > 0:
    stepmolnacl = -1 * stepmolnacl
if stepmolpucl > 0:
    stepmolpucl = -1 * stepmolpucl
endreflectorThickness = args.thicknessStep
print('startmolnacl:', startmolnacl)
print('stepmolnacl:', stepmolnacl)
print('startmolpucl:', startmolpucl)
print('stepmolpucl:', stepmolpucl)
print('endreflectorThickness:', endreflectorThickness)

results = {}
thicknessStep = 10
mh = McnpinpHandler()
mh.cleanup(inp)
# loop for reflector
resultfile = inp + 'results.out'
seachoutfile = inp + 'search.out'
with open(resultfile, 'w') as fid, open(seachoutfile, 'w') as fid2:
    fid.write(
        "{:^10} {:^10} {:^10} {:^10} {:^10} {:^20} {:^20} {:^20} {:^20}\n".
        format('Thickness', 'Nacl', 'PuCl3', 'ThCl4', 'Keff', 'CR of kcode',
               'Escape of kcode', 'CR of fixed', 'Escape of fixed'))
    fid2.write(
        "{:^10} {:^10} {:^10} {:^10} {:^10} {:^20} {:^20} {:^20} {:^20}\n".
        format('Thickness', 'Nacl', 'PuCl3', 'ThCl4', 'Keff', 'CR of kcode',
               'Escape of kcode', 'CR of fixed', 'Escape of fixed'))

for kk in range(0, endreflectorThickness, thicknessStep):