Пример #1
0
    def check( self, info ) :
        """
        Check for incomplete angular distributions + any negative probabilities.
        Ignore normalization for this double-differential distribution.
        """

        from fudge.gnd import warning
        from pqu import PQU
        warnings = []

        for index, energy_in in enumerate(self):
            integral = energy_in.integrate()
            if abs(integral - 1.0) > info['normTolerance']:
                warnings.append( warning.unnormalizedDistribution( PQU.PQU(energy_in.value, self.axes[0].unit),
                    index, integral, self.toXLink() ) )
            if( energy_in.domainMin != -1 ) or ( energy_in.domainMax != 1 ) :
                warnings.append( warning.incompleteDistribution( PQU.PQU(energy_in.value, self.axis[0].unit),
                        energy_in.domainMin, energy_in.domainMax, energy_in ) )
            for mu in energy_in:
                if( mu.domainMin < 0 ) :
                    warnings.append( warning.valueOutOfRange("Negative outgoing energy for energy_in=%s!"
                        % PQU.PQU(energy_in.value, self.axes[0].unit), mu.domainMin, 0, 'inf', self.toXLink() ) )
                if( mu.rangeMin < 0 ) :
                    warnings.append( warning.negativeProbability( PQU.PQU(energy_in.value, self.axes[-1].unit),
                        mu=mu.value, obj=mu ) )

        return warnings
Пример #2
0
 def test_getMatchingComponent_1(self):
     '''Fails because there is no component of section 1 with such bounds'''
     self.assertRaises(ValueError,
                       FeCovariance[1]['eval'].getMatchingComponent,
                       rowBounds=(PQU.PQU("1.e-5 eV"), PQU.PQU("2.e7 eV")),
                       columnBounds=(PQU.PQU("1.e-5 eV"),
                                     PQU.PQU("2.e7 eV")))
Пример #3
0
def toENDL(incoherentElastic, energyMin_MeV, energyMax_MeV, temperature_MeV):

    sigma_b = incoherentElastic.characteristicCrossSection.getValueAs('b')
    temperature = PQUModule.PQU(temperature_MeV, 'MeV/k').getValueAs(
        incoherentElastic.DebyeWaller.axes[1].unit)
    debyeWallerPrime = incoherentElastic.DebyeWaller.evaluate(temperature)
    debyeWallerPrime = PQUModule.PQU(
        debyeWallerPrime,
        incoherentElastic.DebyeWaller.axes[0].unit).getValueAs('1/MeV')

    parameters = {'debyeWallerPrime': debyeWallerPrime, 'sigma_b': sigma_b}

    crossSection = [[energy, crossSectionAtEnergy(energy, parameters)]
                    for energy in [energyMin_MeV, energyMax_MeV]]
    crossSection = fudgemath.thickenXYList(crossSection,
                                           evaluator(crossSectionAtEnergy,
                                                     parameters),
                                           biSectionMax=12)

    PmuGivenE = []
    for energy, sigma in crossSection:
        parameters['energy'] = energy
        PmuForEachE = [[mu, incoherentElasticPmuGivenE(mu, parameters)]
                       for mu in [-1., 1.]]
        PmuForEachE = fudgemath.thickenXYList(PmuForEachE,
                                              evaluator(
                                                  incoherentElasticPmuGivenE,
                                                  parameters),
                                              biSectionMax=12)
        PmuGivenE.append([energy, PmuForEachE])

    return (crossSection, PmuGivenE, None)
Пример #4
0
    def check(self, info):

        from fudge.gnd import warning
        warnings = []

        if (not (self.aSubform.isEmptyASubform())):
            raise NotImplementedError(
                "Checking for Kalbach-Mann data with 'a' coefficients")

        for index, F in enumerate(
                self.fSubform.data
        ):  # F is like P(E' | E), must be normalized for each incident energy
            integral = F.integrate()
            if abs(integral - 1.0) > info['normTolerance']:
                warnings.append(
                    warning.unnormalizedKMDistribution(
                        PQUModule.PQU(F.value, F.axes[-1].unit), index,
                        integral, F))
            if F.rangeMin < 0:
                warnings.append(
                    warning.negativeProbability(PQUModule.PQU(
                        F.value, F.axes[-1].unit),
                                                obj=F))
        for R in self.rSubform.data:  # R = pre-compound fraction, must be between 0 and 1
            if R.rangeMin < 0 or R.rangeMax > 1:
                badR = R.rangeMin if (
                    0.5 - R.rangeMin > R.rangeMax - 0.5) else R.rangeMax
                warnings.append(
                    warning.valueOutOfRange(
                        "Invalid 'r' in KalbachMann distribution at incident energy %s"
                        % PQUModule.PQU(R.value, R.axes[-1].unit), badR, 0, 1,
                        R))

        return warnings
