示例#1
0
# this creates a neutron distribution with the shape of a tokamak plasma
my_plasma = Plasma(elongation=2.9,
                   minor_radius=1.118,
                   major_radius=1.9,
                   triangularity=0.55)
# there are other parameters that can be set for the plasma, but we can use the defaults for now
my_plasma.export_plasma_source('my_custom_plasma_source.so')
# sets the source poition, direction and energy with predefined plasma parameters (see source_sampling.cpp)
source.library = './my_custom_plasma_source.so'
sett.source = source

# Run OpenMC!
model = openmc.model.Model(geom, mats, sett)
statepoint_filename = model.run()

sp = openmc.StatePoint(statepoint_filename)

print('direction of first neutron =',
      sp.source['u'][0])  # these neutrons are all created

fig_directions = go.Figure()

# plot the neutron birth locations and trajectory
fig_directions.add_trace({
    'type': 'cone',
    'cauto': False,
    'x': sp.source['r']['x'],
    'y': sp.source['r']['y'],
    'z': sp.source['r']['z'],
    'u': sp.source['u']['x'],
    'v': sp.source['u']['y'],
示例#2
0
import matplotlib.pyplot as plt
import numpy as np

import openmc

# Load the statepoint file
sp = openmc.StatePoint('statepoint.20.h5')

tally = sp.get_tally(scores=['flux'])
print(tally)

#tally.sum

#standard and mean deviation
print(tally)
(tally.mean, tally.std_dev)

flux = tally.get_slice(scores=['flux'])
thermal_flux = flux.get_slice(filters=[openmc.EnergyFilter],
                              filter_bins=[((0., 4.), )])

fission = tally.get_slice(scores=['fission'])
thermal_fission = fission.get_slice(filters=[openmc.EnergyFilter],
                                    filter_bins=[((0., 4.), )])

nu_fission = tally.get_slice(scores=['nu-fission'])

thermal_flux.std_dev.shape = (100, 100)
thermal_flux.mean.shape = (100, 100)

thermal_fission.std_dev.shape = (100, 100)
# added a cell tally for tritium production
cell_filter = openmc.CellFilter(breeder_blanket_cell)
tbr_tally = openmc.Tally(name='TBR')
tbr_tally.filters = [cell_filter]
tbr_tally.scores = [
    '(n,Xt)'
]  # MT 205 is the (n,Xt) reaction where X is a wildcard, if MT 105 or (n,t) then some tritium production will be missed, for example (n,nt) which happens in Li7 would be missed
tallies.append(tbr_tally)

# Run OpenMC!
model = openmc.model.Model(geom, mats, sett, tallies)
model.run()

# open the results file
sp = openmc.StatePoint('statepoint.' + str(batches) + '.h5')

# access the tally using pandas dataframes
tbr_tally = sp.get_tally(name='TBR')
df = tbr_tally.get_pandas_dataframe()

tbr_tally_result = df['mean'].sum()
tbr_tally_std_dev = df['std. dev.'].sum()

# print results
print('The tritium breeding ratio was found, TBR = ', tbr_tally_result)
print('error on the tbr tally is ', tbr_tally_std_dev)

# output results to json file
json_output = {'TBR': tbr_tally_result, 'TBR_std_dev': tbr_tally_std_dev}
with open('simulation_results.json', 'w') as file_object:
def get_neutron_spectrum_from_plasma(plasma_temperature=14080000.0):

    # MATERIALS (there are none in this model)

    mats = openmc.Materials([])

    # GEOMETRY

    # surfaces
    inner_surface = openmc.Sphere(r=100)
    outer_surface = openmc.Sphere(r=101, boundary_type='vacuum')

    # cells
    inner_cell = openmc.Cell(region=-inner_surface)
    # this is filled with a void / vauum by default

    outer_cell = openmc.Cell(region=+inner_surface & -outer_surface)
    # this is filled with a void / vauum by default

    universe = openmc.Universe(cells=[inner_cell, outer_cell])
    geom = openmc.Geometry(universe)

    # SIMULATION SETTINGS

    # Instantiate a Settings object
    sett = openmc.Settings()
    sett.batches = 20
    sett.inactive = 0  # the default is 10, which would be wasted computing for us
    sett.particles = 500000
    sett.run_mode = 'fixed source'

    # Create a DT point source
    source = openmc.Source()
    source.space = openmc.stats.Point((0, 0, 0))
    source.angle = openmc.stats.Isotropic()
    source.energy = openmc.stats.Muir(kt=plasma_temperature)
    sett.source = source

    # setup the  filters for the tallies
    neutron_particle_filter = openmc.ParticleFilter(['neutron'])
    surface_filter = openmc.SurfaceFilter(
        inner_surface)  # detects particles across a surface

    energy_filter = openmc.EnergyFilter(energy_bins)
    spectra_tally = openmc.Tally(name='energy_spectra')
    spectra_tally.scores = ['current']
    spectra_tally.filters = [
        surface_filter, neutron_particle_filter, energy_filter
    ]

    tallies = openmc.Tallies()
    tallies.append(spectra_tally)

    # combine all the required parts to make a model
    model = openmc.model.Model(geom, mats, sett, tallies)
    # Run OpenMC!
    results_filename = model.run()

    # open the results file
    results = openmc.StatePoint(results_filename)

    #extracts the tally values from the simulation results
    surface_tally = results.get_tally(name='energy_spectra')
    surface_tally = surface_tally.get_pandas_dataframe()
    surface_tally_values = surface_tally['mean']

    return surface_tally_values
示例#5
0
###############################################################################

import openmc
import sys
sys.path.insert(1, '../../scripts/')
from phase1a_constants import *
from openmc_analysis import *

###############################################################################
#                                  Run
###############################################################################
case = 'p1a_2ah'
keff = 1.41823
keff_unc = 0.00003

sp = openmc.StatePoint('h5files/3pcm/fhr_p1a_c2ah_3pcm_statepoint.500.h5')
beta_b(sp, case)
# doppler
print(
    reactivity_coefficient_b(keff_og=keff,
                             keff_og_unc=keff_unc,
                             keff_new=1.41474,
                             keff_new_unc=0.00003,
                             temp_change=+50))
# flibe
print(
    reactivity_coefficient_b(keff_og=keff,
                             keff_og_unc=keff_unc,
                             keff_new=1.41804,
                             keff_new_unc=0.00003,
                             temp_change=+50))
示例#6
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-l',
                        '--benchmarks',
                        type=Path,
                        default=Path('benchmarks/lists/pst-short'),
                        help='List of benchmarks to run.')
    parser.add_argument('-c',
                        '--code',
                        choices=['openmc', 'mcnp'],
                        default='openmc',
                        help='Code used to run benchmarks.')
    parser.add_argument('-x',
                        '--cross-sections',
                        type=str,
                        default=os.getenv('OPENMC_CROSS_SECTIONS'),
                        help='OpenMC cross sections XML file.')
    parser.add_argument('-s',
                        '--suffix',
                        type=str,
                        default='70c',
                        help='MCNP cross section suffix')
    parser.add_argument('-p',
                        '--particles',
                        type=int,
                        default=10000,
                        help='Number of source particles.')
    parser.add_argument('-b',
                        '--batches',
                        type=int,
                        default=150,
                        help='Number of batches.')
    parser.add_argument('-i',
                        '--inactive',
                        type=int,
                        default=50,
                        help='Number of inactive batches.')
    parser.add_argument('-m',
                        '--max-batches',
                        type=int,
                        default=10000,
                        help='Maximum number of batches.')
    parser.add_argument(
        '-t',
        '--threshold',
        type=float,
        default=0.0001,
        help='Value of the standard deviation trigger on eigenvalue.')
    parser.add_argument(
        '--mpi-args',
        default="",
        help="MPI execute command and any additional MPI arguments")
    args = parser.parse_args()

    # Create timestamp
    timestamp = time.strftime("%Y-%m-%d-%H%M%S")

    # Check that executable exists
    executable = 'mcnp6' if args.code == 'mcnp' else 'openmc'
    if not shutil.which(executable, os.X_OK):
        msg = f'Unable to locate executable {executable} in path.'
        raise IOError(msg)
    mpi_args = args.mpi_args.split()

    # Create directory and set filename for results
    results_dir = Path('results')
    results_dir.mkdir(exist_ok=True)
    outfile = results_dir / f'{timestamp}.csv'

    # Get a copy of the benchmarks repository
    if not Path('benchmarks').is_dir():
        repo = 'https://github.com/mit-crpg/benchmarks.git'
        subprocess.run(['git', 'clone', repo], check=True)

    # Get the list of benchmarks to run
    if not args.benchmarks.is_file():
        msg = f'Unable to locate benchmark list {args.benchmarks}.'
        raise IOError(msg)
    with open(args.benchmarks) as f:
        benchmarks = [Path(line) for line in f.read().split()]

    # Set cross sections
    if args.cross_sections is not None:
        os.environ["OPENMC_CROSS_SECTIONS"] = args.cross_sections

    # Prepare and run benchmarks
    for i, benchmark in enumerate(benchmarks):
        print(f"{i + 1} {benchmark} ", end="", flush=True)

        path = 'benchmarks' / benchmark

        if args.code == 'openmc':
            openmc.reset_auto_ids()

            # Remove old statepoint files
            for f in path.glob('statepoint.*.h5'):
                os.remove(f)

            # Modify settings
            settings = openmc.Settings.from_xml(path / 'settings.xml')
            settings.particles = args.particles
            settings.inactive = args.inactive
            settings.batches = args.batches
            settings.keff_trigger = {
                'type': 'std_dev',
                'threshold': args.threshold
            }
            settings.trigger_active = True
            settings.trigger_max_batches = args.max_batches
            settings.output = {'tallies': False}
            settings.export_to_xml(path)

            # Re-generate materials if Python script is present
            genmat_script = path / "generate_materials.py"
            if genmat_script.is_file():
                subprocess.run(["python", "generate_materials.py"], cwd=path)

            # Run benchmark
            proc = subprocess.run(
                mpi_args + ["openmc"],
                cwd=path,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                universal_newlines=True,
            )

            # Determine last statepoint
            t_last = 0
            last_statepoint = None
            for sp in path.glob('statepoint.*.h5'):
                mtime = sp.stat().st_mtime
                if mtime >= t_last:
                    t_last = mtime
                    last_statepoint = sp

            # Read k-effective mean and standard deviation from statepoint
            if last_statepoint is not None:
                with openmc.StatePoint(last_statepoint) as sp:
                    mean = sp.k_combined.nominal_value
                    stdev = sp.k_combined.std_dev

        else:
            # Read input file
            with open(path / 'input', 'r') as f:
                lines = f.readlines()

            # Update criticality source card
            line = f'kcode {args.particles} 1 {args.inactive} {args.batches}\n'
            for i in range(len(lines)):
                if lines[i].strip().startswith('kcode'):
                    lines[i] = line
                    break

            # Update cross section suffix
            match = '(7[0-4]c)|(8[0-6]c)'
            if not re.match(match, args.suffix):
                msg = f'Unsupported cross section suffix {args.suffix}.'
                raise ValueError(msg)
            lines = [re.sub(match, args.suffix, x) for x in lines]

            # Write new input file
            with open(path / 'input', 'w') as f:
                f.write(''.join(lines))

            # Remove old MCNP output files
            for f in ('outp', 'runtpe', 'srctp'):
                try:
                    os.remove(path / f)
                except OSError:
                    pass

            # Run benchmark and capture and print output
            arg_list = mpi_args + [executable, 'inp=input']
            proc = subprocess.run(arg_list,
                                  cwd=path,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.STDOUT,
                                  universal_newlines=True)

            # Read k-effective mean and standard deviation from output
            with open(path / 'outp', 'r') as f:
                line = f.readline()
                while not line.strip().startswith('col/abs/trk len'):
                    line = f.readline()
                words = line.split()
                mean = float(words[2])
                stdev = float(words[3])

        # Write output to file
        with open(path / f"output_{timestamp}", "w") as fh:
            fh.write(proc.stdout)

        if proc.returncode != 0:
            mean = stdev = ""
            print()
        else:
            # Display k-effective
            print(f"{mean:.5f} ± {stdev:.5f}")

        # Write results
        words = str(benchmark).split('/')
        name = words[1]
        case = '/' + words[3] if len(words) > 3 else ''
        line = f'{name}{case},{mean},{stdev}\n'
        with open(outfile, 'a') as f:
            f.write(line)
示例#7
0
import matplotlib.pyplot as plt
import os
import openmc
import numpy as np
import helperfunction as hf
import csv

# ### Load Reference
directory = "./data/FET/1000/"
sp = openmc.StatePoint(directory + 'statepoint.1100.h5')
porder = 50
name = 'fet' + str(porder)
fet = sp.get_tally(name=name)
df = fet.get_pandas_dataframe()
# print(df[df['score'] == 'absorption'])
fet_mean_coeff = df[df['score'] == 'absorption']['mean']
fet_std_coeff = df[df['score'] == 'absorption']['std. dev.']
fet_var_coeff = np.square(fet_std_coeff)
fet_var_coeff_even = fet_var_coeff[::2]
fet_mean_coeff_even = fet_mean_coeff[::2]
# print(fet_mean_coeff)
# print(fet_std_coeff)
# print(fet_var_coeff)
# normarray = np.arange(porder+1)
normarrayeven = np.linspace(0, porder, num=(porder / 2) + 1)
print(normarrayeven)
k_n = (2 * normarrayeven + 1) / 2
up = np.multiply(fet_var_coeff_even, k_n)
upnew = fet_var_coeff_even
down = np.square(fet_mean_coeff_even)
Rvalue = np.divide(up, down)
示例#8
0
    def _get_results(self, hash_output=False):
        """Digest info in the statepoint and return as a string."""

        # Read the statepoint file.
        statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0]
        sp = openmc.StatePoint(statepoint)

        # Extract the cell tally
        tallies = [sp.get_tally(name='cell tally')]

        # Slice the tallies by cell filter bins
        cell_filter_prod = itertools.product(tallies, self.cell_filters)
        tallies = map(
            lambda tf: tf[0].get_slice(filters=[type(tf[1])],
                                       filter_bins=[tf[1].get_bin(0)]),
            cell_filter_prod)

        # Slice the tallies by energy filter bins
        energy_filter_prod = itertools.product(tallies, self.energy_filters)
        tallies = map(
            lambda tf: tf[0].get_slice(filters=[type(tf[1])],
                                       filter_bins=[(tf[1].get_bin(0), )]),
            energy_filter_prod)

        # Slice the tallies by nuclide
        nuclide_prod = itertools.product(tallies, self.nuclides)
        tallies = map(lambda tn: tn[0].get_slice(nuclides=[tn[1]]),
                      nuclide_prod)

        # Slice the tallies by score
        score_prod = itertools.product(tallies, self.scores)
        tallies = map(lambda ts: ts[0].get_slice(scores=[ts[1]]), score_prod)
        tallies = list(tallies)

        # Initialize an output string
        outstr = ''

        # Append sliced Tally Pandas DataFrames to output string
        for tally in tallies:
            df = tally.get_pandas_dataframe()
            outstr += df.to_string()

        # Merge all tallies together
        while len(tallies) != 1:
            halfway = int(len(tallies) / 2)
            zip_split = zip(tallies[:halfway], tallies[halfway:])
            tallies = list(map(lambda xy: xy[0].merge(xy[1]), zip_split))

        # Append merged Tally Pandas DataFrame to output string
        df = tallies[0].get_pandas_dataframe()
        outstr += df.to_string() + '\n'

        # Extract the distribcell tally
        distribcell_tally = sp.get_tally(name='distribcell tally')

        # Sum up a few subdomains from the distribcell tally
        sum1 = distribcell_tally.summation(
            filter_type=openmc.DistribcellFilter,
            filter_bins=[0, 100, 2000, 30000])
        # Sum up a few subdomains from the distribcell tally
        sum2 = distribcell_tally.summation(
            filter_type=openmc.DistribcellFilter,
            filter_bins=[500, 5000, 50000])

        # Merge the distribcell tally slices
        merge_tally = sum1.merge(sum2)

        # Append merged Tally Pandas DataFrame to output string
        df = merge_tally.get_pandas_dataframe()
        outstr += df.to_string() + '\n'

        # Extract the mesh tally
        mesh_tally = sp.get_tally(name='mesh tally')

        # Sum up a few subdomains from the mesh tally
        sum1 = mesh_tally.summation(filter_type=openmc.MeshFilter,
                                    filter_bins=[(1, 1, 1), (1, 2, 1)])
        # Sum up a few subdomains from the mesh tally
        sum2 = mesh_tally.summation(filter_type=openmc.MeshFilter,
                                    filter_bins=[(2, 1, 1), (2, 2, 1)])

        # Merge the mesh tally slices
        merge_tally = sum1.merge(sum2)

        # Append merged Tally Pandas DataFrame to output string
        df = merge_tally.get_pandas_dataframe()
        outstr += df.to_string() + '\n'

        # Hash the results if necessary
        if hash_output:
            sha512 = hashlib.sha512()
            sha512.update(outstr.encode('utf-8'))
            outstr = sha512.hexdigest()

        return outstr
