Esempio n. 1
0
def toENDF6(self, flags, targetInfo, verbosityIndent=''):

    gridded = self.forms[0]
    data = gridded.array.constructArray()
    Tlist = list(gridded.axes[-1].grid)  #FIXME what if grid units aren't 'K'?
    Elist = list(gridded.axes[-2].grid)  #FIXME      ""                  'eV'?

    LT = len(Tlist) - 1
    # first temperature includes the energy list:
    endf = [
        endfFormatsModule.endfHeadLine(Tlist[0], 0, LT, 0, 1, len(data[0]))
    ]
    independentInterp = gndToENDF6.gndToENDFInterpolationFlag(
        gridded.axes[1].interpolation)
    dependentInterp = gndToENDF6.gndToENDFInterpolationFlag(
        gridded.axes[2].interpolation)
    endf += ['%11i%11i%44s' % (len(data[0]), independentInterp, '')
             ]  # no trailing zeros
    endf += endfFormatsModule.endfDataList(
        list(itertools.chain(*zip(Elist, data[0]))))

    # remaining temperatures:
    for T, datList in zip(Tlist[1:], data[1:]):
        endf += [
            endfFormatsModule.endfHeadLine(T, 0, dependentInterp, 0,
                                           len(datList), 0)
        ]
        endf += endfFormatsModule.endfDataList(datList)
    return endf
Esempio n. 2
0
def toENDF6(self, flags, targetInfo, verbosityIndent=''):
    NR = 1
    NP = len(self)
    endf = [endfFormatsModule.endfHeadLine(0, 0, 0, 0, NR, NP)]
    interp = gndToENDF6.gndToENDFInterpolationFlag(self.interpolation)
    endf += ['%11i%11i%44s' % (len(self), interp, '')]
    endf += endfFormatsModule.endfDataList(
        list(itertools.chain(*self.copyDataToXYs())))
    return endf
Esempio n. 3
0
def gammasToENDF6_MF6_oneGamma(MT, endfMFList, flags, targetInfo, gamma, LANG,
                               LEP, frame):

    component = gamma.distribution[targetInfo['style']]
    isPrimary, isDiscrete, energySubform, angularSubform = gammaType(component)
    if (isPrimary or isDiscrete): return (False)

    targetInfo['multiplicity'] = gamma.multiplicity[targetInfo['style']]

    if (isinstance(component, uncorrelatedModule.form)):
        angularSubform = component.angularSubform.data
        energySubform = component.energySubform.data
        if (not (isinstance(angularSubform, angularModule.isotropic))):
            raise Exception('Unsupport angular form = "%s"' %
                            angularSubform.moniker)
        if (not (isinstance(energySubform, energyModule.regions2d))):
            energySubform = [energySubform]
        interpolationEIn = gndToENDF2PlusDInterpolationFlag(
            energySubform[0].interpolation,
            energySubform[0].interpolationQualifier)
        EInFactor = PQUModule.PQU(
            1, energySubform[0].axes[2].unit).getValueAs('eV')
        EOutFactor = PQUModule.PQU(
            1, energySubform[0].axes[1].unit).getValueAs('eV')

        NE, NR = 0, 1
        ENDFDataList = []
        for i1, region in enumerate(energySubform):
            interpolationEIn = gndToENDF2PlusDInterpolationFlag(
                region.interpolation, region.interpolationQualifier)
            for energyInData in region:
                NE += 1
                EIn = energyInData.value
                data = []
                if (not (isinstance(energyInData, energyModule.regions1d))):
                    energyInData = [energyInData]
                for region2 in energyInData:
                    for Ep, probability in region2:
                        data.append(Ep * EOutFactor)
                        data.append(probability / EOutFactor)
                ENDFDataList += [
                    endfFormatsModule.endfContLine(0, EIn, 0, 0, len(data),
                                                   len(data) / 2)
                ]
                ENDFDataList += endfFormatsModule.endfDataList(data)
    else:
        raise Exception('Unsupport continuum gamma distribution = "%s"' %
                        component.moniker)

    interpolations = [NE, interpolationEIn]
    ENDFDataList.insert(
        0, endfFormatsModule.endfContLine(0, 0, LANG, LEP, NR, NE))
    ENDFDataList.insert(
        1, endfFormatsModule.endfInterpolationLine(interpolations))

    toENDF6_MF6(MT, endfMFList, flags, targetInfo, 1, frame, ENDFDataList)
    return (True)