Пример #5
0
def toENDF6( self, flags, targetInfo ) :

    MT = 5
    EInInterpolation = gndToENDF6Module.gndToENDF2PlusDInterpolationFlag( self.interpolation, self.interpolationQualifier )
    EpInterpolation0 = gndToENDF6Module.gndToENDF2PlusDInterpolationFlag( self[0].interpolation, self[0].interpolationQualifier )
    if( EpInterpolation0 == 1 ) :       # flat interpolation
        LEP = 1
    elif( EpInterpolation0 == 2 ) :     # lin-lin interpolation
        LEP = 2
    else :
        raise 'hell - fix me'
    ENDFDataList = [ endfFormatsModule.endfContLine( 0, 0, 1, LEP, 1, len( self ) ) ]
    ENDFDataList += endfFormatsModule.endfInterpolationList( [ len( self ), EInInterpolation ] )
    energyInFactor = PQUModule.PQU( 1, self.axes[3].unit ).getValueAs( 'eV' )
    energyPFactor = PQUModule.PQU( 1, self.axes[2].unit ).getValueAs( 'eV' )
    for energyIn in self :
        if( not( isinstance( energyIn, multiD_XYsModule.XYs2d ) ) ) : raise 'hell - fix me'
        EpInterpolation = gndToENDF6Module.gndToENDF2PlusDInterpolationFlag( energyIn.interpolation, energyIn.interpolationQualifier )
        if( EpInterpolation != EpInterpolation0 ) : raise 'hell - fix me'
        NA, data = 0, []
        for energy_p in energyIn :
            if( not( isinstance( energy_p, series1dModule.LegendreSeries ) ) ) : raise 'hell - fix me'
            NA = max( len( energy_p ) , NA )
            coefficients = [ coefficient / energyPFactor for coefficient in energy_p ]
            data += [ energy_p.value * energyPFactor ] + coefficients
        ENDFDataList.append( endfFormatsModule.endfContLine( 0, energyIn.value * energyInFactor, 0, NA - 1, len( data ), len( data ) / ( NA + 1 ) ) )
        ENDFDataList += endfFormatsModule.endfDataList( data )
    LAW = 1
    return( LAW, ENDFDataList )
Пример #6
0
    def check(self, info):

        from fudge.gnd import warning

        warnings = []
        for idx, function in enumerate(self):
            xys = function.toPointwise_withLinearXYs(
                accuracy=info['normTolerance'], lowerEps=1e-6)

            if isinstance(function, Legendre):
                integral = function.coefficients[0]
            elif isinstance(function, XYs1d):
                integral = xys.integrate(-1, 1)
            else:
                raise NotImplementedError(
                    "checking function of type %s" %
                    type(function))  # FIXME support xs_pdf_cdf1d

            if abs(integral - 1.0) > info['normTolerance']:
                warnings.append(
                    warning.unnormalizedDistribution(
                        PQUModule.PQU(function.value, self.axes[-1].unit), idx,
                        integral, function))

            if (xys.rangeMin < 0.0):
                warnings.append(
                    warning.negativeProbability(PQUModule.PQU(
                        function.value, self.axes[-1].unit),
                                                value=xys.rangeMin,
                                                obj=function))

        return warnings
Пример #7
0
def toENDF6(self, flags, targetInfo, weight=None):

    U, EFL, EFH = 0, 0, 0
    if (self.LF == 12):
        EFL, EFH = self.EFL.getValueAs('eV'), self.EFH.getValueAs('eV')
    else:
        U = self.U.getValueAs('eV')
    parameter1 = self.parameter1.data
    energyFactor = float(
        PQUModule.PQU('1 eV') / PQUModule.PQU(1, parameter1.axes[1].unit))
    if (weight is None):
        weight = [[energyFactor * parameter1[0][0], 1.0],
                  [energyFactor * parameter1[-1][0], 1.0]]
        interpolation = 2
    elif (hasattr(weight, 'axes')):
        interpolation = gndToENDF6Module.gndToENDFInterpolationFlag(
            weight.interpolation)
    else:
        interpolation = 2
    ENDFDataList = [ endfFormatsModule.endfContLine( U, 0, 0, self.LF, 1, len( weight ) ) ] + \
        endfFormatsModule.endfInterpolationList( [ len( weight ), interpolation ] ) + endfFormatsModule.endfNdDataList( weight )
    ENDFDataList += endfFormatsModule.toTAB1(parameter1,
                                             'eV',
                                             'eV',
                                             C1=EFL,
                                             C2=EFH)
    if (self.parameter2 is not None):
        parameter2 = self.parameter2.data
        yUnit = ''
        if (self.LF in [5, 11]): yUnit = '1/eV'
        ENDFDataList += endfFormatsModule.toTAB1(parameter2, 'eV', yUnit)
    return (1, ENDFDataList)