示例#9
0
def sphere_with_firstwall_model(
        material_for_structure,
        blanket_breeder_material,
        blanket_coolant_material,
        firstwall_coolant_material,
        blanket_breeder_li6_enrichment,  # this is a percentage
        coolant_pressure,  # this is in Pa
        blanket_coolant_temperature_in_C,
        firstwall_coolant_temperature_in_C,
        blanket_breeder_fraction,
        blanket_coolant_fraction,
        blanket_structural_fraction,
        blanket_breeder_temperature_in_C = None, #needed for liquid breeders like lithium lead
        firstwall_thickness = 2.7,  # this is in cm
        blanket_thickness = 200,  # this is in cm
        inner_radius = 1000,
        firstwall_armour_fraction = 0.106305, # equivilent to 3mm and based on https://doi.org/10.1016/j.fusengdes.2017.02.008
        firstwall_coolant_fraction= 0.333507, # based on https://doi.org/10.1016/j.fusengdes.2017.02.008
        firstwall_structural_fraction = 0.560188, # based on https://doi.org/10.1016/j.fusengdes.2017.02.008
        blanket_multipler_material = None, #used for combined breeder multiplier options
        blanket_multiplier_fraction = None, #used for combined breeder multiplier options
        blanket_breeder_material_packing_fraction = None, #used for combined breeder multiplier options
        blanket_multiplier_packing_fraction = None, #used for combined breeder multiplier options
        blanket_multiplier_material = None #used for combined breeder multiplier options
        ):

    breeder_percent_in_breeder_plus_multiplier_ratio = 100 * (blanket_breeder_fraction / (blanket_breeder_fraction + blanket_multiplier_fraction))

    inputs = locals()

    """ 
    This function builds materials for the homogenised blanket material, homogenised firstwall material
    The creates a simple sphere geometry with a simple point source and TBR tally on the blanket
    The function also carries out the simulation and writes the results to a JSON file
    """

    # creates homogensied blanket material using a single breeder / multiplier material (e.g lithium lead)
    if blanket_breeder_material == 'Pb842Li158':
        blanket_material =  MultiMaterial(material_tag = 'blanket_material',
                            materials = [
                                        Material(material_name = material_for_structure),
                                        Material(material_name = blanket_coolant_material,
                                                 temperature_in_C = blanket_coolant_temperature_in_C,
                                                 pressure_in_Pa = coolant_pressure),
                                        Material(material_name = blanket_breeder_material, 
                                                 enrichment = blanket_breeder_li6_enrichment,
                                                 temperature_in_C = blanket_breeder_temperature_in_C),
                                        ],
                            fracs = [blanket_structural_fraction,
                                    blanket_coolant_fraction,
                                    blanket_breeder_fraction],
                            percent_type='vo'
                            ).openmc_material

    # creates homogensied blanket material using a combined breeder multiplier material (e.g lithium ceramic with be multiplier)
    else:

        blanket_material =  MultiMaterial(
                                material_tag = 'blanket_material',
                                materials = [
                                            Material(material_name = material_for_structure),
                                            Material(material_name = blanket_coolant_material,
                                                    temperature_in_C = blanket_coolant_temperature_in_C,
                                                    pressure_in_Pa = coolant_pressure),
                                            Material(material_name = blanket_breeder_material, 
                                                    enrichment = blanket_breeder_li6_enrichment,
                                                    packing_fraction = blanket_breeder_material_packing_fraction),
                                            Material(material_name = blanket_multipler_material,
                                                    packing_fraction = blanket_multiplier_packing_fraction),
                                            ],
                                fracs = [blanket_structural_fraction,
                                        blanket_coolant_fraction,
                                        blanket_breeder_fraction,
                                        blanket_multiplier_fraction],
                                percent_type='vo'
                                ).openmc_material


    # creates homogensied firstwall material with eurofer, tungsten and a coolant
    firstwall_material = MultiMaterial(material_tag = 'firstwall_material',
                                        materials = [
                                            Material(material_name = 'tungsten'),
                                            Material(material_name = firstwall_coolant_material,
                                                        temperature_in_C = firstwall_coolant_temperature_in_C,
                                                        pressure_in_Pa = coolant_pressure),
                                            Material(material_name = 'eurofer')],
                                        fracs = [firstwall_armour_fraction,
                                                 firstwall_coolant_fraction,
                                                 firstwall_structural_fraction]
                                        ).openmc_material

    mats = openmc.Materials([blanket_material, firstwall_material]) 

    # creates surfaces
    breeder_blanket_inner_surface = openmc.Sphere(r=inner_radius+firstwall_thickness)
    firstwall_outer_surface = openmc.Sphere(r=inner_radius)  

    inner_void_region = -firstwall_outer_surface 
    inner_void_cell = openmc.Cell(region=inner_void_region) 
    inner_void_cell.name = 'inner_void'

    firstwall_region = +firstwall_outer_surface & -breeder_blanket_inner_surface 
    firstwall_cell = openmc.Cell(name='firstwall', region=firstwall_region)
    firstwall_cell.fill = firstwall_material

    breeder_blanket_outer_surface = openmc.Sphere(r=inner_radius+firstwall_thickness+blanket_thickness, boundary_type='vacuum')
    breeder_blanket_region = -breeder_blanket_outer_surface & +breeder_blanket_inner_surface
    breeder_blanket_cell = openmc.Cell(name = 'breeder_blanket', region=breeder_blanket_region) 
    breeder_blanket_cell.fill = blanket_material

    universe = openmc.Universe(cells=[inner_void_cell, 
                                      firstwall_cell,
                                      breeder_blanket_cell])

    geom = openmc.Geometry(universe)

    # assigns simulation settings
    sett = openmc.Settings()
    sett.batches = 200  # this is minimum number of batches that will be run
    sett.trigger_active = True
    sett.trigger_max_batches =  1500  # this is maximum number of batches that will be run
    sett.particles = 300
    sett.verbosity = 1
    sett.run_mode = 'fixed source'

    # sets a 14MeV (distributuion) point source
    source = openmc.Source()
    source.space = openmc.stats.Point((0,0,0))
    source.angle = openmc.stats.Isotropic()
    source.energy = openmc.stats.Muir(e0=14080000.0, m_rat=5.0, kt=20000.0) #neutron energy = 14.08MeV, AMU for D + T = 5, temperature is 20KeV
    sett.source = source

    # this is the tally set up
    tallies = openmc.Tallies()

    # define filters
    cell_filter_breeder = openmc.CellFilter(breeder_blanket_cell)
    particle_filter = openmc.ParticleFilter(['neutron'])

    # creates the TBR tally using the filters and sets a completion trigger
    tally = openmc.Tally(name='TBR')
    tally.filters = [cell_filter_breeder, particle_filter]
    tally.scores = ['(n,Xt)'] # where X is a wildcard, if MT 105 or (n,t) then some tritium production will be missed, for example (n,nt) which happens in Li7 would be missed
    tally.triggers = [openmc.Trigger(trigger_type='rel_err', threshold=0.0001)]  # This stops the simulation if the threshold is meet
    tallies.append(tally)

    # collects all the model parts and runs the model
    model = openmc.model.Model(geom, mats, sett, tallies)
    sp_filename = model.run(output=False)

    # opens the output file and retrieves the tally results
    sp = openmc.StatePoint(sp_filename)

    tally = sp.get_tally(name='TBR')

    df = tally.get_pandas_dataframe()

    tally_result = df['mean'].sum()
    tally_std_dev = df['std. dev.'].sum()

    # combines the tally results with the input data
    inputs.update({'tbr': tally_result})
    inputs.update({'tbr_error': tally_std_dev})

    return inputs