Esempio n. 4
0
def toENDF6_MF6(MT, endfMFList, flags, targetInfo, LAW, frame, MF6):

    reactionSuite = targetInfo['reactionSuite']
    MF6or26 = {3: 6, 23: 26}[targetInfo['crossSectionMF']]
    targetInfo['MF6LCTs'].append({
        standardsModule.frames.labToken: 1,
        standardsModule.frames.centerOfMassToken: 2
    }[frame])
    LIP = 0
    if ((targetInfo['product'].id in targetInfo['metastables'])
            and not ((50 <= MT <= 91) or (600 <= MT <= 850))):
        # set LIP to metastable index of product UNLESS excited state of product is encoded in MT number:
        alias = targetInfo['metastables'][targetInfo['product'].id]
        LIP = int(alias.metaStableIndex)
    if (MT not in endfMFList[MF6or26]): endfMFList[MF6or26][MT] = []
    particleID = targetInfo['zapID']  # get ZAP for the outgoing particle
    if (particleID == IDsPoPsModule.electron):
        ZAP = 11
    else:
        ZAP = miscPoPsModule.ZA(reactionSuite.PoPs[particleID])
    productMass = targetInfo['particleMass']
    if ((particleID == IDsPoPsModule.neutron)
            and (MT in [18])):  # Special case when fission has MF = 6 data.
        nPoints = 2
        interpolationFlatData = [nPoints, 2]
        multiplicityList = endfFormatsModule.endfDataList(
            [[targetInfo['EMin'], 1.], [targetInfo['EMax'], 1.]])
    else:
        multiplicity = targetInfo['multiplicity']
        if (isinstance(multiplicity, multiplicityModule.component)):
            multiplicity = multiplicity[targetInfo['style']]
        interpolationFlatData, nPoints, multiplicityList = multiplicity.toENDF6List(
            targetInfo)
    if ((particleID == IDsPoPsModule.photon) and (LAW == 2)):
        projectileMass = reactionSuite.PoPs[reactionSuite.projectile].getMass(
            'eV/c**2')
        targetMass = reactionSuite.PoPs[reactionSuite.projectile].getMass(
            'eV/c**2')
        AWP = targetInfo['Q']
        AWP /= 1. + 0.5 * AWP / (
            projectileMass + targetMass
        )  # Should be divided by residual mass, but this is close.
    else:
        AWP = productMass
    ENDFHeaderList = [
        endfFormatsModule.endfContLine(ZAP, AWP, LIP, LAW,
                                       len(interpolationFlatData) / 2, nPoints)
    ]
    ENDFHeaderList += endfFormatsModule.endfInterpolationList(
        interpolationFlatData)
    ENDFHeaderList += multiplicityList
    endfMFList[MF6or26][MT] += ENDFHeaderList + MF6
Esempio n. 5
0
def toENDF6_MF6(MT, endfMFList, flags, targetInfo, LAW, frame, MF6):

    MF6or26 = {3: 6, 23: 26}[targetInfo['crossSectionMF']]
    targetInfo['MF6LCTs'].append({
        standardsModule.frames.labToken: 1,
        standardsModule.frames.centerOfMassToken: 2
    }[frame])
    LIP = 0
    if ((targetInfo['product'].particle.name in targetInfo['metastables'])
            and not ((50 <= MT <= 91) or (600 <= MT <= 850))):
        # set LIP to metastable index of product UNLESS excited state of product is encoded in MT number:
        alias, = [
            alias for alias in targetInfo['reactionSuite'].aliases.values()
            if alias.getValue() == targetInfo['product'].particle.name
        ]
        LIP = int(alias.getAttribute('nuclearMetaStable'))
    if (MT not in endfMFList[MF6or26]): endfMFList[MF6or26][MT] = []
    particleID = targetInfo['zapID']  # get ZAP for the outgoing particle
    if (particleID == 'gamma'):
        ZAP = 0
    if (particleID == 'e-'):
        ZAP = 11
    else:
        Z, A, suffix, ZAP = nuclear.getZ_A_suffix_andZAFromName(particleID)
    productMass = targetInfo['particleMass']
    if ((particleID == 'n')
            and (MT in [18])):  # Special case when fission has MF = 6 data.
        nPoints = 2
        interpolationFlatData = [nPoints, 2]
        multiplicityList = endfFormatsModule.endfDataList(
            [[targetInfo['EMin'], 1.], [targetInfo['EMax'], 1.]])
    else:
        multiplicity = targetInfo['multiplicity']
        if (isinstance(multiplicity, multiplicityModule.component)):
            multiplicity = multiplicity[targetInfo['style']]
        interpolationFlatData, nPoints, multiplicityList = multiplicity.toENDF6List(
            targetInfo)
    if ((particleID == 'gamma')
            and ('primaryGammaEnergy' in targetInfo.keys())):
        AWP = targetInfo.dict.pop('primaryGammaEnergy')
    else:
        AWP = productMass / targetInfo['neutronMass']
    ENDFHeaderList = [
        endfFormatsModule.endfContLine(ZAP, AWP, LIP, LAW,
                                       len(interpolationFlatData) / 2, nPoints)
    ]
    ENDFHeaderList += endfFormatsModule.endfInterpolationList(
        interpolationFlatData)
    ENDFHeaderList += multiplicityList
    endfMFList[MF6or26][MT] += ENDFHeaderList + MF6