Пример #8
0
def computeScatteringRadius( rs, useCovariance=True, covariance=None, verbose=False ):
    """
    Compute R', the scattering radius

    We take the E=0 point (or at least the lowest available energy point in the elastic cross section).

    with this,
        ..math::
            \sigma_{el}=4\pi(R')^2

    :param elxs: the elastic scattering cross section
    :param useCovariance:
    :param covariance:
    :return:
    """
    # get RRR parameter averages
    if (hasattr(rs.resonances,'resolved') and rs.resonances.resolved is not None):
        import fudge.processing.resonances.reconstructResonances as RRReconstruct
        resCls = RRReconstruct.getResonanceReconstructionClass(rs.resonances.resolved.evaluated.moniker)
        rrr = resCls( rs, None, enableAngDists=False, verbose=verbose )
        rrr.setResonanceParametersByChannel()
        R=rrr.getScatteringLength()
        return PQU.PQU(10.*R,'fm')
    elif (hasattr(rs.resonances,'scatteringRadius') and rs.resonances.scatteringRadius is not None):
        return PQU.PQU(rs.resonances.scatteringRadius.getValueAs( 'fm', energy_grid=[1e-5], L=0 ),'fm')
    else:
        return PQU.PQU(0.0,'fm')
Пример #9
0
def toENDF6( self, MT, endfMFList, flags, targetInfo ) :

    angularForm = self.angularForm
    angularEnergyForm = self.angularEnergyForm

    energy_inInterpolation, energy_inFunctionInterpolation, energy_inInterpolationQualifier = angularEnergyForm.axes[0].interpolation.getInterpolationTokens( )
    muInterpolation, muFunctionInterpolation, muQualifier = angularEnergyForm.axes[1].interpolation.getInterpolationTokens( )
    energy_outInterpolation, probabilityInterpolation, energy_outQualifier = angularEnergyForm.axes[2].interpolation.getInterpolationTokens( )
    frame = angularEnergyForm.getProductFrame( )
    axes = pointwise.defaultAxes( energyInterpolation = energy_inInterpolation, energyFunctionInterpolation = energy_inFunctionInterpolation, 
            energyInterpolationQualifier = energy_inInterpolationQualifier, muInterpolation = muInterpolation, 
            energy_outInterpolation = energy_outInterpolation, probabilityInterpolation = probabilityInterpolation )
    E_inRatio = PQUModule.PQU( 1, angularEnergyForm.axes[0].getUnit( ) ).getValueAs( 'eV' )
    E_outRatio = PQUModule.PQU( 1, angularEnergyForm.axes[2].getUnit( ) ).getValueAs( 'eV' )
    LAW7 = pointwise( axes, self.getProductFrame( ) )

    if( len( angularForm ) != len( angularEnergyForm ) ) :
        raise Exception( "len( angularForm ) = %s != len( angularEnergyForm ) = %s" % ( len( angularForm ), len( angularEnergyForm ) ) )
    for indexE, EMuP in enumerate( angularForm ) :
        EMuEpP = angularEnergyForm[indexE]
        if( EMuP.value != EMuEpP.value ) : raise Exception( "At indexE = %d, EMuP.value %s != EMuEpP.value = %s" % ( indexE, EMuP.value, EMuEpP.value ) )
        if( len( EMuP ) != len( EMuEpP ) ) :
            raise Exception( "At indexE = %d (E_in = %s), len( EMuP ) %s != len( EMuEpP ) = %s" % ( indexE, EMuP.value, len( EMuP ), len( EMuEpP ) ) )
        w_xys = W_XYs.W_XYs( axesW_XY, index = indexE, value = EMuP.value )
        for indexMu, muP in enumerate( EMuP ) :
            muEpP = EMuEpP[indexMu]
            if( muP[0] != muEpP.value ) : raise Exception( "At indexE = %d, mu = %s != muEpP.value = %s" % ( indexE, muP[0], muEpP.value ) )
            xys = [ [ E_outRatio * Ep, muP[1] * P / E_outRatio ] for Ep, P in muEpP ]
            xys = XYs.XYs( axesXY, xys, accuracy = muEpP.getAccuracy( ), value = muP[0], index = indexMu, parent = w_xys )
            w_xys.append( XYs.XYs( axesXY, muEpP * muP[1], accuracy = muEpP.getAccuracy( ), value = muP[0], index = indexMu, parent = w_xys ) )
        LAW7.append( w_xys )

    LAW, frame, MF6 = LAW7.toENDF6( flags, targetInfo )
    gndToENDF6Module.toENDF6_MF6( MT, endfMFList, flags, targetInfo, LAW, frame, MF6 )