示例#10
0
p.pixels = (200, 200)
p.color_by = 'material'
p.colors = {uo2: 'yellow', heavy_water: 'cyan'}

plots = openmc.Plots([p])
plots.export_to_xml()

openmc.plot_geometry(output=False)
pngstring = 'pinplot{}.png'.format(str(pitch))
subprocess.call(['convert', 'pinplot.ppm', pngstring])

#############################
###       EXECUTION       ###
#############################
openmc.run()
sp = openmc.StatePoint('statepoint.{}.h5'.format(settings.batches))
# Collect all the tallies
fiss_rate = sp.get_tally(name='fiss. rate')
fiss_rate_df = fiss_rate.get_pandas_dataframe()
abs_rate = sp.get_tally(name='abs. rate')
abs_rate_df = abs_rate.get_pandas_dataframe()
therm_abs_rate = sp.get_tally(name='therm. abs. rate')
therm_abs_rate_df = therm_abs_rate.get_pandas_dataframe()
fuel_therm_abs_rate = sp.get_tally(name='fuel therm. abs. rate')
fuel_therm_abs_rate_df = fuel_therm_abs_rate.get_pandas_dataframe()
therm_fiss_rate = sp.get_tally(name='therm. fiss. rate')
therm_fiss_rate_df = therm_fiss_rate.get_pandas_dataframe()

# Compute k-infinity
kinf = fiss_rate / abs_rate
kinf_df = kinf.get_pandas_dataframe()
示例#11
0
def simulate_model(
    enrichment,
    thickness,
    breeder_material_name="Li4SiO4",
    temperature_in_C=500,
    batches=10,
    nps=1000,
    inner_radius=500,
):

    # MATERIALS from library of materials in neutronics_material_maker package
    breeder_material = Material(
        material_name=breeder_material_name,
        enrichment=enrichment,
        temperature_in_C=temperature_in_C,
    ).neutronics_material

    eurofer = Material(material_name="eurofer").neutronics_material
    copper = Material(material_name="copper").neutronics_material

    mats = openmc.Materials([breeder_material, eurofer, copper])
    mats.export_to_xml("materials.xml")

    # GEOMETRY#

    central_sol_surface = openmc.ZCylinder(r=100)
    central_shield_outer_surface = openmc.ZCylinder(r=110)
    first_wall_inner_surface = openmc.Sphere(r=inner_radius)
    first_wall_outer_surface = openmc.Sphere(r=inner_radius + 10)
    breeder_blanket_outer_surface = openmc.Sphere(r=inner_radius + 10.0 +
                                                  thickness)
    vessel_outer_surface = openmc.Sphere(r=inner_radius + 10.0 + thickness +
                                         10.0,
                                         boundary_type="vacuum")

    central_sol_region = -central_sol_surface & -breeder_blanket_outer_surface
    central_sol_cell = openmc.Cell(region=central_sol_region)
    central_sol_cell.fill = copper

    central_shield_region = (+central_sol_surface
                             & -central_shield_outer_surface
                             & -breeder_blanket_outer_surface)
    central_shield_cell = openmc.Cell(region=central_shield_region)
    central_shield_cell.fill = eurofer

    inner_void_region = -first_wall_inner_surface & +central_shield_outer_surface
    inner_void_cell = openmc.Cell(region=inner_void_region)
    inner_void_cell.name = "inner_void"

    first_wall_region = (-first_wall_outer_surface
                         & +first_wall_inner_surface
                         & +central_shield_outer_surface)
    first_wall_cell = openmc.Cell(region=first_wall_region)
    first_wall_cell.fill = eurofer

    breeder_blanket_region = (+first_wall_outer_surface
                              & -breeder_blanket_outer_surface
                              & +central_shield_outer_surface)
    breeder_blanket_cell = openmc.Cell(region=breeder_blanket_region)
    breeder_blanket_cell.fill = breeder_material

    vessel_region = +breeder_blanket_outer_surface & -vessel_outer_surface
    vessel_cell = openmc.Cell(region=vessel_region)
    vessel_cell.name = "vessel"
    vessel_cell.fill = eurofer

    universe = openmc.Universe(cells=[
        central_sol_cell,
        central_shield_cell,
        inner_void_cell,
        first_wall_cell,
        breeder_blanket_cell,
        vessel_cell,
    ])

    geom = openmc.Geometry(universe)

    # SIMULATION SETTINGS#

    sett = openmc.Settings()
    sett.batches = batches
    sett.inactive = 0
    sett.particles = nps
    sett.run_mode = "fixed source"

    source = openmc.Source()
    source.space = openmc.stats.Point((150, 0, 0))
    source.angle = openmc.stats.Isotropic()
    source.energy = openmc.stats.Discrete([14.08e6], [1])
    sett.source = source

    # sett.export_to_xml("settings.xml")

    # tally filters
    particle_filter = openmc.ParticleFilter("neutron")
    cell_filter_breeder = openmc.CellFilter(breeder_blanket_cell)

    # TALLIES#
    tallies = openmc.Tallies()

    tally = openmc.Tally(name="TBR")
    tally.filters = [cell_filter_breeder, particle_filter]
    tally.scores = ["(n,Xt)"]
    tallies.append(tally)

    # RUN OPENMC #
    model = openmc.model.Model(geom, mats, sett, tallies)
    model.run(output=False)

    # RETRIEVING TALLY RESULTS

    sp = openmc.StatePoint("statepoint." + str(batches) + ".h5")

    json_output = {
        "batches": batches,
        "nps": nps,
        "enrichment": enrichment,
        "inner_radius": inner_radius,
        "thickness": thickness,
        "breeder_material_name": breeder_material_name,
        "temperature_in_C": temperature_in_C,
    }

    tally = sp.get_tally(name="TBR")

    df = tally.get_pandas_dataframe()

    json_output["TBR"] = df["mean"].sum()
    json_output["TBR_std_dev"] = df["std. dev."].sum()

    return json_output
示例#12
0
 def open(self):
     if self.is_open:
         return
     self._sp = openmc.StatePoint(self.filename)
     self.is_open = True
示例#13
0
import helperfunction as hf
import csv
import sys

N = []
for i in range(1, len(sys.argv)):
    N.append(int(sys.argv[i]))
zerk_order = 100
evenmodes = int(zerk_order / 2 + 1)
orderarray = np.linspace(0, zerk_order, evenmodes)
pos, k_n = hf.get_position(zerk_order)
for n in N:
    # ### Load Reference
    directory = "./data/FET/" + str(n) + "/"
    filename = "statepoint." + str(int(n + 100)) + ".h5"
    sp = openmc.StatePoint(directory + filename)
    name = 'fet' + str(zerk_order)
    fettal = sp.get_tally(name=name)

    fetabs = fettal.get_slice(scores=['absorption'])
    fetabs_mean = fetabs.get_pandas_dataframe()['mean']
    fetabs_std = fetabs.get_pandas_dataframe()['std. dev.']

    fet_mean_coeff = hf.get_val_at_pos(pos, fetabs_mean)
    fet_std_coeff = hf.get_val_at_pos(pos, fetabs_std)
    fet_var_coeff = np.square(fet_std_coeff)

    # normarrayeven = np.linspace(0,zerk_order,num = (zerk_order/2)+1)
    # print(normarrayeven)
    # k_n = (2*normarrayeven + 1)/2
