Ejemplo n.º 1
0
def bumat_search(element='94', bu_specific_file_name=file_name + burnup_adder):
    '''
    Finds values for the element given in bumat file provided
    Input: element where element is string number representing the atomic number
    Input: bu_file where the file is the current bumat file being analyzed
    Output: List of values associated with each of the isotopes of the elements given
    '''
    global divisions
    bu_file = st.read(bu_specific_file_name, 'bumat')
    iso_dict = {}
    cur_dict_list = []
    bu = bu_file.materials
    name_conv = list(bu)[-1].strip('1')
    divisions = int(list(bu)[0].strip(name_conv))
    for radius in range(len(list(bu))):
        counter = 0
        radial_name = name_conv + str(radius + 1)  # 1 is the innermost ring
        nuclides = bu.get(radial_name).get('nuclides')
        ele_key_list = list(nuclides)
        first = True
        for ele_list in ele_key_list:
            if ele_list.startswith(element):
                cur_iso_key = ele_key_list[counter]
                try:
                    cur_dict_list = iso_dict[cur_iso_key]
                except:
                    cur_dict_list = []
                cur_dict_list.append(nuclides[cur_iso_key])
                iso_dict[cur_iso_key] = cur_dict_list
                counter += 1
            else:
                counter += 1
    return iso_dict
Ejemplo n.º 2
0
def readDataFile(path, **kwargs):
    """
    Return a reader for the data file (test or example) file.

    All additional keyword arguments will be passed to
    :func:`serpentTools.read`.

    Parameters
    ----------
    path: str
        The name of the file without any additional directory
        information

    Returns
    -------
    object
        The reader that has processed this file and stored
        all the data

    Raises
    ------
    IOError:
        If the file for ``path`` does not exist

    See Also
    --------
    * :func:`serpentTools.read`
    """
    if not exists(path):
        # assume this is a example/test file contained in this project
        filePath = getFile(path)
    else:
        _warnDataFilePurpose()
        filePath = path
    return read(filePath, **kwargs)
Ejemplo n.º 3
0
def plots_fullcore():
    '''
    Plots full-core flux detectors:
    * Spectrum
    * Axial1, Axial2, Axial3,
    * Radial1, Radial2, Radial3
    '''

    # Plot spectrum
    data = st.read('serpent/fullcore_det1b1.m', reader='det')
    name = 'EnergyDetector'
    plot_spectrum(data, name, 'figures2/fullcore')

    A = 18/np.cos(np.pi/6)  # cm length of face of the hexagon
    Ah = 6. * (A * 18./2)  # Area of the hexagon
    V = Ah * (160 + 793 + 120)
    plot_detector(data, 'Axial1', 'figures2/fullcore', V)
    plot_detector(data, 'Axial2', 'figures2/fullcore', V)
    plot_detector(data, 'Axial3', 'figures2/fullcore', V)

    H = 793
    p = 2*np.pi  # = 360 deg
    plot_radial(data, 'Radial1', 'figures2/fullcore', p*H)

    H = 79.3
    p = np.pi/90  # = 2 deg
    plot_radial(data, 'Radial2', 'figures2/fullcore', p*H)

    H = 79.3
    p = np.pi/90  # = 2 deg
    plot_radial(data, 'Radial3', 'figures2/fullcore', p*H)
Ejemplo n.º 4
0
def test_multipleGcuNoBu(multipleGcuNoBu):
    r = serpentTools.read(multipleGcuNoBu)
    assert len(r.universes) == 3
    for key in r.universes:
        assert key.step == 0
        assert key.burnup == 0
        assert key.days == 0
Ejemplo n.º 5
0
    def __init__(self, leakageCorrection, transportCorrection, solver,
                 inputFilesAndTemps, outputFile):

        rc.__setitem__("serpentVersion", "2.1.30")

        self.leakageCorrection = leakageCorrection
        self.transportCorrection = transportCorrection
        self.solver = solver
        self.inputFilesAndTemps = inputFilesAndTemps
        self.outputFile = outputFile

        self.serpentFilesAndTemps = {}

        self.mesh = Mesh()

        self.prepareSerpentFiles()
        self.fileObject = open(self.outputFile, 'w')
        self.printHeader()

        for temp in self.serpentFilesAndTemps:
            res = serpentTools.read(self.serpentFilesAndTemps[temp])

            if temp == list(self.serpentFilesAndTemps.keys())[0]:
                self.createMaterials(res)

            self.readSerpentOutput(res, temp)

        self.calculateALMOSTCrossSections()
        self.printAlmostOutput()