Пример #10
0
    def heat(self,
             style,
             EMin,
             lowerlimit=None,
             upperlimit=None,
             interpolationAccuracy=0.002,
             heatAllPoints=False,
             doNotThin=True,
             heatBelowThreshold=True,
             heatAllEDomain=True,
             setThresholdToZero=False,
             addToSuite=False):
        """
        Returns the result of self.toPointwise_withLinearXYs( ).heat( ... ). See method XYs1d.heat for more information.
        If setThresholdToZero is True and self's cross section at the first point is 0., then the heated cross section's
        first value will also be 0.
        """

        styles = self.findAttributeInAncestry('styles')
        currentstyle = styles[style.derivedFrom]
        if (not (isinstance(currentstyle,
                            (stylesModule.evaluated, stylesModule.heated)))):
            TypeError(
                'Form to heat is not heatable form: its style moniker is "%s"'
                % style.label)
        currentTemperature = PQUModule.PQU(
            currentstyle.temperature.getValueAs('K'),
            'K') * PQUModule.PQU('1 k')
        currentTemperature = currentTemperature.getValueAs(self.domainUnit)

        newTemperature = PQUModule.PQU(style.temperature.getValueAs('K'),
                                       'K') * PQUModule.PQU('1 k')
        newTemperature = newTemperature.getValueAs(self.domainUnit)

        reactionSuite = self.getRootAncestor()
        projectile = reactionSuite.PoPs[reactionSuite.projectile]
        projectileMass = projectile.getMass('amu')
        if (projectileMass == 0):
            raise ValueError('Heating with gamma as projectile not supported.')

        target = reactionSuite.PoPs[reactionSuite.target]
        massRatio = target.getMass('amu') / projectileMass

        linear = self.toPointwise_withLinearXYs(accuracy=1e-5, upperEps=1e-8)
        heated = linear.heat(currentTemperature,
                             newTemperature,
                             massRatio,
                             EMin,
                             lowerlimit,
                             upperlimit,
                             interpolationAccuracy,
                             heatAllPoints,
                             doNotThin,
                             heatBelowThreshold,
                             heatAllEDomain,
                             setThresholdToZero=setThresholdToZero)
        heated.label = style.label
        if (addToSuite): self.add(heated)
        return (heated)
Пример #11
0
 def test_RI_vs_INTER(self):
     for r in self.eval['reactionSuite']:
         if r.ENDF_MT==1:
             self.assertIsClose(computeRI(r.crossSection,domainMax=PQU.PQU(1.00000E+05,'eV'),useCovariance=False), PQU.PQU(2.39596E+02,'b'), rel_tol=1e-5)
         if r.ENDF_MT==2:
             self.assertIsClose(computeRI(r.crossSection,domainMax=PQU.PQU(1.00000E+05,'eV'),useCovariance=False), PQU.PQU(2.39452E+02,'b'), rel_tol=1e-6)
         if r.ENDF_MT==102:
             self.assertIsClose(computeRI(r.crossSection,domainMax=PQU.PQU(1.00000E+05,'eV'),useCovariance=False), PQU.PQU(1.48914E-01,'b'), abs_tol=5e-6)
Пример #12
0
Файл: Q.py Проект: alhajri/FUDGE
    def getConstantAs( self, unit ) :   # FIXME: Remove?

        for form in self :
            if( isinstance( form, constant1d ) ) :
                return( PQUModule.PQU( form.constant, form.axes[0].unit ).getValueAs( unit ) )
            elif( isinstance( form, fissionEnergyReleasedModule.fissionEnergyReleased ) ) :
                return( PQUModule.PQU( form.nonNeutrinoEnergy.data.evaluate( 0 ) ) )
        raise ValueError( 'Q-value is not a constant' )