Esempio n. 6
0
def toENDF6(self, endfMFList, flags, targetInfo, verbosityIndent=''):
    ZAM, AWT = targetInfo['ZA'], targetInfo['mass']
    LTHR, LAT, LASYM = 0, self.calculatedAtThermal, self.asymmetric
    endf = [endfFormatsModule.endfHeadLine(ZAM, AWT, LTHR, LAT, LASYM, 0)]
    # describe scattering atoms:
    LLN, NS = 0, len(self.scatteringAtoms) - 1
    NI = 6 * (NS + 1)
    endf += [endfFormatsModule.endfHeadLine(0, 0, LLN, 0, NI, NS)]
    # principal scattering atom:
    atom = self.scatteringAtoms[0]
    endf += [
        endfFormatsModule.endfDataLine([
            atom.freeAtomCrossSection.getValueAs('b'), atom.e_critical,
            atom.mass,
            atom.e_max.getValueAs('eV'), 0, atom.numberPerMolecule
        ])
    ]
    for atom in self.scatteringAtoms[1:]:
        a1 = {
            'SCT': 0.0,
            'free_gas': 1.0,
            'diffusive_motion': 2.0
        }[atom.functionalForm]
        endf += [
            endfFormatsModule.endfDataLine([
                a1,
                atom.freeAtomCrossSection.getValueAs('b'), atom.mass, 0, 0,
                atom.numberPerMolecule
            ])
        ]

    # convert data form: sort first by beta, then E, then T
    gridded = self.S_alpha_beta.forms[0]
    array = gridded.array.constructArray()  # 3D numpy array

    Tlist = list(gridded.axes[3].grid)  # FIXME check grid units
    betas = list(gridded.axes[2].grid)
    alphas = list(gridded.axes[1].grid)

    # switch array back to ENDF ordering:  1st beta, then T, then alpha:
    array = array.transpose((1, 0, 2))

    NR = 1
    NB = len(betas)
    endf += [endfFormatsModule.endfHeadLine(0, 0, 0, 0, NR, NB)]
    #endf += endfFormatsModule.endfInterpolationList( (NB, 4) )
    endf += [
        '%11i%11i%44s' % (NB, 4, '')
    ]  # FIXME add 'suppressTrailingZeros' option to endfInterpolationList

    LT = len(Tlist) - 1
    if LT:
        T_interp = gndToENDF6.gndToENDFInterpolationFlag(
            gridded.axes[3].interpolation)
    else:
        T_interp = None
    beta_interp = gndToENDF6.gndToENDFInterpolationFlag(
        gridded.axes[2].interpolation)
    alpha_interp = gndToENDF6.gndToENDFInterpolationFlag(
        gridded.axes[1].interpolation)

    for index, beta in enumerate(betas):
        data = array[index, :, :]  # 2D sub-array for this beta

        endf += [
            endfFormatsModule.endfHeadLine(Tlist[0], beta, LT, 0, 1,
                                           len(data[0]))
        ]
        endf += ['%11i%11i%44s' % (len(alphas), alpha_interp, '')
                 ]  # no trailing zeros
        # For each beta, the first temperature needs to include the energy list:
        endf += endfFormatsModule.endfDataList(
            list(itertools.chain(*zip(alphas, data[0]))))

        # remaining temperatures:
        for T, datList in zip(Tlist[1:], data[1:]):
            endf += [
                endfFormatsModule.endfHeadLine(T, beta, T_interp, 0,
                                               len(datList), 0)
            ]
            endf += endfFormatsModule.endfDataList(datList)

    for atom in self.scatteringAtoms:
        if atom.effectiveTemperature is not None:
            endf += atom.effectiveTemperature.toENDF6(flags,
                                                      targetInfo,
                                                      verbosityIndent='')
    endfMFList[7][4] = endf + [99999]