Ejemplo n.º 6
0
def test_2132_nofilter(fake2132File):
    with serpentTools.settings.rc as rc:
        rc["serpentVersion"] = "2.1.32"
        reader = serpentTools.read(fake2132File)
    singleFima = numpy.array([0, 0, 1e25])
    assert "fima" in reader.resdata
    assert (reader.resdata["fima"] == singleFima).all(), reader.resdata["fima"]
    assert not reader.resdata["burnRandomizeData"].any()
Ejemplo n.º 7
0
def test_2132_filterburnup(fake2132File):
    with serpentTools.settings.rc as rc:
        rc["serpentVersion"] = "2.1.32"
        rc["xs.variableGroups"] = ["burnup-coeff", "eig"]
        reader = serpentTools.read(fake2132File)
    assert "fima" in reader.resdata
    assert "burnDays" in reader.resdata
    assert "absKeff" in reader.resdata
    assert "pop" not in reader.metadata
 def _scrape(self, resfile):
     """Read multiplication factor from resfile"""
     try:
         reader = read(resfile, 'results')
         kinf = reader.resdata['absKeff'][0:2]
     except Exception as ee:
         move(resfile, self._pwd)
         raise ee
     return kinf
Ejemplo n.º 9
0
def plots_standardcolumn():
    """
    Plots standard-column flux detector
    """

    data = st.read('standard-column_det0.m', reader='det')
    A = 18/np.cos(np.pi/6)  # cm length of face of the hexagon
    Ah = 6. * (A * 18./2)  # Area of the hexagon
    V = Ah * (160 + 793 + 120)
    plot_detector(data, 'Axial', V)
Ejemplo n.º 10
0
def get_keff_vs_bu(filename):
    '''
    '''
    data = st.read(filename + '_res.m')
    keff = data.resdata['impKeff'][:, 0]
    days = data.resdata['burnDays'][:, 0]

    # plt.figure()
    # plt.plot(days, keff, marker='o')
    # plt.xlabel('EFFPD')
    # plt.ylabel('Keff')
    # plt.savefig('keff-vs-bu', dpi=300, bbox_inches="tight")
    # plt.close()

    return keff[-1]
Ejemplo n.º 11
0
    def get_power(self, filename, detectorname):
        data = st.read(filename, reader='det')
        det = data.detectors[detectorname]

        self.power = []
        # 1
        self.power.append(det.tallies[0, 7])
        self.power.append(det.tallies[0, 8])
        # 2
        self.power.append(det.tallies[1, 5])
        self.power.append(det.tallies[1, 6])
        self.power.append(det.tallies[1, 8])
        self.power.append(det.tallies[1, 9])
        # 3
        self.power.append(det.tallies[2, 6])
        self.power.append(det.tallies[2, 7])
        self.power.append(det.tallies[2, 9])
        self.power.append(det.tallies[2, 10])
        # 4
        self.power.append(det.tallies[3, 5])
        self.power.append(det.tallies[3, 7])
        self.power.append(det.tallies[3, 8])
        self.power.append(det.tallies[3, 10])
        # 5
        self.power.append(det.tallies[4, 5])
        self.power.append(det.tallies[4, 6])
        self.power.append(det.tallies[4, 8])
        self.power.append(det.tallies[4, 9])
        # 6
        self.power.append(det.tallies[5, 6])
        self.power.append(det.tallies[5, 7])
        self.power.append(det.tallies[5, 9])
        # 7
        self.power.append(det.tallies[6, 5])
        self.power.append(det.tallies[6, 7])
        self.power.append(det.tallies[6, 8])
        # 8
        self.power.append(det.tallies[7, 5])
        self.power.append(det.tallies[7, 6])
        self.power.append(det.tallies[7, 8])
        # 9
        self.power.append(det.tallies[8, 6])
        self.power.append(det.tallies[8, 7])
        # 10
        self.power.append(det.tallies[9, 5])
        # 11
        #
        self.power = np.array(self.power)