Пример #13
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)
Пример #14
0
 def test_check(self):
     from pqu import PQU
     info = {
         'Q': 1.0,
         'kinematicFactor': 1.0,
         'dThreshold': PQU.PQU('1e-4 b'),
         'crossSectionEnergyMax': PQU.PQU('20.0 MeV'),
         'CoulombChannel': False
     }
     self.assertEqual(self.xs_const.check(info), [])
Пример #15
0
def otherToSelfsUnits( self, other, checkXOnly = False ) :

    if( not( isinstance( other, XYs1d ) ) ) : raise TypeError( 'other instance not XYs1d instance' )
    if( ( self.axes is None ) and ( other.axes is None ) ) : return( other )
    yScale = 1
    xUnitSelf = PQU._getPhysicalUnit( self.axes[xAxisIndex].unit )
    xScale = xUnitSelf.conversionFactorTo( other.axes[xAxisIndex].unit )
    if( not( checkXOnly ) ) :
        yUnitSelf = PQU._getPhysicalUnit( self.axes[yAxisIndex].unit )
        yScale = yUnitSelf.conversionFactorTo( other.axes[yAxisIndex].unit )
    if( ( xScale != 1 ) or ( yScale != 1 ) ) : other = other.scaleOffsetXAndY( xScale = xScale, yScale = yScale )
    return( other )
Пример #16
0
        def test_MACS(self):
            """
            These test values come from B. Pritychenko, S.F. Mughabghab arXiv:1208.2879v3.
            """
            for r in self.eval['reactionSuite']:
                if r.ENDF_MT==102:
                    self.assertIsClose(computeMACS(r.crossSection, PQU.PQU(30.,'keV'),useCovariance=False), PQU.PQU(1.525E-4,'b'), abs_tol=1e-7)
                    self.assertIsClose(computeMACS(r.crossSection, PQU.PQU(1420.,'keV'),useCovariance=False), PQU.PQU(3.892E-5,'b'), abs_tol=2e-8)

                    # Turn on covariance, what happens then?
                    self.assertIsClose(computeMACS(r.crossSection, PQU.PQU(30.,'keV'),useCovariance=True), PQU.PQU("1.524e-4 +/- 5.6e-6 b"), abs_tol=1e-7)
                    break
Пример #17
0
 def test_shrinkToBounds(self):
     self.maxDiff = None
     self.assertXMLListsEqual(
         FeCovariance[0]['eval'].shrinkToBounds(
             (PQU.PQU("862270 eV"), PQU.PQU("1.5e7 eV")), ).toXMLList(),
         [
             '<mixed>', '  <covarianceMatrix index="1" type="relative">',
             '    <axes>',
             '      <axis index="0" label="row_energy_bounds" unit="eV" interpolation="lin,flat" length="6"> 862270 1e6 2e6 5e6 1e7 1.5e7</axis>',
             '      <axis index="1" label="column_energy_bounds" unit="eV" interpolation="lin,flat" mirror_row_energy_bounds="true"/>',
             '      <axis index="2" label="matrix_elements" unit=""/></axes>',
             '    <matrix rows="6" columns="6" form="diagonal" precision="6"> 9.900000e-05  5.564000e-03  1.584000e-03  8.910000e-04  3.960000e-04  3.960000e-04 </matrix></covarianceMatrix></mixed>'
         ])
Пример #18
0
    def parseXMLNode(element, xPath, linkData):

        xPath.append(element.tag)
        default = PQU.PQU(element.find('default').get('value'))
        lvals = {}
        for child in element:
            if child.tag == 'Lspecific':
                lval = int(child.get('L'))
                lvals[lval] = PQU.PQU(child.get('value'))
        result = LdependentScatteringRadii(default, lvals,
                                           element.get('label'))
        xPath.pop()
        return result