Esempio n. 7
0
def toENDF6( self, style, flags, verbosityIndent = '', covarianceSuite = None ) :

    evaluatedStyle = self.styles.getEvaluatedStyle( )
    if( evaluatedStyle is None ) : raise ValueError( 'no evaluation style found' )

    if( flags['verbosity'] >= 10 ) : print '%s%s' % ( verbosityIndent, self.inputParticlesToReactionString( suffix = " -->" ) )
    verbosityIndent2 = verbosityIndent + ' ' * ( len( self.inputParticlesToReactionString( suffix = " -->" ) ) + 1 )
    projectile, target = self.projectile, self.target
    projectileZA = projectile.getZ_A_SuffixAndZA( )[-1]
    IPART = projectileZA
    if( projectile.name == 'e-' ) : IPART = 11
    targetZA, MAT = endf_endl.ZAAndMATFromParticleName( target.name )
    targetZ, targetA = divmod( targetZA, 1000 )
    targetInfo = processingInfoModule.tempInfo( )
    targetInfo['style'] = style
    targetInfo['reactionSuite'] = self
    targetInfo['ZA'] = targetZA
    if( self.particles.hasID( 'n' ) ) :       # Need neutron mass in eV/c**2, but it may not be in the particle list.
        targetInfo['neutronMass'] = self.getParticle( 'n' ).getMass( 'eV/c**2' )
    else :
        neutronAmu = masses.getMassFromZA( 1 )
        targetInfo['neutronMass'] = PQU.PQU( neutronAmu, 'amu' ).getValueAs('eV/c**2')
    if( isinstance( target, fudge.gnd.xParticle.element ) ) :
        targetInfo['mass'] = elementalMass[targetZA]
    else :
        targetInfo['mass'] = target.getMass( 'eV/c**2' ) / targetInfo['neutronMass']

    try :
        targetInfo['LIS'] = target['levelIndex']
    except :
        targetInfo['LIS'] = 0
    targetInfo['metastables'] = []
    targetInfo['LISO'] = 0
    for key, alias in self.aliases.items( ) :
        if( alias.hasAttribute( 'nuclearMetaStable' ) ) :
            targetInfo['metastables'].append( alias.getValue() )
            if( alias.getValue() == target.name ) :
                targetInfo['LISO'] = int( alias.getAttribute( 'nuclearMetaStable' ) )
    MAT += targetInfo['LISO']
    if( self.MAT is not None ) : MAT = self.MAT

    ITYPE = 0                   # Other ITYPE sublibraries not yet supported. BRB is this still true
    for reaction in self.reactions :
        if( 500 <= reaction.ENDF_MT < 573 ) : ITYPE = 3
    targetInfo['crossSectionMF'] = { 0 : 3, 3 : 23 }[ITYPE]

    targetInfo['delayedRates'] = []
    targetInfo['totalDelayedNubar'] = None
    targetInfo['MTs'], targetInfo['MF8'], targetInfo['LRs'] = {}, {}, {}
    endfMFList = { 1 : { 451 : [] }, 2 : {}, 3 : {}, 4 : {}, 5 : {}, 6 : {}, 8 : {}, 9 : {}, 10 : {}, 12 : {}, 13 : {},
            14 : {}, 15 : {}, 23 : {}, 26 : {}, 27 : {}, 31 : {}, 32 : {}, 33 : {}, 34 : {}, 35 : {}, 40 : {} }
    if( self.resonances is not None ) :      # Add resonances, independent of reaction channels
        self.resonances.toENDF6( endfMFList, flags, targetInfo, verbosityIndent=verbosityIndent2 )

    targetInfo['production_gammas'] = {}

    for reaction in self :
        reaction.toENDF6( endfMFList, flags, targetInfo, verbosityIndent = verbosityIndent2 )
    gndToENDF6Module.upDateENDFMF8Data( endfMFList, targetInfo )
    for MT, production_gammas in targetInfo['production_gammas'].items( ) :
        MF, production_gammas = production_gammas[0], production_gammas[1:]
        for productionReaction in production_gammas :
            gammas = [ gamma for gamma in productionReaction.outputChannel ]
            targetInfo['crossSection'] = productionReaction.crossSection[targetInfo['style']]
            gndToENDF6Module.gammasToENDF6_MF12_13( MT, MF, endfMFList, flags, targetInfo, gammas )

    for particle in self.particles :              # gamma decay data.
        if( isinstance( particle, fudge.gnd.xParticle.isotope ) ) :
            for level in particle :
                if( level.gammas ) :                        # non-empty gamma information
                    for baseMT in [ 50, 600, 650, 700, 750, 800 ] :
                        residualZA = endf_endl.ENDF_MTZAEquation( projectileZA, targetZA, baseMT )[0][-1]
                        if( nuclear.nucleusNameFromZA( residualZA ) == particle.name ) : break
                    level.toENDF6( baseMT, endfMFList, flags, targetInfo )

    MFs = sorted( endfMFList.keys( ) )
    endfList = []

    totalNubar = None
    totalDelayedNubar = targetInfo['totalDelayedNubar']
    if( 455 in endfMFList[5] ) :
        MF5MT455s = endfMFList[5][455]

        endfMFList[1][455]  = [ endfFormatsModule.endfHeadLine( targetZA, targetInfo['mass'], 0, 2, 0, 0 ) ] # Currently, only LDG = 0, LNU = 2 is supported.
        endfMFList[1][455] += [ endfFormatsModule.endfHeadLine( 0, 0, 0, 0, len( targetInfo['delayedRates'] ), 0 ) ]
        endfMFList[1][455] += endfFormatsModule.endfDataList( targetInfo['delayedRates'] )

        multiplicityModule.fissionNeutronsToENDF6( 455, totalDelayedNubar, endfMFList, flags, targetInfo )

        MF5MT455List = [ endfFormatsModule.endfHeadLine( targetZA, targetInfo['mass'], 0, 0, len( MF5MT455s ), 0 ) ]
        for MF5MT455 in MF5MT455s : MF5MT455List += MF5MT455
        if( len( MF5MT455s ) == 0 ) :
            del endfMFList[5][455]
        else :
            endfMFList[5][455] = MF5MT455List + [ endfFormatsModule.endfSENDLineNumber( ) ]
    if(   'promptNubar' in targetInfo.dict ) :
        promptNubar = targetInfo['promptNubar']
        multiplicityModule.fissionNeutronsToENDF6( 456, promptNubar, endfMFList, flags, targetInfo )
        totalNubar = promptNubar
        try :
            if( not( totalDelayedNubar is None ) ) : totalNubar = totalNubar + totalDelayedNubar
        except :                                # The following is a kludge for some "bad" data.
            if( ( totalNubar.domainMax( unitTo = 'MeV' ) == 30. ) and
                ( totalDelayedNubar.domainMax( unitTo = 'MeV' ) == 20. ) ) :
                    totalDelayedNubar[-1] = [ totalNubar.domainMax( ), totalDelayedNubar.getValue( totalDelayedNubar.domainMax( ) ) ]
            totalNubar = totalNubar + totalDelayedNubar
    elif( 'totalNubar' in targetInfo.dict ) :
        totalNubar = targetInfo['totalNubar']
    if( totalNubar is not None ) :
        multiplicityModule.fissionNeutronsToENDF6( 452, totalNubar, endfMFList, flags, targetInfo )

    if( covarianceSuite ) : covarianceSuite.toENDF6( endfMFList, flags, targetInfo )

    endfDoc = self.documentation.get( 'endfDoc' )
    if( endfDoc is None ) :
        docHeader2 = [  ' %2d-%-2s-%3d LLNL       EVAL-OCT03 Unknown' % ( targetZ, fudge.particles.nuclear.elementSymbolFromZ( targetZ ), targetA ),
                        '                      DIST-DEC99                       19990101   ',
                        '----ENDL              MATERIAL %4d' % MAT,
                        '-----INCIDENT %s DATA' %
                            { 1 : 'NEUTRON', 1001 : 'PROTON', 1002 : 'DEUTERON', 1003 : 'TRITON', 2003 : 'HELION', 2004 : 'ALPHA' }[projectileZA],
                        '------ENDF-6 FORMAT' ]
        endfDoc = [ 'LLNL ENDL file translated to ENDF6 by FUDGE.', '' ' ************************ C O N T E N T S ***********************' ]
    else :
        docHeader2 = []
        endfDoc = endfDoc.getLines( )

        # update the documentation, including metadata on first 4 lines:
    try :
        self.getReaction( 'fission' )
        LFI = True
    except KeyError :
        LFI = False
    LRP = -1
    if( self.resonances is not None ) :
        if( self.resonances.scatteringRadius ) :
            LRP = 0
        elif( self.resonances.reconstructCrossSection ) :
            LRP = 1
        elif( self.resonances.unresolved and not( self.resonances.resolved )
                and self.resonances.unresolved.tabulatedWidths.forSelfShieldingOnly ) :
            LRP = 1
        else :
            LRP = 2
    EMAX = max( [ reaction.crossSection.domainMax( unitTo = 'eV' ) for reaction in self.reactions ] )

    temperature = self.styles[style].temperature.getValueAs( 'K' )
    library = evaluatedStyle.library
    version = evaluatedStyle.version
    if( library == 'ENDL' ) :           # Additional ENDF meta-data. If the library is unknown, use NLIB = -1
        NVER, LREL, NMOD = 1, 1, 1
        NLIB = -1
    else :
        NVER, LREL, NMOD = map( int, version.split( '.' ) )    # Version stored as '7.2.1'
        NLIB = { "ENDF/B" :  0,     "ENDF/A" :  1,      "JEFF"                 :  2,    "EFF"      :  3,    "ENDF/B (HE)" :  4,
                 "CENDL"  :  5,     "JENDL"  :  6,      "SG-23"                : 21,    "INDL/V"   : 31,    "INDL/A"      : 32,
                 "FENDL"  : 33,     "IRDF"   : 34,      "BROND (IAEA version)" : 35,    "INGDB-90" : 36,    "FENDL/A"     : 37,
                 "BROND"  : 41 }.get( library, -1 )

    NFOR = 6    # ENDF-6 format
    NSUB = 10 * IPART + ITYPE
    LDRV = 0
    STA = 0
    if( isinstance( self.target, fudge.gnd.xParticle.nuclearLevel ) or self.target.attributes.get( 'unstable' ) ) : STA = 1
    if( targetInfo['LISO'] ) : STA = 1
    levelIndex, level_eV = 0, 0.
    if( hasattr( self.target, 'getLevelIndex' ) ) : levelIndex, level_eV = self.target.getLevelIndex( ), self.target.getLevelAsFloat( 'eV' )
    docHeader = [ endfFormatsModule.endfHeadLine( targetZA, targetInfo['mass'], LRP, LFI, NLIB, NMOD ),
            endfFormatsModule.endfHeadLine( level_eV, STA, levelIndex, targetInfo['LISO'], 0, NFOR ),
            endfFormatsModule.endfHeadLine( self.projectile.getMass( 'eV/c**2' ) / targetInfo['neutronMass'], EMAX, LREL, 0, NSUB, NVER ),
            endfFormatsModule.endfHeadLine( temperature, 0, LDRV, 0, len( endfDoc ), -1 ) ]
    new_doc = fudge.gnd.documentation.documentation( 'endf', '\n'.join( docHeader + docHeader2 + endfDoc ) )
    endfMFList[1][451] += endfFormatsModule.toEndfStringList( new_doc )

    return( endfFormatsModule.endfMFListToFinalFile( endfMFList, MAT, lineNumbers = True ) )