Ejemplo n.º 12
0
def ReadPdistrHistSerpent(file, FullCoreLayout):
    SerpentLayout = GetSerpentLayout(FullCoreLayout, 2)
    # Read that Serpent history file
    hist = serpentTools.read(file)
    # For a detector (here -80), the results are grouped in three columns that
    # provide (1) the cycle-wise value,
    #         (2) the cumulative mean and
    #         (3) the corresponding relative statistical error.
    # Cf. http://serpent.vtt.fi/mediawiki/index.php/Description_of_output_files#History_output
    # Only the first is kept here.
    cycle = hist['det-80'][:, 0::3]
    # Among that, only the total deposited energy is kept
    cycle = cycle[:, 0::3]
    # Among that, only the central layer (the active core) is kept ; top and
    # bottom layers are splitted out
    cycle = np.split(cycle, 3, axis=1)[1]
    # Raise exception if inactive generations are being used. One (1) inactive
    # generation is the minimum permitted by Serpent and therefore the only
    # one we accept.
    if np.isclose(0.0, np.sum(cycle[1]), atol=1e-20):
        raise Exception('The convergence plot cannot be achieved since ' +
                        'inactive generations have been detected: ' +
                        '*set pop [x] [y] 1* should be used in Serpent.')
    # Reshaping into nbatch*size*size
    nbatch = np.shape(cycle)[0]
    nxysize = int(math.sqrt(np.shape(cycle)[1]))
    cycle.shape = (nbatch, nxysize, nxysize)
    # Prepare output
    out = np.zeros((nbatch, np.count_nonzero(FullCoreLayout)))
    for ibatch in range(1, nbatch):
        # Filter out the reflector to get only the response of the core
        thiscycle = np.where(SerpentLayout == 0, 0, cycle[ibatch])
        # Normalize the core power
        nassembly = np.count_nonzero(FullCoreLayout)
        thiscycle = nassembly * thiscycle / np.sum(thiscycle)
        # Remove columns and rows full of zeroes
        thiscycle = Deploy2D(thiscycle[np.nonzero(thiscycle)], FullCoreLayout)
        # The input is symmetrical by eighth, so we can symmetrize (a fold
        # followed by an unfold) in order to increase the statistical strength
        thiscycle = UnfoldEighth(FoldEighth(thiscycle))
        # Keep all the (non-zero) powers of the full core
        out[ibatch] = thiscycle[np.nonzero(thiscycle)]
        # ... except the first (empty) one (it is the only inactive generation)
    return out[1:]
Ejemplo n.º 13
0
    def get_calculated_values(self) -> bool:
        'Fill k and cr for lattice if calculated'
        if os.path.exists(self.deck_path+'/done.out') and \
                os.path.getsize(self.deck_path+'/done.out') > 30:
            pass
        else:  # Calculation not done yet
            return False

        results = serpentTools.read(self.deck_path + '/' + self.deck_name +
                                    "_res.m")
        self.k = results.resdata["anaKeff"][0]
        self.kerr = results.resdata["anaKeff"][1]
        self.cr = results.resdata["conversionRatio"][0]
        self.crerr = results.resdata["conversionRatio"][1]

        if my_debug:
            print("[DEBUG Lat] ---> k = {self.k}, CR = {self.cr}".format(
                **locals()))
        return True
Ejemplo n.º 14
0
    def get_power(self, filename, detectorname):
        data = st.read(filename, reader='det')
        det = data.detectors[detectorname]

        self.power = []
        # 1
        # 2
        # 3
        # 4
        self.power.append(det.tallies[3, 2])
        # 5
        self.power.append(det.tallies[4, 2])
        self.power.append(det.tallies[4, 3])
        # 6
        self.power.append(det.tallies[5, 1])
        self.power.append(det.tallies[5, 3])
        # 7
        self.power.append(det.tallies[6, 1])
        self.power.append(det.tallies[6, 2])
        # 8
        self.power.append(det.tallies[7, 0])
        self.power.append(det.tallies[7, 2])
        self.power.append(det.tallies[7, 3])
        self.power.append(det.tallies[7, 5])
        self.power.append(det.tallies[7, 6])
        # 9
        self.power.append(det.tallies[8, 0])
        self.power.append(det.tallies[8, 1])
        self.power.append(det.tallies[8, 3])
        self.power.append(det.tallies[8, 4])
        self.power.append(det.tallies[8, 6])
        self.power.append(det.tallies[8, 7])
        # 10
        self.power.append(det.tallies[9, 1])
        self.power.append(det.tallies[9, 2])
        self.power.append(det.tallies[9, 4])
        self.power.append(det.tallies[9, 5])
        # 11
        self.power.append(det.tallies[10, 2])
        self.power.append(det.tallies[10, 3])
        #
        self.power = np.array(self.power)
Ejemplo n.º 15
0
def main():
    # Serpent results
    # Add legend to geometry figure
    # standard()

    # Plot flux
    data = st.read('standard-column_det0.m', reader='det')
    save = 'standard-column-detector'
    A = 18 / np.cos(np.pi / 6)  # cm length of face of the hexagon
    Ah = 6. * (A * 18. / 2)  # Area of the hexagon
    V = Ah * (160 + 793 + 120)
    # plot_serpent_axial(data, 'Axial', save, V)
    plot_serpent_axial_werrbars(data, 'Axial', save, V)

    # Moltres results
    # Add legend to geometry figure
    # moltres_assembly_legend()

    # Plot flux
    file = '3D-assembly-h**o-eig_fuel_0002.csv'
    save = 'standard-column-h**o'
    plotcsv_frommoose_groups(file, save, G=2, dire='z')