Пример #19
0
    def evaluateWithUncertainty(self,
                                E,
                                useCovariance=True,
                                covariance=None,
                                covarianceSuite=None):
        """

        :param E:
        :param useCovariance: use this to override covarance usage
        :type useCovariance: bool
        :param covariance:
        :param covarianceSuite:
        :return:
        """
        import fudge.gnd.covariances.base as covModule

        if (not isinstance(E, PQUModule.PQU)):
            raise TypeError("E must be an PQUModule.PQU instance")

        ptwise = self.hasLinearForm()
        if ptwise is None:
            ptwise = self.toPointwise_withLinearXYs(lowerEps=lowerEps,
                                                    upperEps=upperEps)

        EinDomainUnit = E.getValueAs(ptwise.domainUnit)
        if EinDomainUnit < ptwise.domainMin or EinDomainUnit > ptwise.domainMax:
            meanValue = 0.0
        else:
            meanValue = ptwise.evaluate(EinDomainUnit)

        # We might be done
        if not useCovariance:
            return PQUModule.PQU(meanValue, unit=ptwise.rangeUnit)

        # Get that the covariance goes with the data.
        covariance = self.getMatchingCovariance(covariance, covarianceSuite)

        if covariance is None:
            return PQUModule.PQU(meanValue, unit=ptwise.rangeUnit)
        else:
            try:
                return (PQUModule.PQU(
                    meanValue,
                    unit=ptwise.rangeUnit,
                    uncertainty=covariance.getUncertaintyVector(
                        self.evaluated,
                        relative=False).evaluate(EinDomainUnit)))
            except IndexError as err:  # FIXME: a kludge until cov routines working again, try it on 27Al(n,tot)
                print "WARNING: Could not extract uncertianty, got error %s" % str(
                    err)
                return PQUModule.PQU(meanValue, unit=ptwise.rangeUnit)
Пример #20
0
 def parseXMLNode(element, xPath, linkData):
     xPath.append(element.tag)
     value = PQU.PQU(element.get('value'))
     bounds = None
     if 'lowerBound' in element.keys():
         bounds = tuple([
             PQU.PQU(element.get(bound))
             for bound in ('lowerBound', 'upperBound')
         ])
     CSR = constantScatteringRadius(value,
                                    bounds=bounds,
                                    label=element.get('label'))
     xPath.pop()
     return CSR
Пример #21
0
def convert_units_to_energy(T, energyUnits='eV'):
    if type(T) == str: T = PQU.PQU(T)
    if not isinstance(T, PQU.PQU):
        raise TypeError(
            "argument to convert_units_to_energy must be a PQU, got type=%s" %
            str(type(T)))
    if T.isEnergy(): return T.inUnitsOf(energyUnits)
    elif T.isTemperature():
        return (T.inUnitsOf('K') *
                PQU.PQU(8.6173324e-5, 'eV/K')).inUnitsOf(energyUnits)
        #    elif T.isMass(): return
        #    elif T.isLength(): return
        #    elif T.isTime(): return
    else:
        raise Exception("Cannot convert %s to energy units" % str(T))
Пример #22
0
    def __init__(self,
                 particleLibrary,
                 projectile,
                 target,
                 library="ENDF/B",
                 version=None,
                 documentation=None,
                 transportables=['n']):
        if version is None:
            import datetime
            version = datetime.datetime.today().strftime("%Y")
        self.rs = gnd.reactionSuite.reactionSuite(
            projectile,
            target,
            style=gnd.miscellaneous.style("evaluated", {
                'library': library,
                'version': version
            }))
        self.rs.addDocumentation(
            gnd.documentation.documentation(
                library, documentation or "skeleton for documentation"))
        self.rs.setAttribute('temperature', PQU.PQU(0, 'K'))

        self.rs.projectile.attributes['transportable'] = True
        self.particleLibrary = particleLibrary
        self.transportables = transportables

        self.units = None
Пример #23
0
    def parseXMLNode(productElement, xPath, linkData):
        """Translate a <product> element from xml."""

        xPath.append('%s[@label="%s"]' %
                     (productElement.tag, productElement.get('label')))
        attrs = dict(productElement.items())
        prod = product(id=attrs.pop('name'), label=attrs.pop('label'))
        prod.multiplicity.parseXMLNode(
            productElement.find(multiplicityModule.component.moniker), xPath,
            linkData)
        prod.distribution.parseXMLNode(
            productElement.find(distributionModule.component.moniker), xPath,
            linkData)
        outputChannel = productElement.find(channelsModule.outputChannelToken)
        if (outputChannel):
            prod.addOutputChannel(
                channelsModule.parseXMLNode(outputChannel, xPath, linkData))
        for attr in ('decayRate', 'primary', 'discrete'):
            if (attr in attrs):
                attrs[attr] = PQUModule.PQU(attrs[attr])
        prod.attributes = attrs

        depositionEnergyToken = energyDepositionModule.component.moniker
        if (productElement.find(depositionEnergyToken) is not None):
            prod.energyDeposition.parseXMLNode(
                productElement.find(depositionEnergyToken), xPath, linkData)
        depositionMomentumToken = momentumDepositionModule.component.moniker
        if (productElement.find(depositionMomentumToken) is not None):
            prod.momentumDeposition.parseXMLNode(
                productElement.find(depositionMomentumToken), xPath, linkData)
        xPath.pop()
        return (prod)