Esempio n. 8
0
def upDateENDF_MT_MF8Data(MT, endfMFList, targetInfo):

    reactionSuite = targetInfo['reactionSuite']
    MF8Channels = targetInfo['MF8'][MT]
    ZA, mass = targetInfo['ZA'], targetInfo['mass']
    LIS, LISO, NO, NS = targetInfo['LIS'], targetInfo['LISO'], 1, len(
        MF8Channels)
    firstReaction = MF8Channels[0]
    residual = firstReaction.outputChannel[0]

    crossSection_ = firstReaction.crossSection[
        targetInfo['style']]  # LMF determines which MF section to write to.
    if (isinstance(crossSection_, crossSectionModule.reference)):
        multiplicity = residual.multiplicity[targetInfo['style']]
        if (isinstance(multiplicity, multiplicityModule.constant1d)):
            LMF = 3
        elif (isinstance(multiplicity, multiplicityModule.reference)):
            LMF = 6
        else:
            LMF = 9
    else:
        LMF = 10

    level = 0
    if (hasattr(residual, 'getLevelAsFloat')):
        level = residual.getLevelAsFloat('eV')
    endfMFList[8][MT] = [
        endfFormatsModule.endfHeadLine(ZA, mass, LIS, LISO, NS, NO)
    ]
    if (LMF not in [3, 6]):
        endfMFList[LMF][MT] = [
            endfFormatsModule.endfHeadLine(ZA, mass, LIS, 0, NS, 0)
        ]

    for reaction in MF8Channels:
        outputChannel = reaction.outputChannel
        if (len(outputChannel) != 1):
            raise Exception(
                'Currently, production channel can only have one product; not %d'
                % len(outputChannel))
        product = outputChannel[0]

        particle = reactionSuite.PoPs[product.id]
        ZAP = miscPoPsModule.ZA(particle)

        QI = outputChannel.getConstantQAs('eV', final=True)
        LFS2, level2 = 0, 0
        if (isinstance(particle, nuclearLevelModule.particle)):
            LFS2 = particle.intIndex
            level2 = particle.energy[0].float('eV')
        QM = QI + level2

        endfMFList[8][MT].append(
            endfFormatsModule.endfHeadLine(ZAP, level2, LMF, LFS2, 0, 0))

        if (
                LMF == 9
        ):  # Currenty, multiplicity.toENDF6List only has one interpolation and its linear.
            multiplicity = product.multiplicity[targetInfo['style']]
            interpolationFlatData, nPoints, multiplicityList = multiplicity.toENDF6List(
                targetInfo)
            endfMFList[LMF][MT].append(
                endfFormatsModule.endfHeadLine(QM, QI, ZAP, LFS2,
                                               len(interpolationFlatData) / 2,
                                               nPoints))
            endfMFList[LMF][MT] += endfFormatsModule.endfInterpolationList(
                interpolationFlatData)
            endfMFList[LMF][MT] += multiplicityList
        elif (LMF == 10):
            interpolationFlatData, flatData = reaction.crossSection[
                targetInfo['style']].toENDF6Data(MT, endfMFList, targetInfo,
                                                 level2)
            endfMFList[LMF][MT].append(
                endfFormatsModule.endfHeadLine(QM, QI, ZAP, LFS2,
                                               len(interpolationFlatData) / 2,
                                               len(flatData) / 2))
            endfMFList[LMF][MT] += endfFormatsModule.endfInterpolationList(
                interpolationFlatData)
            endfMFList[LMF][MT] += endfFormatsModule.endfDataList(flatData)

    endfMFList[8][MT].append(endfFormatsModule.endfSENDLineNumber())
    if (LMF not in [3, 6]):
        endfMFList[LMF][MT].append(endfFormatsModule.endfSENDLineNumber())