Ejemplo n.º 16
0
def ReadPdistrSerpent(file, FullCoreLayout, msg):
    # Retrieve Serpent detector output
    det = serpentTools.read(file)
    # Total energy deposition, see
    # http://serpent.vtt.fi/mediawiki/index.php/ENDF_reaction_MT%27s_and_macroscopic_reaction_numbers
    reaction = '-80'
    power = det.detectors[reaction].tallies
    if reaction == '-80':
        power = power[0]
    # Number of assembly-sized tallies outside the core, on each side
    outside = 2
    # Produce the core layout corresponding to tallies
    hstack = np.zeros((len(FullCoreLayout), outside))
    TalliesLayout = np.hstack([hstack, FullCoreLayout, hstack])
    vstack = np.zeros((outside, len(FullCoreLayout) + 2 * outside))
    TalliesLayout = np.vstack([vstack, TalliesLayout, vstack])
    # Compute fraction of power delivered in the reflector
    corepower = np.where(TalliesLayout == 0, 0, power[1])
    radialreflpower = np.where(TalliesLayout == 1, 0, power[1])
    botreflpower = np.sum(power[0])
    topreflpower = np.sum(power[2])
    reflpower = np.sum(radialreflpower) + botreflpower + topreflpower
    print('Fraction of the power Serpent delivers in the reflector = ' +
          str(np.sum(reflpower) / np.sum(power)) + ' (' + msg + ')')
    # Ignore reflector power and renormalize core power
    corepower = corepower / np.sum(corepower) * np.count_nonzero(corepower)
    # The input is symmetrical by eighth, so we can symmetrize (a fold followed
    # by an unfold) in order to increase the statistical strength
    symcorepower = UnfoldEighth(FoldEighth(corepower))
    # Estimate the uncertainty
    sym = symcorepower
    unsym = corepower
    reldif = unsym[np.nonzero(unsym)] / sym[np.nonzero(sym)] - 1
    print("min, max (%)=" + str(np.min(reldif) * 100) + ", " +
          str(np.max(reldif) * 100))
    # Return powers, removing all of them equal to zero
    return symcorepower[np.nonzero(symcorepower)]
Ejemplo n.º 17
0
import matplotlib.pyplot as plt
from matplotlib.cbook import get_sample_data
import serpentTools as st
import pathmagic
from auxiliary import plot_serpent_axial_collapse


if __name__ == "__main__":

    A = 18/np.cos(np.pi/6)  # cm length of face of the hexagon
    Ah = 6. * (A * 18./2)   # Area of the hexagon
    V = Ah * (160 + 793 + 120)
    lim = [4, 16, 26]
    name = 'Axial'

    data = st.read('standard-column-noLBP-26G_det1b1.m', reader='det')
    save = 'serpent26G-noLBP-600-collapse'
    plot_serpent_axial_collapse(data, name, save, lim, V)

    data = st.read('standard-column-noLBP-26G_det1b3.m', reader='det')
    save = 'serpent26G-noLBP-1200-collapse'
    plot_serpent_axial_collapse(data, name, save, lim, V)

    data = st.read('standard-column-LBP-26G_det1b1.m', reader='det')
    save = 'serpent26G-LBP-600-collapse'
    plot_serpent_axial_collapse(data, name, save, lim, V)

    data = st.read('standard-column-LBP-26G_det1b3.m', reader='det')
    save = 'serpent26G-LBP-1200-collapse'
    plot_serpent_axial_collapse(data, name, save, lim, V)
from numpy import empty
from itertools import product
import serpentTools
d = serpentTools.read('det_det0.m')['xymesh']

# Get data

xgrids = d.grids['X']
ygrids = d.grids['Y']

nx = xgrids.shape[0]
ny = ygrids.shape[0]

data = empty((nx * ny, 4))
data[:, 2].fill(0)

for ix, (yi, xi) in enumerate(product(range(ny), range(nx))):
    data[ix, 0] = xgrids[xi, 2]
    data[ix, 1] = ygrids[yi, 2]
    data[ix, 3] = d.tallies[yi, xi]

with open('det.csv', 'w') as out:
    out.write("X Axis,Y Axis,Z Axis,Flux\n")
    for row in data:
        out.write(','.join(map(str, row)) + "\n")
Ejemplo n.º 19
0
                strData = materials[currentMat][data]
                strData = ' '.join([str(dat)
                                    for dat in strData]) if isinstance(
                                        strData, np.ndarray) else str(strData)
                fh.write(str(temp) + ' ' + strData)
                fh.write('\n')
    return None