Пример #24
0
def toENDF6(self, flags, targetInfo):

    MF6 = [endfFormatsModule.endfContLine(0, 0, 0, 0, 1, len(self))]
    EInInterpolation = gndToENDF6Module.gndToENDF2PlusDInterpolationFlag(
        self.interpolation, self.interpolationQualifier)
    energyConversionFactor = PQUModule.PQU(1,
                                           self.axes[-1].unit).getValueAs('eV')
    MF6 += endfFormatsModule.endfInterpolationList(
        [len(self), EInInterpolation])
    for oneEin in self:
        muInterpolation = gndToENDF6Module.gndToENDF2PlusDInterpolationFlag(
            self.interpolation, self.interpolationQualifier)
        Ein = oneEin.value * energyConversionFactor
        numMu = len(oneEin)
        MF6 += [endfFormatsModule.endfContLine(0, Ein, 0, 0, 1, numMu)]
        MF6 += endfFormatsModule.endfInterpolationList(
            [numMu, muInterpolation])
        for entries in oneEin:
            pdf_of_EpInterpolation = gndToENDF6Module.gndToENDFInterpolationFlag(
                self.interpolation)
            mu = entries.value
            numEout = len(entries)
            MF6 += [endfFormatsModule.endfContLine(0, mu, 0, 0, 1, numEout)]
            MF6 += endfFormatsModule.endfInterpolationList(
                [numEout, pdf_of_EpInterpolation])
            xys = entries.copyDataToXYs(xUnitTo='eV', yUnitTo='1/eV')
            MF6 += endfFormatsModule.endfNdDataList(xys)
    return (7, standardsModule.frames.labToken, MF6)
Пример #25
0
    def integrateTwoFunctions(self, f2, domainMin=None, domainMax=None):
        """

        :param f2:
        :param domainMin:
        :param domainMax:
        :return:
        """

        if (not isinstance(f2, XYs1d)):
            raise TypeError("f2 must be an instance of an XYs1d")
        unit = self.axes[xAxisIndex].unit
        if (f2.axes[xAxisIndex].unit != unit):
            f2 = f2.copy()
            f2.convertAxisToUnit(xAxisIndex, unit)
        domainMin, domainMax = baseModule.getDomainLimits(
            self, domainMin, domainMax, unit)
        domainMin = max(domainMin, self.domainMin, f2.domainMin)
        domainMax = min(domainMax, self.domainMax, f2.domainMax)
        return (PQU.PQU(pointwiseXY.groupTwoFunctions(self,
                                                      [domainMin, domainMax],
                                                      f2)[0],
                        baseModule.processUnits(
                            baseModule.processUnits(unit,
                                                    self.axes[yAxisIndex].unit,
                                                    '*'),
                            f2.axes[yAxisIndex].unit, '*'),
                        checkOrder=False))
Пример #26
0
def computeAstrophysicalReactionRate( xs, T, useCovariance=True, covariance=None ):
    '''
    The astrophysical reaction rate R is defined as :math:`R = N_A <\sigma v>`, where 
    :math:`N_A` is Avagadro's number.  It is typically reported in units of [cm^3/mole s].

    :param PQU T: temperature as a physical quantity
    :param useCovariance: use this to override covarance usage
    :type useCovariance: bool
    :param covariance: covariance to use when computing uncertainty on the spectral average.
        If None (default: None), no uncertainty is computed.
    :type covariance: covariance instance or None
    :rtype: PQU
    
    .. warning:: Not implemented yet
    '''
    check_is_cross_section( xs )

    if T is None: kT=convert_units_to_energy(ROOMTEMPERATURE)
    else:         kT=convert_units_to_energy(T)

    m2 = xs.getRootAncestor().PoPs[xs.getRootAncestor().target].getMass('amu')
    m1 = xs.getRootAncestor().PoPs[xs.getRootAncestor().projectile].getMass('amu')
    mu = PQU.PQU(m1*m2/(m1+m2),'amu')

    vT=(2.0*kT/mu).sqrt()
    return (AVAGADROSNUMBER*computeMACS(xs,kT,useCovariance=useCovariance,covariance=covariance)*vT).inUnitsOf( "cm**3/mol/s" )