示例#14
0
def make_geometry_tallies(batches, nps, enrichment_fraction, inner_radius,
                          thickness, breeder_material_name, temperature_in_C):
    #print('simulating ',batches,enrichment_fraction,inner_radius,thickness,breeder_material_name)

    #MATERIALS#
    breeder_material = make_breeder_materials(enrichment_fraction,
                                              breeder_material_name,
                                              temperature_in_C)
    eurofer = make_eurofer()
    copper = make_copper()
    mats = openmc.Materials([breeder_material, eurofer, copper])
    mats.export_to_xml('materials.xml')

    #GEOMETRY#

    central_sol_surface = openmc.ZCylinder(R=100)
    central_shield_outer_surface = openmc.ZCylinder(R=110)
    first_wall_inner_surface = openmc.Sphere(R=inner_radius)
    first_wall_outer_surface = openmc.Sphere(R=inner_radius + 10)
    breeder_blanket_outer_surface = openmc.Sphere(R=inner_radius + 10.0 +
                                                  thickness)
    vessel_outer_surface = openmc.Sphere(R=inner_radius + 10.0 + thickness +
                                         10.0,
                                         boundary_type='vacuum')

    central_sol_region = -central_sol_surface & -breeder_blanket_outer_surface
    central_sol_cell = openmc.Cell(region=central_sol_region)
    central_sol_cell.fill = copper

    central_shield_region = +central_sol_surface & -central_shield_outer_surface & -breeder_blanket_outer_surface
    central_shield_cell = openmc.Cell(region=central_shield_region)
    central_shield_cell.fill = eurofer

    inner_void_region = -first_wall_inner_surface & +central_shield_outer_surface
    inner_void_cell = openmc.Cell(region=inner_void_region)
    inner_void_cell.name = 'inner_void'

    first_wall_region = -first_wall_outer_surface & +first_wall_inner_surface & +central_shield_outer_surface
    first_wall_cell = openmc.Cell(region=first_wall_region)
    first_wall_cell.fill = eurofer

    breeder_blanket_region = +first_wall_outer_surface & -breeder_blanket_outer_surface & +central_shield_outer_surface
    breeder_blanket_cell = openmc.Cell(region=breeder_blanket_region)
    breeder_blanket_cell.fill = breeder_material

    vessel_region = +breeder_blanket_outer_surface & -vessel_outer_surface
    vessel_cell = openmc.Cell(region=vessel_region)
    vessel_cell.name = 'vessel'
    vessel_cell.fill = eurofer

    universe = openmc.Universe(cells=[
        central_sol_cell, central_shield_cell, inner_void_cell,
        first_wall_cell, breeder_blanket_cell, vessel_cell
    ])

    #plt.show(universe.plot(width=(1500,1500),basis='xz'))

    geom = openmc.Geometry(universe)
    # geom.export_to_xml('geometry.xml')

    #SIMULATION SETTINGS#

    sett = openmc.Settings()
    sett.batches = batches
    sett.inactive = 1
    sett.particles = nps
    sett.run_mode = 'fixed source'

    source = openmc.Source()
    source.space = openmc.stats.Point((150, 0, 0))
    source.angle = openmc.stats.Isotropic()
    #source.energy = openmc.stats.Discrete([14.08e6], [1])
    source.energy = openmc.stats.Muir(
        e0=14080000.0, m_rat=5.0, kt=20000.0
    )  #neutron energy = 14.08MeV, AMU for D + T = 5, temperature is 20KeV
    sett.source = source

    sett.export_to_xml('settings.xml')

    #tally filters
    particle_filter = openmc.ParticleFilter([1])  #1 is neutron, 2 is photon
    cell_filter_breeder = openmc.CellFilter(breeder_blanket_cell)
    cell_filter_vessel = openmc.CellFilter(vessel_cell)
    surface_filter_front = openmc.SurfaceFilter(first_wall_inner_surface)
    surface_filter_rear = openmc.SurfaceFilter(breeder_blanket_outer_surface)
    energy_bins = openmc.mgxs.GROUP_STRUCTURES['VITAMIN-J-175']
    energy_filter = openmc.EnergyFilter(energy_bins)

    #TALLIES#
    tallies = openmc.Tallies()

    tally = openmc.Tally(name='TBR')
    tally.filters = [cell_filter_breeder, particle_filter]
    tally.scores = ['205']
    tallies.append(tally)

    tally = openmc.Tally(name='blanket_leakage')
    tally.filters = [surface_filter_rear, particle_filter]
    tally.scores = ['current']
    tallies.append(tally)

    tally = openmc.Tally(name='vessel_leakage')
    tally.filters = [surface_filter_rear, particle_filter]
    tally.scores = ['current']
    tallies.append(tally)

    tally = openmc.Tally(name='rear_neutron_spectra')
    tally.filters = [surface_filter_rear, particle_filter, energy_filter]
    tally.scores = ['flux']
    tallies.append(tally)

    tally = openmc.Tally(name='front_neutron_spectra')
    tally.filters = [surface_filter_front, particle_filter, energy_filter]
    tally.scores = ['flux']
    tallies.append(tally)

    tally = openmc.Tally(name='breeder_blanket_spectra')
    tally.filters = [cell_filter_breeder, particle_filter, energy_filter]
    tally.scores = ['flux']
    tallies.append(tally)

    tally = openmc.Tally(name='vacuum_vessel_spectra')
    tally.filters = [cell_filter_vessel, particle_filter, energy_filter]
    tally.scores = ['flux']
    tallies.append(tally)

    tally = openmc.Tally(name='DPA')
    tally.filters = [cell_filter_vessel, particle_filter]
    tally.scores = ['444']
    tallies.append(tally)

    #RUN OPENMC #
    model = openmc.model.Model(geom, mats, sett, tallies)

    model.run()

    #RETRIEVING TALLY RESULTS

    sp = openmc.StatePoint('statepoint.' + str(batches) + '.h5')

    json_output = {
        'enrichment_fraction': enrichment_fraction,
        'inner_radius': inner_radius,
        'thickness': thickness,
        'breeder_material_name': breeder_material_name,
        'temperature_in_C': temperature_in_C
    }

    tallies_to_retrieve = ['TBR', 'DPA', 'blanket_leakage', 'vessel_leakage']
    for tally_name in tallies_to_retrieve:
        tally = sp.get_tally(name=tally_name)
        tally_result = tally.sum[0][0][
            0] / batches  #for some reason the tally sum is a nested list
        tally_std_dev = tally.std_dev[0][0][
            0] / batches  #for some reason the tally std_dev is a nested list

        json_output[tally_name] = {
            'value': tally_result,
            'std_dev': tally_std_dev
        }

    spectra_tallies_to_retrieve = [
        'front_neutron_spectra', 'breeder_blanket_spectra',
        'vacuum_vessel_spectra', 'rear_neutron_spectra'
    ]
    for spectra_name in spectra_tallies_to_retrieve:
        spectra_tally = sp.get_tally(name=spectra_name)
        spectra_tally_result = [entry[0][0] for entry in spectra_tally.mean]
        spectra_tally_std_dev = [
            entry[0][0] for entry in spectra_tally.std_dev
        ]

        json_output[spectra_name] = {
            'value': spectra_tally_result,
            'std_dev': spectra_tally_std_dev,
            'energy_groups': list(energy_bins)
        }

    return json_output
示例#15
0
def make_materials_geometry_tallies(enrichment_fraction):

    #MATERIALS#

    breeder_material = openmc.Material(
        1, "breeder_material")  #Pb84.2Li15.8 with natural enrichment of Li6
    breeder_material.add_element('Pb', 84.2, 'ao')
    breeder_material.add_nuclide('Li6', enrichment_fraction * 15.8, 'ao')
    breeder_material.add_nuclide('Li7', (1.0 - enrichment_fraction) * 15.8,
                                 'ao')
    breeder_material.set_density('atom/b-cm', 3.2720171e-2)  # around 11 g/cm3

    copper = openmc.Material(name='copper')
    copper.set_density('g/cm3', 8.5)
    copper.add_element('Cu', 1.0)

    eurofer = openmc.Material(name='eurofer')
    eurofer.set_density('g/cm3', 7.75)
    eurofer.add_element('Fe', 89.067, percent_type='wo')
    eurofer.add_element('C', 0.11, percent_type='wo')
    eurofer.add_element('Mn', 0.4, percent_type='wo')
    eurofer.add_element('Cr', 9.0, percent_type='wo')
    eurofer.add_element('Ta', 0.12, percent_type='wo')
    eurofer.add_element('W', 1.1, percent_type='wo')
    eurofer.add_element('N', 0.003, percent_type='wo')
    eurofer.add_element('V', 0.2, percent_type='wo')

    mats = openmc.Materials([breeder_material, eurofer, copper])

    #GEOMETRY#

    central_sol_surface = openmc.ZCylinder(R=100)
    central_shield_outer_surface = openmc.ZCylinder(R=110)
    vessel_inner = openmc.Sphere(R=500)
    first_wall_outer_surface = openmc.Sphere(R=510)
    breeder_blanket_outer_surface = openmc.Sphere(R=610,
                                                  boundary_type='vacuum')

    central_sol_region = -central_sol_surface & -vessel_inner
    central_sol_cell = openmc.Cell(region=central_sol_region)
    central_sol_cell.fill = copper

    central_shield_region = +central_sol_surface & -central_shield_outer_surface & -vessel_inner
    central_shield_cell = openmc.Cell(region=central_shield_region)
    central_shield_cell.fill = eurofer

    inner_vessel_region = -vessel_inner & +central_shield_outer_surface
    inner_vessel_cell = openmc.Cell(region=inner_vessel_region)

    first_wall_region = -first_wall_outer_surface & +vessel_inner
    first_wall_cell = openmc.Cell(region=first_wall_region)
    first_wall_cell.fill = eurofer

    breeder_blanket_region = +first_wall_outer_surface & -breeder_blanket_outer_surface
    breeder_blanket_cell = openmc.Cell(region=breeder_blanket_region)
    breeder_blanket_cell.fill = breeder_material
    breeder_blanket_cell.name = 'breeder_blanket'

    universe = openmc.Universe(cells=[
        central_sol_cell, central_shield_cell, inner_vessel_cell,
        first_wall_cell, breeder_blanket_cell
    ])
    geom = openmc.Geometry(universe)

    #SIMULATION SETTINGS#

    sett = openmc.Settings()
    batches = 3
    sett.batches = batches
    sett.inactive = 50
    sett.particles = 5000
    sett.run_mode = 'fixed source'

    source = openmc.Source()
    source.space = openmc.stats.Point((350, 0, 0))
    source.angle = openmc.stats.Isotropic()
    source.energy = openmc.stats.Discrete([14e6], [1])
    sett.source = source

    #TALLIES#

    tallies = openmc.Tallies()

    cell_filter = openmc.CellFilter(breeder_blanket_cell)
    tbr_tally = openmc.Tally(2, name='TBR')
    tbr_tally.filters = [cell_filter]
    tbr_tally.scores = ['205']
    tallies.append(tbr_tally)

    #RUN OPENMC #
    model = openmc.model.Model(geom, mats, sett, tallies)
    model.run()
    sp = openmc.StatePoint('statepoint.' + str(batches) + '.h5')

    tbr_tally = sp.get_tally(name='TBR')
    tbr_tally_result = tbr_tally.sum[0][0][
        0] / batches  #for some reason the tally sum is a nested list
    tbr_tally_std_dev = tbr_tally.std_dev[0][0][
        0] / batches  #for some reason the tally std_dev is a nested list

    return {
        'enrichment_fraction': enrichment_fraction,
        'tbr_tally_result': tbr_tally_result,
        'tbr_tally_std_dev': tbr_tally_std_dev
    }