Esempio n. 9
0
def gammasToENDF6_MF6(MT, endfMFList, flags, targetInfo, gammas):
    # FIXME - Still need to convert energies to eV.

    def checkOrder(nOrders, data, gammaEnergy, EIn):

        if (nOrders < 0): nOrders = len(data)
        if (nOrders != len(data)):
            raise Exception( "nOrders = %d != len( data ) = %d for gammaEnergy = %s, incident energy = %s" % \
                    ( nOrders, len( data ), gammaEnergy, EIn ) )

    def getTotalMultiplicityRegion(region, multiplicityRegions):

        for i2, totalRegion in enumerate(multiplicityRegions):
            if (totalRegion.domainMin <= region.domainMin):
                if (totalRegion.domainMax > region.domainMin):
                    return (i2, totalRegion)
        for i2, totalRegion in enumerate(multiplicityRegions):
            print i2, totalRegion.domainMin, totalRegion.domainMax
        raise Exception('Could not find total region with domain %s, %s' %
                        (self.domainMin, self.domainMax))

    if (len(gammas) == 1):  # Check for LLNL legacy data
        distribution = gammas[0].distribution
        component = distribution[targetInfo['style']]
        if (not (isinstance(component, uncorrelatedModule.form))):
            raise 'hell - fix me: was check for LLNL special data'
            component.toENDF6(MT, endfMFList, flags, targetInfo)
            return

    LANG, interpolationEIn, nOrders, discreteGammasVsEIn, continuum = 1, 2, -1, {}, None
    massRatio = targetInfo['mass'] / (targetInfo['mass'] + 1.)

    LEP, discreteLEP = -2, -2
    frame = None
    for gamma in gammas:  # Determine LEP and frame
        component = gamma.distribution[targetInfo['style']]
        isPrimary, isDiscrete, energySubform, angularSubform = gammaType(
            component)
        if (isPrimary or isDiscrete):
            if (not (isinstance(
                    angularSubform,
                (angularModule.XYs2d, angularModule.isotropic)))):
                raise 'hell - fix me'
            if (discreteLEP < 0):
                discreteLEP = 2
                if (isinstance(angularSubform, angularModule.XYs2d)):
                    if (len(angularSubform.axes) == 3):
                        if (angularSubform.interpolation ==
                                standardsModule.interpolation.flatToken):
                            discreteLEP = 1
        else:
            if (LEP < 0):
                if (isinstance(component, energyAngularModule.form)):
                    energy1 = component.energyAngularForm[0]
                    LEP = gndToENDF2PlusDInterpolationFlag(
                        energy1.interpolation, energy1.interpolationQualifier)
                else:
                    EpForm = energySubform[0]
                    if (isinstance(EpForm, energyModule.regions1d)):
                        EpForm = EpForm[0]
                    LEP = gndToENDF2PlusDInterpolationFlag(
                        EpForm.interpolation,
                        standardsModule.interpolation.noneQualifierToken)
        if (frame is None): frame = component.productFrame
    if (LEP < 0): LEP = discreteLEP
    if (frame is None): return

    if (len(gammas) == 1):
        if (gammasToENDF6_MF6_oneGamma(MT, endfMFList, flags, targetInfo,
                                       gammas[0], LANG, abs(LEP), frame)):
            return

    total = [
        tmp for tmp in targetInfo['reactionSuite'].sums.multiplicities
        if tmp.ENDF_MT == MT
    ]
    if (len(total) > 1):
        raise Exception("Multiple total gamma multiplicities for MT=%d" % MT)
    elif (len(total) == 1):
        total = total[0]
        if (isinstance(total, sumsModule.multiplicitySum)):
            totalMultiplicity = total.multiplicity[targetInfo['style']].copy()
        elif (isinstance(total, multiplicityModule.component)):
            totalMultiplicity = total[targetInfo['style']].copy()
        else:
            raise TypeError('Unsupport multiplitiy type = "%s"' %
                            total.moniker)
    else:  # Total multiplicity is missing in sums section, compute from parts.
        multiplicities = [
            gamma.multiplicity[targetInfo['style']] for gamma in gammas
        ]
        totalMultiplicity = multiplicities.pop(0)
        for multiplicity in multiplicities:
            totalMultiplicity += multiplicity
    if (isinstance(totalMultiplicity, multiplicityModule.regions1d)):
        totalMultiplicityRegions = totalMultiplicity.copy()
    else:
        totalMultiplicityRegions = multiplicityModule.regions1d(
            axes=totalMultiplicity.axes)
        totalMultiplicityRegions.append(totalMultiplicity)