Пример #27
0
def convertUnit(unitFrom, unitTo, xs, xErrs, legend):
    if unitTo is None: return None
    if unitFrom is None: return None

    unitFrom = unitFrom.replace('EV', 'eV')
    if 'PER-CENT' in unitFrom: unitFrom = 'PERCENT'
    elif 'no-dim' in unitFrom: unitFrom = ''
    elif 'DEG-K' in unitFrom: unitFrom = 'K'
    elif 'KeV' in unitFrom: unitFrom = 'keV'
    unit = unitFrom
    if ((unitFrom is not None) and (unitTo is not None)
            and (unitFrom != unitTo)):
        try:
            conversionFactor = PQU.valueOrPQ(1.0,
                                             unitFrom=unitFrom,
                                             unitTo=unitTo,
                                             asPQU=False)
        except TypeError, err:
            if legend is None: legend = "name suppressed"
            raise TypeError("In plot2d.convertUnit, " + err.message +
                            ', error from PQU: ' + unitFrom + ' -> ' + unitTo +
                            ' for dataset ' + str(legend))
        except NameError, err:
            if legend is None: legend = "name suppressed"
            raise NameError("In plot2d.convertUnit, " + err.message +
                            ', error from PQU: ' + unitFrom + ' -> ' + unitTo +
                            ' for dataset ' + str(legend))
Пример #28
0
 def getColumnBounds(self,unit=None):
     """Get the bounds of the column.  If unit is specified, return the bounds in that unit."""
     if self.matrix.axes[-2].style=='link': return self.getRowBounds(unit)
     factor = 1
     if unit:
         factor = PQU.PQU(1, self.matrix.axes[-1].unit).getValueAs(unit)
     return( self.matrix.axes[-1].values[0] * factor, self.matrix.axes[-1].values[-1] * factor )
Пример #29
0
    def convertUnits(self, unitMap):

        unit, factor = PQUModule.convertUnits(self.unit, unitMap)
        if (abs(factor - 1) > (4 * sys.float_info.epsilon)):
            NotImplementedError(
                'Conversion of units for quantity of "%s" not implemented: from unit "" to unit "%s"'
                % (self.moniker, self.unit, unit))
Пример #30
0
def computeRI( xs, Ecut=None, domainMax=None, useCovariance=True, covariance=None ):
    '''
    Compute the resonance integral (RI):
    
    .. math::
        RI = \int_{Ec}^{\infty} \sigma(E) dE/E
        
    Where the lower cut-off is usually taken to be the Cadmium cut-off energy of 
    Ecut = 0.5 eV (see S. Mughabghab, Atlas of Neutron Resonances).  If the covariance
    is provided, the uncertainty on the resonance integral will be computed.
    
    :param PQU Ecut: lower bound of integration.
        Usually taken to be the Cadmium cut-off energy (default: '0.5 eV')
    :param PQU domainMax: an alternative upper energy integration cut-off used for cross checking against INTER mainly
    :param useCovariance: use this to override covarance usage
    :type useCovariance: bool
    :param covariance: covariance to use when computing uncertainty on the spectral average.
        If None (default: None), no uncertainty is computed.
    :type covariance: covariance instance or None
    :rtype: PQU
    
    '''
    check_is_cross_section( xs )
    if Ecut is None:
        return xs.integrateTwoFunctionsWithUncertainty( DEFAULTONEOVEREXYs, domainMax=domainMax, useCovariance=useCovariance, covariance=covariance, normalize=False )

    Ecut = PQU.PQU(Ecut).getValueAs( xs.domainUnit )
    # Construct an XYs instance that spans the same domain as self.
    # The y values are all 1/E and the x values are all E.
    def oneOverEFunc(E,*args): 
        if E < Ecut: return 0.0
        return 1.0/E
    Egrid=[1e-5,0.99999*Ecut]+list(equal_lethargy_bins(5000,domainMin=Ecut))
    oneOverE = function_to_XYs( oneOverEFunc, [], Egrid=Egrid )
    return xs.integrateTwoFunctionsWithUncertainty( oneOverE, domainMax=domainMax, useCovariance=useCovariance, covariance=covariance, normalize=False )