if __name__ == '__main__':
    '''
    Cross-sections from 'fullcore3G-LBP.coe' - 9 176 (fuel).
    '''

    # get data from .coe
    coeList = sT.read('fullcore3G-LBP.coe')

    # user defined parameters
    mat = 'fuel'
    item = 'fuel0'
    uni = '9'

    getdata = [
        'Flx', 'Tot', 'Sp0', 'Sp2', 'Fiss', 'Nsf', 'Kappa', 'Sp1', 'Sp3',
        'Invv', 'Chit', 'Chip', 'Chid', 'Diffcoef', 'Abs'
    ]
    goodMap = dict([(thing, 'inf' + thing) for thing in getdata])

    constants = {}
    for data in getdata:
        constants[data.upper()] = coeList.branches[item].universes[
Ejemplo n.º 20
0
                cur_iso_key = ele_key_list[counter]
                try:
                    cur_dict_list = iso_dict[cur_iso_key]
                except:
                    cur_dict_list = []
                cur_dict_list.append(nuclides[cur_iso_key])
                iso_dict[cur_iso_key] = cur_dict_list
                counter += 1
            else:
                counter += 1
    return iso_dict


##### File Reading
try:
    depf = st.read(file_name + depletion_adder, 'dep')
    depletion_file = True
except:
    depletion_file = False
    print('No depletion file found.')
try:
    resf = st.read(file_name + results_adder, 'results')
    result_file = True
except:
    result_file = False
    print('No result file found.')

if depletion_file:
    ##### Defining Materials
    dep_fuel = depf.materials['uranium']
Ejemplo n.º 21
0
def test_similarDetectors(similarDetectorFile):
    reader = serpentTools.read(similarDetectorFile)

    assert set(reader.detectors) == {"spectrum", "spectrumA", "spectrumB"}
    assert isinstance(reader["spectrumA"], detectors.HexagonalDetector)
Ejemplo n.º 22
0
SerpentLayout = GetSerpentLayout(FullCoreLayout, 2)
for file in glob.glob('../Serpent/BatchHist/Tihange*ppm_*.sss2_his0.m'):
    print(file)
    # Identify the file we're about to read
    basename = file.split('/')[-1].split('.')[0]
    cbor = int(re.sub("[^0-9]", "", basename.split('_')[0]))
    if cbor == 1206:
        controlrod = 'ARO'
    elif cbor == 1084:
        controlrod = 'D'
    elif cbor == 960:
        controlrod = 'CD'
    else:
        raise Exception(cbor + ' unknown.')
    # Read that Serpent history file
    hist = serpentTools.read(file)
    # For a detector (here -80), the results are grouped in three columns that
    # provide (1) the cycle-wise value,
    #         (2) the cumulative mean and
    #         (3) the corresponding relative statistical error.
    # Cf. http://serpent.vtt.fi/mediawiki/index.php/Description_of_output_files#History_output
    # Only the first is kept here.
    cycle = hist['det-80'][:, 0::3]
    # Among that, only the total deposited energy is kept
    cycle = cycle[:, 0::3]
    # Among that, only the central layer (the active core) is kept ; top and
    # bottom layers are splitted out
    cycle = np.split(cycle, 3, axis=1)[1]
    # Raise exception if inactive generations are being used. One (1) inactive
    # generation is the minimum permitted by Serpent and therefore the only
    # one we accept.
Ejemplo n.º 23
0
    print("Submitting File ",i)
        
  
print("-----Files Submitted!-----")


for i,enrichment in enumerate(enrichments):
    
    prefix="godiva"
    prefix+="{:0>2d}".format(i)
    file_in=prefix+".inp"
    file_out=prefix+".out"
    resname=file_in+"_res.m"
    
    while resname not in glob.glob("*_res.m"):
        time.sleep(10)
        print("Files Still Running, Waiting Ten Seconds")
        
    results=serpentTools.read(resname)
    keff_sigma=results.resdata['absKeff'] #keff with sigma
    keff=results.resdata['absKeff'][0] #keff
    keff_list.append(keff)
     
    

    with open("godiva_data.csv","a+") as datafile:
        datafile.write("{},{},{},{}\n".format(file_in,enrichment,radius,keff))   

print("-----Done!-----")

Ejemplo n.º 24
0
# Open results file
results = openmc.deplete.ResultsList.from_hdf5("openmc/depletion_results.h5")

# Obtain K_eff as a function of time
time, keff = results.get_eigenvalue()

# Obtain concentration as a function of time
time, atoms = results.get_atoms('1', nuc)
radius = 0.39218
volume = pi * radius**2
openmc_conc = atoms * 1e-24 / volume  # [atoms] [cm^2/b] / [cm^2] = atom/b

# Read Serpent results --------------------------------------------------------

sdata = serpentTools.read('serpent/serpent_input_dep.m')
fuel = sdata['fuel']
serpent_days = fuel.days
serpent_conc = fuel.getValues(
    'days', 'adens', names=f'{ATOMIC_SYMBOL[z]}{a}{"m" if m else ""}')[0]

# Plot results ----------------------------------------------------------------

fig, ax = plt.subplots()
day = 24 * 60 * 60
ax.plot(time / day, openmc_conc, 'kx', label=f"{nuc} (OpenMC)")
ax.plot(serpent_days, serpent_conc, 'b-', label=f"{nuc} (Serpent)")
ax.set_xlabel("Time (days)")
ax.set_ylabel("Atom/barn")
ax.legend()
ax.grid(True, which='both')
Ejemplo n.º 25
0
    plt.ylabel('Y [cm]')
    plt.savefig(save, dpi=300, bbox_inches="tight")
    plt.close()


if __name__ == "__main__":

    lim26 = [4, 16, 26]  # collapse from 26 to 3
    A = 18/np.cos(np.pi/6)  # cm length of face of the hexagon
    Ah = 6. * (A * 18./2)   # Area of the hexagon
    V = Ah * (160 + 793 + 120)
    H = 79.3
    p = np.pi/180 * 2  # = 2 deg

    # plot axial and radial flux at 600K
    data = st.read('oecd-fullcore-600_det1b1.m', reader='det')
    save = 'serpent26G-600-collapse-Axial1'
    plot_serpent_axial_collapse(data, 'Axial1', save, lim26, V, 'Z')
    save = 'serpent26G-600-collapse-Radial'
    plot_serpent_radial_collapse(data, 'Radial3', save, lim26, p*H)

    # plot serpent radial power distribution 600K
    det = data.detectors['power']
    power = np.zeros(11)
    power[0] = det.tallies[0, 3]
    power[1] = det.tallies[0, 4]
    power[2] = det.tallies[1, 2]
    power[3] = det.tallies[1, 3]
    power[4] = det.tallies[1, 4]
    power[5] = det.tallies[2, 1]
    power[6] = det.tallies[2, 2]
Ejemplo n.º 26
0
def makePropertiesDir(outdir,
                      filebase,
                      mapFile,
                      secbranchFile,
                      unimapFile,
                      serp1=False,
                      fromMain=False):
    """ Takes in a mapping from branch names to material temperatures,
    then makes a properties directory.
    Serp1 means that the group transfer matrix is transposed."""

    if serp1:
        raise NotImplementedError("C'mon, just get serpent 2!")

    if not os.path.isdir(outdir):
        os.mkdir(outdir)

    # the constants moltres looks for:
    goodStuff = [
        'BETA_EFF', 'Chit', 'Chid', 'lambda', 'Diffcoef', 'Kappa', 'Sp0',
        'Nsf', 'Invv', 'Remxs', 'Fiss', 'Nubar', 'Flx'
    ]
    goodMap = dict([(thing, 'inf' + thing) for thing in goodStuff])
    goodMap['BETA_EFF'] = 'betaEff'
    goodMap['lambda'] = 'lambda'

    # map material names to universe names from serpent
    with open(unimapFile) as fh:
        uniMap = []
        for line in fh:
            uniMap.append(tuple(line.split()))
    # this now maps material names to serpent universes
    uniMap = dict(uniMap)

    # list of material names
    inmats = list(uniMap.keys())

    print("Making properties for materials:")
    print(inmats)
    coeList = dict([(mat, sT.read(mat + '.coe')) for mat in inmats])

    # secondary branch burnup steps
    secBranch = []
    with open(secbranchFile) as bf:
        for line in bf:
            secBranch.append(line)

    # primary branch to temp mapping
    branch2TempMapping = open(mapFile)

    # Check if calculation uses 6 neutron precursor groups.
    # This prevents writing of excess zeros. Check if any
    # entries in the 7th and 8th group precursor positions
    # are nonzero, if so, use 8 groups.
    use8Groups = False
    for line in branch2TempMapping:
        item, temp = tuple(line.split())
        for mat in inmats:
            if mat in item:
                currentMat = mat
                break
        if secBranch:
            for branch in secBranch:
                strData = coeList[currentMat].branches[item, branch].universes[
                    int(uniMap[currentMat]), 0, 0].gc[goodMap['BETA_EFF']]
                strData = strData[1:9]
                if np.any(strData[-2:] != 0.0):
                    use8Groups = True
        else:
            strData = coeList[currentMat].branches[item].universes[
                int(uniMap[currentMat]), 0, 0].gc[goodMap['BETA_EFF']]
            strData = strData[1:9]
            if np.any(strData[-2:] != 0.0):
                use8Groups = True

    # Now loop through a second time
    branch2TempMapping.close()
    branch2TempMapping = open(mapFile)

    for line in branch2TempMapping:

        item, temp = tuple(line.split())
        for mat in inmats:
            if mat in item:
                currentMat = mat
                break
        else:
            print('Considered materials: {}'.format(inmats))
            raise Exception(
                'Couldnt find a material corresponding to branch {}'.format(
                    item))

        try:
            if secBranch:
                for branch in secBranch:
                    for coefficient in goodStuff:
                        with open(
                                outdir + '/' + filebase + '_' + currentMat +
                                '_' + branch + '_' + coefficient.upper() +
                                '.txt', 'a') as fh:
                            if coefficient == 'lambda' or \
                                    coefficient == 'BETA_EFF':
                                strData = coeList[currentMat].branches[
                                    item, branch].universes[
                                        int(uniMap[currentMat]), 0,
                                        0].gc[goodMap[coefficient]]
                                # some additional formatting is needed here
                                strData = strData[1:9]

                                # Cut off group 7 and 8 precursor params in 6
                                # group calcs
                                if not use8Groups:
                                    strData = strData[0:6]
                            else:
                                strData = coeList[currentMat].branches[
                                    item, branch].universes[
                                        int(uniMap[currentMat]), 0,
                                        0].infExp[goodMap[coefficient]]
                            strData = ' '.join(
                                [str(dat) for dat in strData]) if isinstance(
                                    strData, np.ndarray) else strData
                            fh.write(str(temp) + ' ' + strData)
                            fh.write('\n')

            else:
                for coefficient in goodStuff:
                    with open(
                            outdir + '/' + filebase + '_' + currentMat + '_' +
                            coefficient.upper() + '.txt', 'a') as fh:
                        if coefficient == 'lambda' or \
                                coefficient == 'BETA_EFF':
                            strData = coeList[currentMat].branches[
                                item].universes[int(uniMap[currentMat]), 0,
                                                0].gc[goodMap[coefficient]]
                            # some additional formatting is needed here
                            strData = strData[1:9]

                            # Cut off group 7 and 8 precursor params in 6
                            # group calcs
                            if not use8Groups:
                                strData = strData[0:6]
                        else:
                            strData = coeList[currentMat].branches[
                                item].universes[int(uniMap[currentMat]), 0,
                                                0].infExp[goodMap[coefficient]]
                        strData = ' '.join(
                            [str(dat) for dat in strData]) if isinstance(
                                strData, np.ndarray) else strData
                        fh.write(str(temp) + ' ' + strData)
                        fh.write('\n')

        except KeyError:
            print(secBranch)
            raise Exception('Check your mapping and secondary branch files.')
Ejemplo n.º 27
0
from tabulate import tabulate
from uncertainties import unumpy as unp

# Read OpenMC results ---------------------------------------------------------

# Open results file
results = openmc.deplete.ResultsList.from_hdf5("openmc/depletion_results.h5")

# Obtain K_eff as a function of time
time, k = results.get_eigenvalue()
openmc_keff = unp.uarray(k[:, 0], k[:, 1])
days = time / (24 * 60 * 60)

# Read Serpent results --------------------------------------------------------

res = serpentTools.read('serpent/serpent_input_res.m')
serpent_days = res.resdata['burnDays'][:, 0]
serpent_keff = unp.uarray(res.resdata['absKeff'][:, 0],
                          res.resdata['absKeff'][:, 1])

# Plot results ----------------------------------------------------------------

# Show tabulation
data = np.vstack((days, serpent_keff, openmc_keff)).T
print(tabulate(data, headers=['Days', 'Serpent', 'OpenMC']))

diff = 1e5 * (openmc_keff - serpent_keff)
fig, ax = plt.subplots()
ax.errorbar(days,
            unp.nominal_values(diff),
            2 * unp.std_devs(diff),
Ejemplo n.º 28
0
    def read(self, readable, filetype):
        """Read an output file and return the corresponding reader

        Wrapper around ``serpentTools.read`` with some extra sugar.
        First, and most plainly, if no options are pre-defined
        in :attr:`options` for a given file type, then nothing fancy
        is done.  The file is read and the resulting Reader is
        returned. Otherwise, the settings are passed to
        ``serpentTools`` and reverted after the file is read.

        Parameters
        ----------
        readable : str
            Name of the file to be read. There should be a
            corresponding ``serpentTools`` reader that can handle
            this file.
        filetype : str
            Type of the file, e.g. ``"results"``. While this is
            not necessary on the ``serpentTools`` side, it is used
            to pull pre-defined options to improve parsing. This
            is especially useful for the result file as only
            global multiplication factor and locally homogenized
            cross sections will be read.

        Returns
        -------
        Reader
            serpentTools reader that processed this file

        Warns
        -----
        SyntaxWarning
            Will be raised if setting any settings are unable to be
            passed into the settings manager. The file will be read
            regardless, but a warning will be raised

        """
        opts = self.options.get(filetype)
        if opts is None:
            return serpentTools.read(readable, filetype)

        valuefails = {}
        unexpectedfails = {}

        with serpentTools.settings.rc as temp:
            for k, v in opts.items():
                try:
                    temp[k] = v
                except (KeyError, TypeError):
                    valuefails[k] = v
                except Exception:
                    unexpectedfails[k] = v
            serpentFile = serpentTools.read(readable, filetype)

        if valuefails:
            self._warnOptions(valuefails, "Bad settings and/or values")
        if unexpectedfails:
            self._warnOptions(
                unexpectedfails,
                "Unexpected failure with rc settings. File parsing still successful",
            )

        return serpentFile
Ejemplo n.º 29
0
    def get_power(self, filename, detectorname):
        data = st.read(filename, reader='det')
        det = data.detectors[detectorname]

        self.power = []
        #
        self.power.append(det.tallies[0, 7])
        self.power.append(det.tallies[0, 8])
        #
        self.power.append(det.tallies[1, 5])
        self.power.append(det.tallies[1, 6])
        self.power.append(det.tallies[1, 8])
        self.power.append(det.tallies[1, 9])
        #
        self.power.append(det.tallies[2, 3])
        self.power.append(det.tallies[2, 4])
        self.power.append(det.tallies[2, 6])
        self.power.append(det.tallies[2, 7])
        self.power.append(det.tallies[2, 9])
        self.power.append(det.tallies[2, 10])
        #
        self.power.append(det.tallies[3, 2])
        self.power.append(det.tallies[3, 4])
        self.power.append(det.tallies[3, 5])
        self.power.append(det.tallies[3, 7])
        self.power.append(det.tallies[3, 8])
        self.power.append(det.tallies[3, 10])
        #
        self.power.append(det.tallies[4, 2])
        self.power.append(det.tallies[4, 3])
        self.power.append(det.tallies[4, 5])
        self.power.append(det.tallies[4, 6])
        self.power.append(det.tallies[4, 8])
        self.power.append(det.tallies[4, 9])
        #
        self.power.append(det.tallies[5, 1])
        self.power.append(det.tallies[5, 3])
        self.power.append(det.tallies[5, 4])
        self.power.append(det.tallies[5, 6])
        self.power.append(det.tallies[5, 7])
        self.power.append(det.tallies[5, 9])
        #
        self.power.append(det.tallies[6, 1])
        self.power.append(det.tallies[6, 2])
        self.power.append(det.tallies[6, 4])
        self.power.append(det.tallies[6, 5])
        self.power.append(det.tallies[6, 7])
        self.power.append(det.tallies[6, 8])
        #
        self.power.append(det.tallies[7, 0])
        self.power.append(det.tallies[7, 2])
        self.power.append(det.tallies[7, 3])
        self.power.append(det.tallies[7, 5])
        self.power.append(det.tallies[7, 6])
        self.power.append(det.tallies[7, 8])
        #
        self.power.append(det.tallies[8, 0])
        self.power.append(det.tallies[8, 1])
        self.power.append(det.tallies[8, 3])
        self.power.append(det.tallies[8, 4])
        self.power.append(det.tallies[8, 6])
        self.power.append(det.tallies[8, 7])
        #
        self.power.append(det.tallies[9, 1])
        self.power.append(det.tallies[9, 2])
        self.power.append(det.tallies[9, 4])
        self.power.append(det.tallies[9, 5])
        #
        self.power.append(det.tallies[10, 2])
        self.power.append(det.tallies[10, 3])
        self.power = np.array(self.power)
Ejemplo n.º 30
0
#!/usr/bin/env python3
#
# Read & Plot flux along X direction, Goofing with Godiva mk2
# Ondrej Chvala, [email protected]
# 2019-07-22

import matplotlib.pyplot as plt
import numpy as np
import serpentTools

verbose: bool = True

# Read in data
godivafile = serpentTools.read("godiva.inp_det0.m")
mydet = godivafile['mydet']

# Fill simple arrays for convenient plotting
xdata = mydet.grids['X'][:, 2]  # centers of X bins [cm]
thrmflux = mydet.slice({'energy': 0})  # THERMAL FLUX
thrmfluxe = mydet.slice({'energy': 0}, 'errors')
thrmfluxe *= thrmflux  # relative -> absolute errors
epitflux = mydet.slice({'energy': 1})  # EPITHERMAL FLUX
epitfluxe = mydet.slice({'energy': 1}, 'errors')
epitfluxe *= epitflux  # relative -> absolute errors
fastflux = mydet.slice({'energy': 2})  # FAST FLUX
fastfluxe = mydet.slice({'energy': 2}, 'errors')
fastfluxe *= fastflux  # relative -> absolute errors

if verbose:
    print("XDATA: ", xdata)
    print("FAST FLUX: ", fastflux)