示例#16
0
    def _plot(self):
        """Extract and plot the results
 
        """
        # Read the results from the OpenMC statepoint
        with openmc.StatePoint(os.path.join('openmc',
                                            'statepoint.1.h5')) as sp:
            t = sp.get_tally(name='photon flux')
            x_openmc = t.find_filter(openmc.EnergyFilter).bins[:, 1] * 1.e-6
            y_openmc = t.mean[:, 0, 0]

        # Read the results from the MCNP output file
        with open(os.path.join('mcnp', 'outp'), 'r') as f:
            text = f.read()
            p = text.find('1tally')
            p = text.find('energy', p) + 10
            q = text.find('total', p)
            t = np.fromiter(text[p:q].split(), float)
            t.shape = (len(t) // 3, 3)
            x_mcnp = t[1:, 0]
            y_mcnp = t[1:, 1]
            sd = t[1:, 2]

        # Normalize the spectra
        y_openmc /= np.diff(np.insert(x_openmc, 0, 1.e-3)) * sum(y_openmc)
        y_mcnp /= np.diff(np.insert(x_mcnp, 0, 1.e-3)) * sum(y_mcnp)

        # Compute the relative error
        err = np.zeros_like(y_mcnp)
        idx = np.where(y_mcnp > 0)
        err[idx] = (y_openmc[idx] - y_mcnp[idx]) / y_mcnp[idx]

        # Set up the figure
        fig = plt.figure(1, facecolor='w', figsize=(8, 8))
        ax1 = fig.add_subplot(111)

        # Create a second y-axis that shares the same x-axis, keeping the first
        # axis in front
        ax2 = ax1.twinx()
        ax1.set_zorder(ax2.get_zorder() + 1)
        ax1.patch.set_visible(False)

        # Plot the spectra
        ax1.loglog(x_mcnp, y_mcnp, 'r', linewidth=1, label='MCNP')
        ax1.loglog(x_openmc,
                   y_openmc,
                   'b',
                   linewidth=1,
                   label='OpenMC',
                   linestyle='--')

        # Plot the relative error and uncertainties
        ax2.semilogx(x_mcnp, err, color=(0.2, 0.8, 0.0), linewidth=1)
        ax2.semilogx(x_mcnp, 2 * sd, color='k', linestyle='--', linewidth=1)
        ax2.semilogx(x_mcnp, -2 * sd, color='k', linestyle='--', linewidth=1)

        # Set grid and tick marks
        ax1.tick_params(axis='both', which='both', direction='in', length=10)
        ax1.grid(b=False, axis='both', which='both')
        ax2.tick_params(axis='y', which='both', right=False)
        ax2.grid(b=True, which='both', axis='both', alpha=0.5, linestyle='--')

        # Set axes labels and limits
        ax1.set_xlim([1.e-3, self.energy_mev])
        ax1.set_xlabel('Energy (MeV)', size=12)
        ax1.set_ylabel('Spectrum', size=12)
        ax1.legend()
        ax2.set_ylabel("Relative error", size=12)
        title = self.material + ', ' + str(self.energy_mev) + ' MeV Source'
        plt.title(title)

        # Save plot
        os.makedirs('plots', exist_ok=True)
        name = self.material + '-' + str(self.energy_mev) + 'MeV.png'
        plt.savefig(os.path.join('plots', name), bbox_inches='tight')
        plt.close()
示例#17
0
pu = openmc.Material()
pu.set_density('sum')
pu.add_nuclide('Pu239', 3.7047e-02)
pu.add_nuclide('Pu240', 1.7512e-03)
pu.add_nuclide('Pu241', 1.1674e-04)
pu.add_element('Ga', 1.3752e-03)
mats = openmc.Materials([pu])
mats.export_to_xml()

# Create a single cell filled with the Pu metal
sphere = openmc.Sphere(r=6.3849, boundary_type='vacuum')
cell = openmc.Cell(fill=pu, region=-sphere)
geom = openmc.Geometry([cell])
geom.export_to_xml()

# Finally, define some run settings
settings = openmc.Settings()
settings.batches = 200
settings.inactive = 10
settings.particles = 10000
settings.export_to_xml()

# Run the simulation
openmc.run()

# Get the resulting k-effective value
n = settings.batches
with openmc.StatePoint(f'statepoint.{n}.h5') as sp:
    keff = sp.k_combined
    print(f'Final k-effective = {keff}')
示例#18
0
# Depletion simulation parameters
time_step = 1*24*60*60 # s
final_time = 5*24*60*60 # s
time_steps = np.full(final_time // time_step, time_step)

chain_file = './chain_simple.xml'
power = 174 # W/cm, for 2D simulations only (use W for 3D)

###############################################################################
#                      Load previous simulation results
###############################################################################

# Load geometry from statepoint
statepoint = 'statepoint.100.h5'
with openmc.StatePoint(statepoint) as sp:
    geometry = sp.summary.geometry

# Load previous depletion results
previous_results = openmc.deplete.ResultsList("depletion_results.h5")

###############################################################################
#                      Transport calculation settings
###############################################################################

# Instantiate a Settings object, set all runtime parameters
settings_file = openmc.Settings()
settings_file.batches = batches
settings_file.inactive = inactive
settings_file.particles = particles
示例#19
0
def pincellfunction(pitch, enrichment):

    settings = openmc.Settings()
    # Set high tolerance to allow use of lower temperature xs
    settings.temperature['tolerance'] = 10000
    settings.temperature['method'] = 'nearest'
    settings.temperature['multipole'] = True
    settings.cutoff = {'energy': 1e-8}  #energy cutoff in eV

    #############################
    ###       MATERIALS       ###
    #############################
    uo2 = openmc.Material(1, "uo2")
    uo2.add_element('U', 1.0, enrichment=enrichment)
    uo2.add_element('O', 2.0)
    uo2.set_density('g/cm3', 10.97)
    uo2.temperature = 900  #kelvin

    water = openmc.Material(3, "h2o")
    water.add_nuclide('H1', 2.0)
    water.add_nuclide('O16', 1.0)
    #Using P = 15.5 Mpa
    water.set_density('g/cm3', 0.66)
    water.add_s_alpha_beta('c_H_in_H2O')
    water.temperature = 600  #kelvin

    mats = openmc.Materials([uo2, water])
    mats.export_to_xml()

    #############################
    ###       GEOMETRY        ###
    #############################
    universe = openmc.Universe()

    fuel_or = openmc.ZCylinder(R=0.5)
    fuel_region = -fuel_or
    fuel_cell = openmc.Cell(1, 'fuel')
    fuel_cell.fill = uo2
    fuel_cell.region = fuel_region

    hexagon = openmc.get_hexagonal_prism(edge_length=1 / 3**(1 / 2) * pitch,
                                         orientation='y',
                                         boundary_type='reflective')
    bottom = openmc.ZPlane(z0=-pitch / 2, boundary_type='reflective')
    top = openmc.ZPlane(z0=pitch / 2, boundary_type='reflective')

    water_region = hexagon & +fuel_or
    moderator = openmc.Cell(2, 'moderator')
    moderator.fill = water
    moderator.region = water_region

    root = openmc.Universe(cells=(fuel_cell, moderator))
    geom = openmc.Geometry(root)
    geom.export_to_xml()

    #####################################
    ###        SOURCE/BATCHES         ###
    #####################################
    point = openmc.stats.Point((0, 0, 0))
    src = openmc.Source(space=point)

    settings.source = src
    settings.batches = 100
    settings.inactive = 10
    settings.particles = 1000

    settings.export_to_xml()

    #############################
    ###       TALLIES         ###
    #############################
    # Instantiate an empty Tallies object
    tallies_file = openmc.Tallies()

    # K-Eigenvalue (infinity) tallies
    fiss_rate = openmc.Tally(name='fiss. rate')
    fiss_rate.scores = ['nu-fission']
    tallies_file.append(fiss_rate)

    abs_rate = openmc.Tally(name='abs. rate')
    abs_rate.scores = ['absorption']
    tallies_file.append(abs_rate)

    # Resonance Escape Probability tallies
    therm_abs_rate = openmc.Tally(name='therm. abs. rate')
    therm_abs_rate.scores = ['absorption']
    therm_abs_rate.filters = [openmc.EnergyFilter([0., 0.625])]
    tallies_file.append(therm_abs_rate)

    # Thermal Flux Utilization tallies
    fuel_therm_abs_rate = openmc.Tally(name='fuel therm. abs. rate')
    fuel_therm_abs_rate.scores = ['absorption']
    fuel_therm_abs_rate.filters = [
        openmc.EnergyFilter([0., 0.625]),
        openmc.CellFilter([fuel_cell])
    ]
    tallies_file.append(fuel_therm_abs_rate)

    # Fast Fission Factor tallies
    therm_fiss_rate = openmc.Tally(name='therm. fiss. rate')
    therm_fiss_rate.scores = ['nu-fission']
    therm_fiss_rate.filters = [openmc.EnergyFilter([0., 0.625])]
    tallies_file.append(therm_fiss_rate)

    tallies_file.export_to_xml()

    #############################
    ###       PLOTTING        ###
    #############################
    p = openmc.Plot()
    p.filename = 'pinplot'
    p.width = (1.5 * pitch, 1.5 * pitch)
    p.pixels = (200, 200)
    p.color_by = 'material'
    p.colors = {uo2: 'yellow', water: 'blue'}

    plots = openmc.Plots([p])
    plots.export_to_xml()

    openmc.plot_geometry()
    pngstring = 'pinplot{}.png'.format(str(pitch))
    subprocess.call(['convert', 'pinplot.ppm', pngstring])
    subprocess.call(['mv', pngstring, 'figures/' + pngstring])

    #############################
    ###       EXECUTION       ###
    #############################
    openmc.run()
    sp = openmc.StatePoint('statepoint.{}.h5'.format(settings.batches))
    # Collect all the tallies
    fiss_rate = sp.get_tally(name='fiss. rate')
    fiss_rate_df = fiss_rate.get_pandas_dataframe()
    abs_rate = sp.get_tally(name='abs. rate')
    abs_rate_df = abs_rate.get_pandas_dataframe()
    therm_abs_rate = sp.get_tally(name='therm. abs. rate')
    therm_abs_rate_df = therm_abs_rate.get_pandas_dataframe()
    fuel_therm_abs_rate = sp.get_tally(name='fuel therm. abs. rate')
    fuel_therm_abs_rate_df = fuel_therm_abs_rate.get_pandas_dataframe()
    therm_fiss_rate = sp.get_tally(name='therm. fiss. rate')
    therm_fiss_rate_df = therm_fiss_rate.get_pandas_dataframe()

    # Compute k-infinity
    kinf = fiss_rate / abs_rate
    kinf_df = kinf.get_pandas_dataframe()

    # Compute resonance escape probability
    res_esc = (therm_abs_rate) / (abs_rate)
    res_esc_df = res_esc.get_pandas_dataframe()

    # Compute fast fission factor
    fast_fiss = fiss_rate / therm_fiss_rate
    fast_fiss_df = fast_fiss.get_pandas_dataframe()

    # Compute thermal flux utilization
    therm_util = fuel_therm_abs_rate / therm_abs_rate
    therm_util_df = therm_util.get_pandas_dataframe()

    # Compute neutrons produced per absorption
    eta = therm_fiss_rate / fuel_therm_abs_rate
    eta_df = eta.get_pandas_dataframe()

    columns = [
        'pitch', 'enrichment', 'kinf mean', 'kinf sd', 'res_esc mean',
        'res_esc sd', 'fast_fiss mean', 'fast_fiss sd', 'therm_util mean',
        'therm_util sd', 'eta mean', 'eta sd'
    ]
    data = [[
        pitch, enrichment, kinf_df['mean'][0], kinf_df['std. dev.'][0],
        res_esc_df['mean'][0], res_esc_df['std. dev.'][0],
        fast_fiss_df['mean'][0], fast_fiss_df['std. dev.'][0],
        therm_util_df['mean'][0], therm_util_df['std. dev.'][0],
        eta_df['mean'][0], eta_df['std. dev.'][0]
    ]]
    all_tallies = pd.DataFrame(data, columns=columns)

    return all_tallies
示例#20
0
# Get heating in a neutron-only calculation
tally = openmc.Tally(name='heating')
tally.filters = [
    openmc.MaterialFilter([fuel_31, helium, zirc4, ss304, agincd, water_600]),
    openmc.ParticleFilter(['neutron', 'photon', 'electron', 'positron'])
]
tally.scores = ['fission', 'heating-local']

total_tally = openmc.Tally(name='total')
total_tally.scores = ['fission', 'heating-local', 'heating']

model.tallies = openmc.Tallies([tally, total_tally])

sp_path = model.run()
with openmc.StatePoint(sp_path) as sp:
    t = sp.get_tally(name='heating')
    df_neutron = t.get_pandas_dataframe()

# Get heating in a coupled neutron-photon calculation
model.settings.photon_transport = True
model.settings.delayed_photon_scaling = True
model.tallies[0].scores = ['fission', 'heating']
sp_path = model.run()
with openmc.StatePoint(sp_path) as sp:
    t = sp.get_tally(name='heating')
    df_neutron_photon = t.get_pandas_dataframe()


def mev_per_fission(df, score):
    heating = df[df.score == score]
示例#21
0
def shield(rad, major, coil, bool, outer, m_batches, m_error, neutrons):

    #MATERIALS#

    min = coil
    max = outer+coil
    major_rad = major + outer

    R1 = rad[0]
    R2 = rad[1]

    mats = openmc.Materials()

    tungsten = openmc.Material(name='Tungsten carbide')
    tungsten.set_density('g/cm3', 15.63)
    tungsten.add_element('W', 1.0)
    tungsten.add_element('C', 1.0)
    mats.append(tungsten)

    water = openmc.Material(name='Water')
    water.set_density('g/cm3', 1.0)
    water.add_element('H', 2.0)
    water.add_element('O', 1.0)
    mats.append(water)

    copper = openmc.Material(name='Copper')
    copper.set_density('g/cm3', 8.5)
    copper.add_element('Cu', 1.0)
    mats.append(copper)

    eurofer = openmc.Material(name='EUROFER97')
    eurofer.set_density('g/cm3', 7.75)
    eurofer.add_element('Fe', 89.067, percent_type='wo')
    eurofer.add_element('C', 0.11, percent_type='wo')
    eurofer.add_element('Mn', 0.4, percent_type='wo')
    eurofer.add_element('Cr', 9.0, percent_type='wo')
    eurofer.add_element('Ta', 0.12, percent_type='wo')
    eurofer.add_element('W', 1.1, percent_type='wo')
    eurofer.add_element('N', 0.003, percent_type='wo')
    eurofer.add_element('V', 0.2, percent_type='wo')
    mats.append(eurofer)

    #GEOMETRY#

    cylinder = openmc.ZCylinder(R=min)

    shield1 = openmc.ZCylinder(R=R1)
    shield2 = openmc.ZCylinder(R=R2)
    shield3 = openmc.ZCylinder(R=max)
    top = major_rad-(max-min)
    shield_sph1 = openmc.Sphere(R=top)
    shield_sph2 = openmc.Sphere(R=major_rad-(max-min)+(max-R2))
    shield_sph3 = openmc.Sphere(R=major_rad-(max-min)+(max-R2)+(R2-R1))

    pit = sqrt(top**2+top**2)
    max_shield = sqrt(top**2+pit**2)+1

    vessel_in = openmc.Sphere(R=major_rad)
    vessel_out = openmc.Sphere(R=max_shield, boundary_type='vacuum')

    magnet = -cylinder & -vessel_in

    mat1 = -shield1 & +cylinder & -shield_sph3  #work on this
    mat2 = -shield2 & +shield1 & -shield_sph2 #work on this
    mat3 = -shield3 & +shield2 & -shield_sph1 #work on this

    plasma = +shield3 & -shield_sph1

    a = +shield_sph1 & -shield_sph2 & +shield2 #work on this
    b = +shield_sph2 & -shield_sph3 & +shield1 #work on this
    c = +shield_sph3 & -vessel_in & +cylinder #work on this

    vessel = +vessel_in & -vessel_out

    plasma_cell = openmc.Cell(region=plasma) #1

    cop_mag = openmc.Cell(region=magnet) #2
    cop_mag.fill = copper

    tung1 = openmc.Cell(region=mat1) #3
    tung1.fill = tungsten
    wat = openmc.Cell(region=mat2) #4
    wat.fill = water
    tung2 = openmc.Cell(region=mat3) #5
    tung2.fill = tungsten

    ste_ves = openmc.Cell(region=vessel) #6
    ste_ves.fill = eurofer

    tung_sph1 = openmc.Cell(region=a) #7
    tung_sph1.fill = tungsten
    wat_sph = openmc.Cell(region=b) #8
    wat_sph.fill = water
    tung_sph2 = openmc.Cell(region=c) #9
    tung_sph2.fill = tungsten

    root = openmc.Universe(cells=(plasma_cell, cop_mag, tung1, wat, tung2, ste_ves, tung_sph1, wat_sph, tung_sph2))
    geom = openmc.Geometry(root)
    root.plot(width=(600.0, 600.0), basis='xz')

    #SETTINGS#

    batch = 2
    max_batches = m_batches
    inactive = 0
    particles = neutrons

    source = openmc.Source()
    source.space = openmc.stats.Box((-top,-top,-top),(top,top,top))
    source.angle = openmc.stats.Isotropic()
    source.energy = openmc.stats.Discrete([14e6], [1])

    sett = openmc.Settings()
    sett.batches = batch
    sett.trigger_active = True
    sett.trigger_max_batches = m_batches
    sett.inactive = inactive
    sett.particles = particles
    sett.output = {'tallies': True}
    sett.run_mode = 'fixed source'
    sett.source = source

    #PLOT#

    plots = openmc.Plots()

    plot = openmc.Plot()
    #plot.type = 'voxel'
    plot.basis = 'xz'
    plot.origin = (0, 0, 0)
    plot.width = (600, 600)
    plot.pixels = (1000, 1000)
    plot.color_by = 'material'
    plot.colors = {tungsten: 'black', water: 'blue', eurofer: 'grey', copper: 'brown'}
    plots.append(plot)

    plots.export_to_xml()

    #TALLIES#

    tallies = openmc.Tallies()

    filter = openmc.CellFilter(cop_mag)

    tally = openmc.Tally(name='total')
    tally.scores = ['total']
    tally.filters = [filter]
    trigger = openmc.Trigger('rel_err', m_error/100)
    tally.triggers = [trigger]
    tallies.append(tally)

    model = openmc.model.Model(geom, mats, sett, tallies)

    #RUN#

    model.run(output=bool)

    for i in reversed(range(batch,max_batches+1)):
        filename = 'statepoint.' +str(i).zfill(len(str(max_batches)))+ '.h5'
        if os.path.isfile(filename):
            sp = openmc.StatePoint(filename)
            break

    #print('file:',filename)
    leakage = sp.get_tally(name='total')
    leakage_mean = leakage.mean[0][0][0]
    leakage_error = leakage.std_dev[0][0][0]
    #print(leakage_mean)
    #print(leakage_error)

    dir = '/home/emiralle/shield_git'
    for zippath in glob.iglob(os.path.join(dir, '*.h5')):
        os.remove(zippath)

    return leakage_mean, leakage_error
示例#22
0
    TallyId = int(TallyId)

if simname == None:
    simname = os.path.basename(input_dir)

if Nsamps == None:    
    Nsamps = np.sum([filename.startswith("statepoint.") for filename in os.listdir(input_dir)])
else:
    Nsamps = int(Nsamps)

if Nsamps == 0: raise Exception("No samples found")

#===============================
# Get energy of first simulation

sp1 = openmc.StatePoint(f'{input_dir}/statepoint.1.h5')
Tal = sp1.get_tally(id = TallyId).get_pandas_dataframe()

enHi = Tal['energy high [eV]']
enLo = Tal['energy low [eV]']


def get_samples(indecies, TallyId, statePointDir):
    index = indecies[0]
    try: 
        sp1 = openmc.StatePoint(f'{statePointDir}/statepoint.{index}.h5')
    except:
        sp1 = openmc.StatePoint(f'{statePointDir}/statepoint.{index-1}.h5')

    Tal = sp1.get_tally(id = TallyId).get_pandas_dataframe()
energy_bins = openmc.mgxs.GROUP_STRUCTURES['CCFE-709']
energy_filter = openmc.EnergyFilter(energy_bins)
spectra_tally = openmc.Tally(name='energy_spectra')
spectra_tally.scores = ['flux']
spectra_tally.filters = [cell_filter, photon_particle_filter, energy_filter]

tallies = openmc.Tallies()
tallies.append(spectra_tally)

# combine all the required parts to make a model
model = openmc.model.Model(geom, mats, sett, tallies)
# Run OpenMC!
results_filename = model.run()

# open the results file
results = openmc.StatePoint(results_filename)

#extracts the tally values from the simulation results
cell_tally = results.get_tally(name='energy_spectra')
cell_tally = cell_tally.get_pandas_dataframe()
cell_tally_values = cell_tally['mean']
cell_tally_std_dev = cell_tally['std. dev.']

# this section plots the results
fig = go.Figure()

# adds a line for the
fig.add_trace(
    go.Scatter(x=energy_bins,
               y=cell_tally_values + cell_tally_std_dev,
               line=dict(shape='hv', width=0)))
示例#24
0
def get_neutronics_results_from_statepoint_file(
        statepoint_filename: str,
        fusion_power: float = None):
    """Reads the statepoint file from the neutronics simulation
    and extracts the tally results.

    Arguments:
        statepoint_filename (str): The name of the statepoint file
        fusion_power (float): The fusion power of the reactor, which is used to
            scale some tallies. Defaults to None

    Returns:
        dict: a dictionary of the simulation results
    """

    try:
        import openmc
    except ImportError as err:
        raise err(
            'openmc not found, get_neutronics_results_from_statepoint_file \
            method is not available')

    # open the results file
    statepoint = openmc.StatePoint(statepoint_filename)

    results = defaultdict(dict)

    # access the tallies
    for tally in statepoint.tallies.values():

        if tally.name.endswith('TBR'):

            data_frame = tally.get_pandas_dataframe()
            tally_result = data_frame["mean"].sum()
            tally_std_dev = data_frame['std. dev.'].sum()
            results[tally.name] = {
                'result': tally_result,
                'std. dev.': tally_std_dev,
            }

        elif tally.name.endswith('heating'):

            data_frame = tally.get_pandas_dataframe()
            tally_result = data_frame["mean"].sum()
            tally_std_dev = data_frame['std. dev.'].sum()
            results[tally.name]['MeV per source particle'] = {
                'result': tally_result / 1e6,
                'std. dev.': tally_std_dev / 1e6,
            }

            if fusion_power is not None:
                results[tally.name]['Watts'] = {
                    'result': tally_result * 1.602176487e-19 * (fusion_power / ((17.58 * 1e6) / 6.2415090744e18)),
                    'std. dev.': tally_std_dev * 1.602176487e-19 * (fusion_power / ((17.58 * 1e6) / 6.2415090744e18)),
                }

        elif tally.name.endswith('flux'):

            data_frame = tally.get_pandas_dataframe()
            tally_result = data_frame["mean"].sum()
            tally_std_dev = data_frame['std. dev.'].sum()
            results[tally.name]['Flux per source particle'] = {
                'result': tally_result,
                'std. dev.': tally_std_dev,
            }

        elif tally.name.endswith('spectra'):
            data_frame = tally.get_pandas_dataframe()
            tally_result = data_frame["mean"]
            tally_std_dev = data_frame['std. dev.']
            results[tally.name]['Flux per source particle'] = {
                'energy': openmc.mgxs.GROUP_STRUCTURES['CCFE-709'].tolist(),
                'result': tally_result.tolist(),
                'std. dev.': tally_std_dev.tolist(),
            }

        elif '_on_2D_mesh' in tally.name:
            score = tally.name.split('_')[0]
            _save_2d_mesh_tally_as_png(
                score=score,
                tally=tally,
                filename=tally.name.replace(
                    '(',
                    '').replace(
                    ')',
                    '').replace(
                    ',',
                    '-'))

        elif '_on_3D_mesh' in tally.name:
            mesh_id = 1
            mesh = statepoint.meshes[mesh_id]

            xs = np.linspace(
                mesh.lower_left[0],
                mesh.upper_right[0],
                mesh.dimension[0] + 1
            )
            ys = np.linspace(
                mesh.lower_left[1],
                mesh.upper_right[1],
                mesh.dimension[1] + 1
            )
            zs = np.linspace(
                mesh.lower_left[2],
                mesh.upper_right[2],
                mesh.dimension[2] + 1
            )
            tally = statepoint.get_tally(name=tally.name)

            data = tally.mean[:, 0, 0]
            error = tally.std_dev[:, 0, 0]

            data = data.tolist()
            error = error.tolist()

            for content in [data, error]:
                for counter, i in enumerate(content):
                    if math.isnan(i):
                        content[counter] = 0.

            write_3d_mesh_tally_to_vtk(
                xs=xs,
                ys=ys,
                zs=zs,
                tally_label=tally.name,
                tally_data=data,
                error_data=error,
                outfile=tally.name.replace(
                    '(',
                    '').replace(
                    ')',
                    '').replace(
                    ',',
                    '-') +
                '.vtk')

        else:
            # this must be a standard score cell tally
            data_frame = tally.get_pandas_dataframe()
            tally_result = data_frame["mean"].sum()
            tally_std_dev = data_frame['std. dev.'].sum()
            results[tally.name]['events per source particle'] = {
                'result': tally_result,
                'std. dev.': tally_std_dev,
            }

    return results
示例#25
0
def make_geometry_tallies(batches, nps, inner_radius, thickness):

    first_wall_inner_surface = openmc.Sphere(r=inner_radius)
    first_wall_outer_surface = openmc.Sphere(r=inner_radius + thickness,
                                             boundary_type='vacuum')

    first_wall = +first_wall_inner_surface & -first_wall_outer_surface
    first_wall = openmc.Cell(region=first_wall)
    first_wall.fill = eurofer

    inner_vac_cell = -first_wall_inner_surface
    inner_vac_cell = openmc.Cell(region=inner_vac_cell)

    universe = openmc.Universe(cells=[first_wall, inner_vac_cell])
    geom = openmc.Geometry(universe)

    geom.export_to_xml('geometry')

    vox_plot = openmc.Plot()
    vox_plot.type = 'voxel'
    vox_plot.width = (10, 10, 10)
    vox_plot.pixels = (200, 200, 200)
    vox_plot.filename = 'plot_3d'
    vox_plot.color_by = 'material'
    vox_plot.colors = {eurofer: 'blue'}
    plots = openmc.Plots([vox_plot])
    plots.export_to_xml()

    openmc.plot_geometry()

    os.system('openmc-voxel-to-vtk plot_3d.h5 -o plot_3d.vti')
    os.system('paraview plot_3d.vti')

    sett = openmc.Settings()
    sett.batches = batches
    sett.inactive = 0
    sett.particles = nps
    sett.run_mode = 'fixed source'

    source = openmc.Source()
    source.space = openmc.stats.Point((0, 0, 0))
    source.angle = openmc.stats.Isotropic()
    source.energy = openmc.stats.Discrete([14.08e6], [1])
    #source.energy = openmc.stats.Muir(e0=14080000.0, m_rat=5.0, kt=20000.0)
    sett.source = source

    sett.export_to_xml('settings.xml')

    #tallies
    particle_filter = openmc.ParticleFilter([1])
    surface_filter_front = openmc.SurfaceFilter(first_wall_inner_surface)
    surface_filter_rear = openmc.SurfaceFilter(first_wall_outer_surface)
    bins = openmc.mgxs.GROUP_STRUCTURES['VITAMIN-J-175']
    #think will need to change this
    energy_filter = openmc.EnergyFilter(bins)

    tallies = openmc.Tallies()

    tally = openmc.Tally(name='wall_leakage')
    tally.filters = [surface_filter_rear, particle_filter]
    tally.scores = ['current']
    tallies.append(tally)

    tally = openmc.Tally(name='incident_neutron_spectrum')
    tally.filters = [surface_filter_rear, particle_filter, energy_filter]
    tally.scores = ['flux']
    tallies.append(tally)

    tally = openmc.Tally(name='leakage_neutron_spectrum')
    tally.filters = [surface_filter_front, particle_filter, energy_filter]
    tally.scores = ['flux']
    tallies.append(tally)

    model = openmc.model.Model(geom, mats, sett, tallies)
    model.run()

    sp = openmc.StatePoint('statepoint.' + str(batches) + '.h5')

    tallies_to_retrieve = ['wall_leakage']
    #at the moment, we only have one tally to retrieve, but we will set it up in a list anyway so we know how to do it
    for tally_name in tallies_to_retrieve:
        tally = sp.get_tally(name=tally_name)

        df = tally.get_pandas_dataframe()
        #defining something that stands for dataframe, need to investigate this
        #its basically something that we use to obtain the mean value and the std deviation value of the tally

        tally_result = df['mean'].sum()
        tally_std_dev = df['std. dev.'].sum()

        #for now, we will just try to print these values

    #get spectra

    spectra_tallies_to_retrieve = [
        'incident_neutron_spectrum', 'leakage_neutron_spectrum'
    ]
    for spectra_name in spectra_tallies_to_retrieve:
        spectra_tally = sp.get_tally(name=spectra_name)
        spectra_tally_result = [entry[0][0] for entry in spectra_tally.mean]
        spectra_tally_std_dev = [
            entry[0][0] for entry in spectra_tally.std_dev
        ]
示例#26
0
def test_activation(run_in_tmpdir, model, reaction_rate_mode,
                    reaction_rate_opts, tolerance):
    # Determine (n.gamma) reaction rate using initial run
    sp = model.run()
    with openmc.StatePoint(sp) as sp:
        tally = sp.tallies[1]
        capture_rate = tally.mean.flat[0]

    # Create one-nuclide depletion chain
    chain = openmc.deplete.Chain()
    w186 = openmc.deplete.Nuclide('W186')
    w186.add_reaction('(n,gamma)', None, 0.0, 1.0)
    chain.add_nuclide(w186)
    chain.export_to_xml('test_chain.xml')

    # Create transport operator
    op = openmc.deplete.Operator(
        model,
        'test_chain.xml',
        normalization_mode="source-rate",
        reaction_rate_mode=reaction_rate_mode,
        reaction_rate_opts=reaction_rate_opts,
    )

    # To determine the source rate necessary to reduce W186 density in half, we
    # start with the single-nuclide transmutation equation:
    #
    #                 dn/dt = -f * sigma * phi * n
    #                  n(t) = n0 * exp(-f * sigma * phi * t)
    #
    # where f is the source rate. The capture rate, r, is sigma * phi * n0,
    # meaning that:
    #
    #                  n(t) = n0 * exp(-f * r * t / n0)
    #
    # To reduce the density by half, we would need:
    #
    #               n(t)/n0 = exp(-f * r * t / n0) = 1/2
    #                     f = n0 / (r * t) ln(2)
    #
    # So we need to know the initial number of atoms (n0), the capture rate (r),
    # and choose an irradiation time (t)

    w = model.geometry.get_materials_by_name('tungsten')[0]
    atom_densities = w.get_nuclide_atom_densities()
    atom_per_cc = 1e24 * atom_densities['W186'][1]  # Density in atom/cm^3
    n0 = atom_per_cc * w.volume  # Absolute number of atoms

    # Pick a random irradiation time and then determine necessary source rate to
    # reduce material by half
    t = uniform(1.0, 5.0) * 86400
    source_rates = [n0 / (capture_rate * t) * log(2.0)]

    # Now activate the material
    integrator = openmc.deplete.PredictorIntegrator(op, [t],
                                                    source_rates=source_rates)
    integrator.integrate()

    # Get resulting number of atoms
    results = openmc.deplete.ResultsList.from_hdf5('depletion_results.h5')
    _, atoms = results.get_atoms(str(w.id), "W186")

    assert atoms[0] == pytest.approx(n0)
    assert atoms[1] / atoms[0] == pytest.approx(0.5, rel=tolerance)
示例#27
0
    def simulate_cylinder_cask_csg(self, material, source, height,
                                   outer_radius, thickness, batches,
                                   particles):
        """Makes a CSG cask geometry runs a simulation and returns the result"""

        mats = openmc.Materials([material])

        outer_cylinder = openmc.ZCylinder(r=outer_radius)
        inner_cylinder = openmc.ZCylinder(r=outer_radius - thickness)
        inner_top = openmc.ZPlane(z0=height * 0.5)
        inner_bottom = openmc.ZPlane(z0=-height * 0.5)
        outer_top = openmc.ZPlane(z0=(height * 0.5) + thickness)
        outer_bottom = openmc.ZPlane(z0=(-height * 0.5) - thickness)

        sphere_1 = openmc.Sphere(r=100, boundary_type='vacuum')

        cylinder_region = -outer_cylinder & +inner_cylinder & -inner_top & +inner_bottom
        cylinder_cell = openmc.Cell(region=cylinder_region)
        cylinder_cell.fill = material

        top_cap_region = -outer_top & +inner_top & -outer_cylinder
        top_cap_cell = openmc.Cell(region=top_cap_region)
        top_cap_cell.fill = material

        bottom_cap_region = +outer_bottom & -inner_bottom & -outer_cylinder
        bottom_cap_cell = openmc.Cell(region=bottom_cap_region)
        bottom_cap_cell.fill = material

        inner_void_region = -inner_cylinder & -inner_top & +inner_bottom
        inner_void_cell = openmc.Cell(region=inner_void_region)

        # sphere 1 region is below -sphere_1 and not (~) in the other regions
        sphere_1_region = -sphere_1
        sphere_1_cell = openmc.Cell(region=sphere_1_region
                                    & ~bottom_cap_region
                                    & ~top_cap_region
                                    & ~cylinder_region
                                    & ~inner_void_region)

        universe = openmc.Universe(cells=[
            inner_void_cell, cylinder_cell, top_cap_cell, bottom_cap_cell,
            sphere_1_cell
        ])

        geom = openmc.Geometry(universe)

        # Instantiate a Settings object
        sett = openmc.Settings()
        sett.batches = batches
        sett.particles = particles
        sett.inactive = 0
        sett.run_mode = 'fixed source'
        sett.photon_transport = True
        sett.source = source

        cell_filter = openmc.CellFilter(
            [cylinder_cell, top_cap_cell, bottom_cap_cell])

        tally = openmc.Tally(name='csg_heating')
        tally.filters = [cell_filter]
        tally.scores = ['heating']
        tallies = openmc.Tallies()
        tallies.append(tally)

        model = openmc.model.Model(geom, mats, sett, tallies)
        sp_filename = model.run()

        # open the results file
        results = openmc.StatePoint(sp_filename)

        # access the tally using pandas dataframes
        tally = results.get_tally(name='csg_heating')
        tally_df = tally.get_pandas_dataframe()

        return tally_df['mean'].sum()
示例#28
0
文件: test.py 项目: smharper/openmc
def test_full(run_in_tmpdir, problem, multiproc):
    """Full system test suite.

    Runs an entire OpenMC simulation with depletion coupling and verifies
    that the outputs match a reference file.  Sensitive to changes in
    OpenMC.

    This test runs a complete OpenMC simulation and tests the outputs.
    It will take a while.

    """

    geometry, lower_left, upper_right = problem

    # OpenMC-specific settings
    settings = openmc.Settings()
    settings.particles = 100
    settings.batches = 10
    settings.inactive = 0
    space = openmc.stats.Box(lower_left, upper_right)
    settings.source = openmc.Source(space=space)
    settings.seed = 1
    settings.verbosity = 1

    # Create operator
    chain_file = Path(__file__).parents[2] / 'chain_simple.xml'
    op = openmc.deplete.Operator(geometry, settings, chain_file)
    op.round_number = True

    # Power and timesteps
    dt1 = 15. * 24 * 60 * 60  # 15 days
    dt2 = 1.5 * 30 * 24 * 60 * 60  # 1.5 months
    N = floor(dt2 / dt1)
    dt = np.full(N, dt1)
    power = 2.337e15 * 4 * JOULE_PER_EV * 1e6  # MeV/second cm from CASMO

    # Perform simulation using the predictor algorithm
    openmc.deplete.pool.USE_MULTIPROCESSING = multiproc
    openmc.deplete.PredictorIntegrator(op, dt, power).integrate()

    # Get path to test and reference results
    path_test = op.output_dir / 'depletion_results.h5'
    path_reference = Path(__file__).with_name('test_reference.h5')

    # If updating results, do so and return
    if config['update']:
        shutil.copyfile(str(path_test), str(path_reference))
        return

    # Load the reference/test results
    res_test = openmc.deplete.ResultsList.from_hdf5(path_test)
    res_ref = openmc.deplete.ResultsList.from_hdf5(path_reference)

    # Assert same mats
    for mat in res_ref[0].mat_to_ind:
        assert mat in res_test[0].mat_to_ind, \
            "Material {} not in new results.".format(mat)
    for nuc in res_ref[0].nuc_to_ind:
        assert nuc in res_test[0].nuc_to_ind, \
            "Nuclide {} not in new results.".format(nuc)

    for mat in res_test[0].mat_to_ind:
        assert mat in res_ref[0].mat_to_ind, \
            "Material {} not in old results.".format(mat)
    for nuc in res_test[0].nuc_to_ind:
        assert nuc in res_ref[0].nuc_to_ind, \
            "Nuclide {} not in old results.".format(nuc)

    tol = 1.0e-6
    for mat in res_test[0].mat_to_ind:
        for nuc in res_test[0].nuc_to_ind:
            _, y_test = res_test.get_atoms(mat, nuc)
            _, y_old = res_ref.get_atoms(mat, nuc)

            # Test each point
            correct = True
            for i, ref in enumerate(y_old):
                if ref != y_test[i]:
                    if ref != 0.0:
                        correct = np.abs(y_test[i] - ref) / ref <= tol
                    else:
                        correct = False

            assert correct, "Discrepancy in mat {} and nuc {}\n{}\n{}".format(
                mat, nuc, y_old, y_test)

    # Compare statepoint files with depletion results

    t_test, k_test = res_test.get_eigenvalue()
    t_ref, k_ref = res_ref.get_eigenvalue()
    k_state = np.empty_like(k_ref)

    n_tallies = np.empty(N + 1, dtype=int)

    # Get statepoint files for all BOS points and EOL
    for n in range(N + 1):
        statepoint = openmc.StatePoint("openmc_simulation_n{}.h5".format(n))
        k_n = statepoint.k_combined
        k_state[n] = [k_n.nominal_value, k_n.std_dev]
        n_tallies[n] = len(statepoint.tallies)
    # Look for exact match pulling from statepoint and depletion_results
    assert np.all(k_state == k_test)
    assert np.allclose(k_test, k_ref)

    # Check that no additional tallies are loaded from the files
    assert np.all(n_tallies == 0)
示例#29
0
# added a cell tally for tritium production
cell_filter = openmc.CellFilter(breeder_blanket_cell)
tbr_tally = openmc.Tally(name='TBR')
tbr_tally.filters = [cell_filter]
tbr_tally.scores = [
    '(n,Xt)'
]  # MT 205 is the (n,Xt) reaction where X is a wildcard, if MT 105 or (n,t) then some tritium production will be missed, for example (n,nt) which happens in Li7 would be missed
tallies.append(tbr_tally)

# Run OpenMC!
model = openmc.model.Model(geom, mats, sett, tallies)
sp_filename = model.run()

# open the results file
sp = openmc.StatePoint(sp_filename)

# access the tally using pandas dataframes
tbr_tally = sp.get_tally(name='TBR')
df = tbr_tally.get_pandas_dataframe()

tbr_tally_result = df['mean'].sum()
tbr_tally_std_dev = df['std. dev.'].sum()

# print results
print('The tritium breeding ratio was found, TBR = ', tbr_tally_result)
print('error on the tbr tally is ', tbr_tally_std_dev)

# output results to json file
json_output = {'TBR': tbr_tally_result, 'TBR_std_dev': tbr_tally_std_dev}
with open('simulation_results.json', 'w') as file_object:
示例#30
0
simDir = Path.cwd()

Nfiles = 500

SIMNAME1 = "endfFe"
SIMNAME2 = "tendlFe"
statePointDirSandy = simDir / f"statepoints-{SIMNAME1}"
statePointDirTendl = simDir / f"statepoints-{SIMNAME2}"

##
#   Plotting stuff
##

index = 1
sp1 = openmc.StatePoint(f'{statePointDirSandy}/statepoint.{index}.h5')

Tal = sp1.get_tally(id=TallyId).get_pandas_dataframe()

enHi = Tal['energy high [eV]']
enLo = Tal['energy low [eV]']

widths = (enHi - enLo)

leth = 1
surf = 1

if useLeth: leth = abs(np.log(widths) * (widths > 1))
if useSurf: surf = np.pi * 4 * r**2

means = np.array(Tal['mean'])