# This data was originally a Legendre expansions with only L=0 terms, was converted to uncorrelated.
# Also, original data stored one multiplicity for all gammas, with weights for individual gammas.
# Convert back to Legendre.

    discreteWeightsRegions = [{} for region in totalMultiplicityRegions]
    for gamma in gammas:
        multiplicity = gamma.multiplicity[targetInfo['style']]
        component = gamma.distribution[targetInfo['style']]
        isPrimary, isDiscrete, energySubform, angularSubform = gammaType(
            component)
        if (not (isPrimary or isDiscrete)):
            continuum = gamma
            continue

        if (isinstance(multiplicity, multiplicityModule.regions1d)):
            multiplicityRegions = multiplicity.copy()
        else:
            if (isinstance(multiplicity, multiplicityModule.XYs1d)):
                multiplicityRegions = multiplicityModule.regions1d(
                    axes=multiplicity.axes)
                multiplicityRegions.append(multiplicity)
            else:
                raise Exception('Unsupported multiplicity "%s"' %
                                multiplicity.moniker)
        for i1, region in enumerate(multiplicityRegions):
            i2, totalRegion = getTotalMultiplicityRegion(
                region, totalMultiplicityRegions)
            for EIn, probability in region:
                total = totalRegion.evaluate(EIn)
                if (total != 0): probability /= total
                gammaEnergy = PQUModule.PQU(
                    energySubform.value,
                    energySubform.axes[1].unit).getValueAs('eV')
                realGammaEnergy = gammaEnergy
                if (isPrimary):
                    realGammaEnergy = -(gammaEnergy + massRatio * EIn)
                if (EIn not in discreteWeightsRegions[i2]):
                    discreteWeightsRegions[i2][EIn] = []
                discreteWeightsRegions[i2][EIn].append(
                    [realGammaEnergy, probability])
    if (
            continuum is None
    ):  # Check if we need to fix probability for lowest energy where multiplicity is 0.
        region = discreteWeightsRegions[0]
        EIn = sorted(region.keys())[0]
        total = sum([probability for energy, probability in region[EIn]])
        if (total == 0):
            norm = 1 / len(region[EIn])
            for xy in region[EIn]:
                xy[1] = norm

    continuumGammasRegions = [{} for region in totalMultiplicityRegions]
    if (continuum is not None):
        multiplicity = continuum.multiplicity[targetInfo['style']]
        if (isinstance(multiplicity, multiplicityModule.regions1d)):
            multiplicityRegions = multiplicity.copy()
        else:
            if (isinstance(multiplicity, multiplicityModule.XYs1d)):
                multiplicityRegions = multiplicityModule.regions1d(
                    axes=multiplicity.axes)
                multiplicityRegions.append(multiplicity)
            else:
                raise Exception('Unsupported multiplicity "%s"' %
                                multiplicity.moniker)

        component = continuum.distribution[targetInfo['style']]
        if (isinstance(component, uncorrelatedModule.form)):
            angularSubform = component.angularSubform.data
            energySubform = component.energySubform.data
            if (not (isinstance(angularSubform, angularModule.isotropic))):
                raise Exception('Unsupport angular form = "%s"' %
                                angularSubform.moniker)
            if (not (isinstance(energySubform, energyModule.regions2d))):
                energySubform = [energySubform]
            interpolationEIn = gndToENDF2PlusDInterpolationFlag(
                energySubform[0].interpolation,
                energySubform[0].interpolationQualifier)
            EInFactor = PQUModule.PQU(
                1, energySubform[0].axes[2].unit).getValueAs('eV')
            EOutFactor = PQUModule.PQU(
                1, energySubform[0].axes[1].unit).getValueAs('eV')
            for i1, region in enumerate(energySubform):
                i2, multiplicityRegion = getTotalMultiplicityRegion(
                    region, multiplicityRegions)
                i2, totalRegion = getTotalMultiplicityRegion(
                    region, totalMultiplicityRegions)
                for energyInData in region:
                    EIn = energyInData.value
                    total = totalRegion.evaluate(EIn)
                    continuumMultiplicity = multiplicityRegion.evaluate(EIn)
                    data = []
                    if (isinstance(energyInData, energyModule.regions1d)):
                        for region2 in energyInData:
                            for Ep, probability in region2:
                                if (total != 0):
                                    probability *= continuumMultiplicity / total
                                data.append(Ep * EOutFactor)
                                data.append(probability)
                    else:
                        for Ep, probability in energyInData:
                            if (total != 0):
                                probability *= continuumMultiplicity / total
                            data.append(Ep * EOutFactor)
                            data.append(probability)
                    continuumGammasRegions[i2][EIn * EInFactor] = data

        elif (isinstance(component, energyAngularModule.form)):
            raise 'hell - FIXME'
            if (len(continuumGammasRegions) > 0):
                raise Exception('Multiple regions not supported for %s' %
                                component.moniker)
            form = component.energyAngularForm
            interpolationEIn = gndToENDF2PlusDInterpolationFlag(
                form.interpolation, form.interpolationQualifier)
            EInFactor = PQUModule.PQU(1,
                                      component.axes[-1].unit).getValueAs('eV')
            EOutFactor = PQUModule.PQU(
                1, component.axes[-2].unit).getValueAs('eV')
            incident_e_vals = []
            for energy_in in form:
                EIn = energy_in.value
                continuumGammas = []
                for EoutCl in energy_in:
                    nOrders = checkOrder(nOrders, EoutCl, gammaEnergy, EIn)
                    continuumGammas += [EoutCl.value * EOutFactor
                                        ] + EoutCl.coefficients
                incident_e_vals.append(EIn * EInFactor)
                continuumGammasRegions[0][EIn * EInFactor] = continuumGammas
        else:
            raise Exception('Unsupport continuum gamma distribution = "%s"' %
                            component.moniker)

    NE = 0
    interpolations = []
    for i1, discreteWeightsRegion in enumerate(discreteWeightsRegions):
        continuumGammasRegion = continuumGammasRegions[i1]
        N = len(
            sorted(
                set(discreteWeightsRegion.keys() +
                    continuumGammasRegion.keys())))
        NE += N
        interpolations += [NE, interpolationEIn]
    NR = len(totalMultiplicityRegions)

    ENDFDataList = [
        endfFormatsModule.endfContLine(0, 0, LANG, abs(LEP), NR, NE)
    ]
    ENDFDataList.append(
        endfFormatsModule.endfInterpolationLine(interpolations))

    nOrders = 1  # FIXME
    wordsPerEout = nOrders + 1
    for i1, discreteWeightsRegion in enumerate(discreteWeightsRegions):
        continuumGammasRegion = continuumGammasRegions[i1]
        EIns = sorted(
            set(discreteWeightsRegion.keys() + continuumGammasRegion.keys()))
        for EIn in EIns:
            ND = 0
            gammaData = []
            if (EIn in discreteWeightsRegion):
                discreteGammas = sorted(discreteWeightsRegion[EIn],
                                        reverse=True)
                for discreteGamma in discreteGammas:
                    gammaData += discreteGamma
                ND = len(gammaData) / wordsPerEout
            if (EIn in continuumGammasRegion):
                gammaData += continuumGammasRegion[EIn]
            NW = len(gammaData)
            NEP = len(gammaData) / wordsPerEout
            ENDFDataList += [
                endfFormatsModule.endfContLine(0, EIn, ND, nOrders - 1, NW,
                                               NEP)
            ]
            ENDFDataList += endfFormatsModule.endfDataList(gammaData)
    targetInfo['multiplicity'] = totalMultiplicity
    toENDF6_MF6(MT, endfMFList, flags, targetInfo, 1, frame, ENDFDataList)