From 978c5421652dd49508da7755b38cabfca66e3d74 Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Thu, 14 Oct 2021 10:42:27 +0100 Subject: [PATCH 01/16] changing bb arg from None to required --- openmc_dagmc_wrapper/Tally.py | 66 ++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index 901dc51..8b66889 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -1,4 +1,4 @@ -from typing import Union +from typing import List, Tuple, Union import dagmc_h5m_file_inspector as di import openmc @@ -6,6 +6,7 @@ from openmc.data import REACTION_MT, REACTION_NAME from openmc_dagmc_wrapper import Materials + from .utils import find_bounding_box @@ -161,12 +162,7 @@ class CellTallies: h5m_filename """ - def __init__( - self, - tally_types, - targets=[None], - materials=None, - h5m_filename=None): + def __init__(self, tally_types, targets=[None], materials=None, h5m_filename=None): self.tallies = [] self.tally_types = tally_types self.targets = targets @@ -183,10 +179,8 @@ def __init__( for score in self.tally_types: for target in all_targets: self.tallies.append( - CellTally( - tally_type=score, - target=target, - materials=materials)) + CellTally(tally_type=score, target=target, materials=materials) + ) class TetMeshTally(Tally): @@ -238,22 +232,19 @@ def __init__(self, tally_types, filenames): self.tally_types = tally_types for score in self.tally_types: for filename in filenames: - self.tallies.append( - TetMeshTally( - tally_type=score, - filename=filename)) + self.tallies.append(TetMeshTally(tally_type=score, filename=filename)) class MeshTally3D(Tally): def __init__( - self, - tally_type, - mesh_resolution=( - 100, - 100, - 100), - bounding_box=None, - **kwargs): + self, + tally_type: str, + bounding_box: Union[ + str, List[Tuple(float, float, float), Tuple(float, float, float)] + ], + mesh_resolution=(100, 100, 100), + **kwargs + ): self.tally_type = tally_type self.mesh_resolution = mesh_resolution super().__init__(tally_type, **kwargs) @@ -287,7 +278,12 @@ class MeshTallies3D: """ def __init__( - self, tally_types, meshes_resolution=(100, 100, 100), bounding_box=None + self, + tally_types: str, + bounding_box: Union[ + str, List[Tuple(float, float, float), Tuple(float, float, float)] + ], + meshes_resolution: Tuple(float, float, float) = (100, 100, 100), ): self.tallies = [] self.tally_types = tally_types @@ -313,7 +309,13 @@ class MeshTally2D(Tally): """ def __init__( - self, tally_type, plane, mesh_resolution=(400, 400), bounding_box=None + self, + tally_type: str, + plane: str, + bounding_box: Union[ + str, List[Tuple(float, float, float), Tuple(float, float, float)] + ], + mesh_resolution: Tuple[float, float] = (400, 400), ): self.tally_type = tally_type self.plane = plane @@ -426,10 +428,12 @@ class MeshTallies2D: def __init__( self, - tally_types, - planes, - meshes_resolution=(400, 400), - bounding_box=None, + tally_types: str, + planes: str, + bounding_box: Union[ + str, List[Tuple(float, float, float), Tuple(float, float, float)] + ], + meshes_resolution: Tuple[float, float] = (400, 400), ): self.tallies = [] self.tally_types = tally_types @@ -490,9 +494,7 @@ def compute_filters(tally_type): energy_function_filter_n = openmc.EnergyFunctionFilter( energy_bins_n, dose_coeffs_n ) - additional_filters = [ - neutron_particle_filter, - energy_function_filter_n] + additional_filters = [neutron_particle_filter, energy_function_filter_n] elif tally_type == "photon_effective_dose": energy_function_filter_p = openmc.EnergyFunctionFilter( energy_bins_p, dose_coeffs_p From 5bc8e86fd16c0926b0c91362b5f646345254082f Mon Sep 17 00:00:00 2001 From: autopep8 Date: Thu, 14 Oct 2021 09:44:19 +0000 Subject: [PATCH 02/16] Automated autopep8 fixes --- openmc_dagmc_wrapper/Tally.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index 8b66889..d978eb0 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -162,7 +162,12 @@ class CellTallies: h5m_filename """ - def __init__(self, tally_types, targets=[None], materials=None, h5m_filename=None): + def __init__( + self, + tally_types, + targets=[None], + materials=None, + h5m_filename=None): self.tallies = [] self.tally_types = tally_types self.targets = targets @@ -179,8 +184,10 @@ def __init__(self, tally_types, targets=[None], materials=None, h5m_filename=Non for score in self.tally_types: for target in all_targets: self.tallies.append( - CellTally(tally_type=score, target=target, materials=materials) - ) + CellTally( + tally_type=score, + target=target, + materials=materials)) class TetMeshTally(Tally): @@ -232,7 +239,10 @@ def __init__(self, tally_types, filenames): self.tally_types = tally_types for score in self.tally_types: for filename in filenames: - self.tallies.append(TetMeshTally(tally_type=score, filename=filename)) + self.tallies.append( + TetMeshTally( + tally_type=score, + filename=filename)) class MeshTally3D(Tally): @@ -494,7 +504,9 @@ def compute_filters(tally_type): energy_function_filter_n = openmc.EnergyFunctionFilter( energy_bins_n, dose_coeffs_n ) - additional_filters = [neutron_particle_filter, energy_function_filter_n] + additional_filters = [ + neutron_particle_filter, + energy_function_filter_n] elif tally_type == "photon_effective_dose": energy_function_filter_p = openmc.EnergyFunctionFilter( energy_bins_p, dose_coeffs_p From c863ddb85895aff919627733f0d998bd460999f0 Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Thu, 14 Oct 2021 11:20:03 +0100 Subject: [PATCH 03/16] corrected type hinting format --- openmc_dagmc_wrapper/Tally.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index 8b66889..f09518f 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -281,7 +281,7 @@ def __init__( self, tally_types: str, bounding_box: Union[ - str, List[Tuple(float, float, float), Tuple(float, float, float)] + str, List[Tuple[float, float, float], Tuple[float, float, float]] ], meshes_resolution: Tuple(float, float, float) = (100, 100, 100), ): @@ -431,7 +431,7 @@ def __init__( tally_types: str, planes: str, bounding_box: Union[ - str, List[Tuple(float, float, float), Tuple(float, float, float)] + str, List[Tuple[float, float, float], Tuple[float, float, float]] ], meshes_resolution: Tuple[float, float] = (400, 400), ): From 8286e5bc8cf0ca79f986cb7c2e413fd5de400589 Mon Sep 17 00:00:00 2001 From: autopep8 Date: Thu, 14 Oct 2021 10:23:14 +0000 Subject: [PATCH 04/16] Automated autopep8 fixes --- openmc_dagmc_wrapper/Tally.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index 6c0a2bf..2331ebf 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -153,7 +153,11 @@ class CellTallies: target=["Be", 2], materials=my_mats ) - my_tallies = odw.CellTallies(tally_types=['TBR', "neutron_flux"], target=[2]) + my_tallies = odw.CellTallies( + tally_types=[ + 'TBR', + "neutron_flux"], + target=[2]) Args: tally_types ([type]): [description] @@ -293,7 +297,7 @@ def __init__( bounding_box: Union[ str, List[Tuple[float], Tuple[float]] ], - meshes_resolution:[Tuple(float, float, float] = (100, 100, 100), + meshes_resolution: [Tuple(float, float, float]=(100, 100, 100), ): self.tallies = [] self.tally_types = tally_types @@ -325,7 +329,7 @@ def __init__( bounding_box: Union[ str, List[Tuple[float], Tuple[float]] ], - mesh_resolution: Tuple[float, float] = (400, 400), + mesh_resolution: Tuple[float, float]=(400, 400), ): self.tally_type = tally_type self.plane = plane @@ -443,7 +447,7 @@ def __init__( bounding_box: Union[ str, List[Tuple[float], Tuple[float]] ], - meshes_resolution: Tuple[float, float] = (400, 400), + meshes_resolution: Tuple[float, float]=(400, 400), ): self.tallies = [] self.tally_types = tally_types @@ -460,18 +464,18 @@ def __init__( def compute_filters(tally_type): - energy_bins_n, dose_coeffs_n = openmc.data.dose_coefficients( + energy_bins_n, dose_coeffs_n=openmc.data.dose_coefficients( particle="neutron", geometry="ISO", ) - energy_bins_p, dose_coeffs_p = openmc.data.dose_coefficients( + energy_bins_p, dose_coeffs_p=openmc.data.dose_coefficients( particle="photon", geometry="ISO", ) - photon_particle_filter = openmc.ParticleFilter(["photon"]) - neutron_particle_filter = openmc.ParticleFilter(["neutron"]) + photon_particle_filter=openmc.ParticleFilter(["photon"]) + neutron_particle_filter=openmc.ParticleFilter(["neutron"]) - additional_filters = [] + additional_filters=[] if tally_type == "neutron_flux": additional_filters = [neutron_particle_filter] elif tally_type == "photon_flux": From a7392a489a9b198341ee9180c8dcc8411f2c25a7 Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Thu, 14 Oct 2021 11:26:33 +0100 Subject: [PATCH 05/16] corrected type hinting format --- openmc_dagmc_wrapper/Tally.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index 6c0a2bf..c4cc744 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -293,7 +293,7 @@ def __init__( bounding_box: Union[ str, List[Tuple[float], Tuple[float]] ], - meshes_resolution:[Tuple(float, float, float] = (100, 100, 100), + meshes_resolution: Tuple[float] = (100, 100, 100), ): self.tallies = [] self.tally_types = tally_types From f140fb21b05093e1836b2f866608748cb986b878 Mon Sep 17 00:00:00 2001 From: autopep8 Date: Thu, 14 Oct 2021 10:27:49 +0000 Subject: [PATCH 06/16] Automated autopep8 fixes --- openmc_dagmc_wrapper/Tally.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index a601aa1..6d66808 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -329,7 +329,7 @@ def __init__( bounding_box: Union[ str, List[Tuple[float], Tuple[float]] ], - mesh_resolution: Tuple[float, float]=(400, 400), + mesh_resolution: Tuple[float, float] = (400, 400), ): self.tally_type = tally_type self.plane = plane @@ -447,7 +447,7 @@ def __init__( bounding_box: Union[ str, List[Tuple[float], Tuple[float]] ], - meshes_resolution: Tuple[float, float]=(400, 400), + meshes_resolution: Tuple[float, float] = (400, 400), ): self.tallies = [] self.tally_types = tally_types @@ -464,18 +464,18 @@ def __init__( def compute_filters(tally_type): - energy_bins_n, dose_coeffs_n=openmc.data.dose_coefficients( + energy_bins_n, dose_coeffs_n = openmc.data.dose_coefficients( particle="neutron", geometry="ISO", ) - energy_bins_p, dose_coeffs_p=openmc.data.dose_coefficients( + energy_bins_p, dose_coeffs_p = openmc.data.dose_coefficients( particle="photon", geometry="ISO", ) - photon_particle_filter=openmc.ParticleFilter(["photon"]) - neutron_particle_filter=openmc.ParticleFilter(["neutron"]) + photon_particle_filter = openmc.ParticleFilter(["photon"]) + neutron_particle_filter = openmc.ParticleFilter(["neutron"]) - additional_filters=[] + additional_filters = [] if tally_type == "neutron_flux": additional_filters = [neutron_particle_filter] elif tally_type == "photon_flux": From d77e0b941d3271e8778dfec8d2d24f7f40730ece Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Thu, 14 Oct 2021 11:42:18 +0100 Subject: [PATCH 07/16] corrected type hinting format --- openmc_dagmc_wrapper/Tally.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index a601aa1..78688c3 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -254,7 +254,7 @@ def __init__( self, tally_type: str, bounding_box: Union[ - str, List[Tuple[float], Tuple[float]] + str, List[Tuple[float]] ], mesh_resolution=(100, 100, 100), **kwargs @@ -295,7 +295,7 @@ def __init__( self, tally_types: str, bounding_box: Union[ - str, List[Tuple[float], Tuple[float]] + str, List[Tuple[float]] ], meshes_resolution: Tuple[float] = (100, 100, 100), ): @@ -327,7 +327,7 @@ def __init__( tally_type: str, plane: str, bounding_box: Union[ - str, List[Tuple[float], Tuple[float]] + str, List[Tuple[float]] ], mesh_resolution: Tuple[float, float]=(400, 400), ): @@ -445,9 +445,9 @@ def __init__( tally_types: str, planes: str, bounding_box: Union[ - str, List[Tuple[float], Tuple[float]] + str, List[Tuple[float]] ], - meshes_resolution: Tuple[float, float]=(400, 400), + meshes_resolution: Tuple[float, float] = (400, 400), ): self.tallies = [] self.tally_types = tally_types From 34433efba666b735f33f47a64a77c6cf6680b340 Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Thu, 14 Oct 2021 12:12:30 +0100 Subject: [PATCH 08/16] added bb arg to function calls --- openmc_dagmc_wrapper/Tally.py | 38 ++++++------------------ tests/test_tallies/test_cell_tallies.py | 4 +-- tests/test_tallies/test_mesh_tally_2d.py | 25 ++++++++-------- tests/test_tallies/test_mesh_tally_3d.py | 17 +++++------ 4 files changed, 32 insertions(+), 52 deletions(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index d3ef8ab..d2a79ff 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -166,12 +166,7 @@ class CellTallies: h5m_filename """ - def __init__( - self, - tally_types, - targets=[None], - materials=None, - h5m_filename=None): + def __init__(self, tally_types, targets=[None], materials=None, h5m_filename=None): self.tallies = [] self.tally_types = tally_types self.targets = targets @@ -188,10 +183,8 @@ def __init__( for score in self.tally_types: for target in all_targets: self.tallies.append( - CellTally( - tally_type=score, - target=target, - materials=materials)) + CellTally(tally_type=score, target=target, materials=materials) + ) class TetMeshTally(Tally): @@ -243,19 +236,14 @@ def __init__(self, tally_types, filenames): self.tally_types = tally_types for score in self.tally_types: for filename in filenames: - self.tallies.append( - TetMeshTally( - tally_type=score, - filename=filename)) + self.tallies.append(TetMeshTally(tally_type=score, filename=filename)) class MeshTally3D(Tally): def __init__( self, tally_type: str, - bounding_box: Union[ - str, List[Tuple[float]] - ], + bounding_box: Union[str, List[Tuple[float]]], mesh_resolution=(100, 100, 100), **kwargs ): @@ -294,9 +282,7 @@ class MeshTallies3D: def __init__( self, tally_types: str, - bounding_box: Union[ - str, List[Tuple[float]] - ], + bounding_box: Union[str, List[Tuple[float]]], meshes_resolution: Tuple[float] = (100, 100, 100), ): self.tallies = [] @@ -326,9 +312,7 @@ def __init__( self, tally_type: str, plane: str, - bounding_box: Union[ - str, List[Tuple[float]] - ], + bounding_box: Union[str, List[Tuple[float]]], mesh_resolution: Tuple[float, float] = (400, 400), ): self.tally_type = tally_type @@ -444,9 +428,7 @@ def __init__( self, tally_types: str, planes: str, - bounding_box: Union[ - str, List[Tuple[float]] - ], + bounding_box: Union[str, List[Tuple[float]]], meshes_resolution: Tuple[float, float] = (400, 400), ): self.tallies = [] @@ -508,9 +490,7 @@ def compute_filters(tally_type): energy_function_filter_n = openmc.EnergyFunctionFilter( energy_bins_n, dose_coeffs_n ) - additional_filters = [ - neutron_particle_filter, - energy_function_filter_n] + additional_filters = [neutron_particle_filter, energy_function_filter_n] elif tally_type == "photon_effective_dose": energy_function_filter_p = openmc.EnergyFunctionFilter( energy_bins_p, dose_coeffs_p diff --git a/tests/test_tallies/test_cell_tallies.py b/tests/test_tallies/test_cell_tallies.py index aed9489..36f4346 100644 --- a/tests/test_tallies/test_cell_tallies.py +++ b/tests/test_tallies/test_cell_tallies.py @@ -9,9 +9,9 @@ class TestCellTallies(unittest.TestCase): """Tests the CellTallies class functionality""" def test_name(self): - my_tally = odw.CellTally('heating', target=1) + my_tally = odw.CellTally("heating", target=1) assert my_tally.name == "1_heating" - my_tally = odw.CellTally('heating', target="coucou", materials=[]) + my_tally = odw.CellTally("heating", target="coucou", materials=[]) assert my_tally.name == "coucou_heating" diff --git a/tests/test_tallies/test_mesh_tally_2d.py b/tests/test_tallies/test_mesh_tally_2d.py index 5981523..78c3716 100644 --- a/tests/test_tallies/test_mesh_tally_2d.py +++ b/tests/test_tallies/test_mesh_tally_2d.py @@ -1,4 +1,3 @@ - import tarfile import unittest import urllib.request @@ -28,14 +27,18 @@ def setUp(self): def test_incorrect_mesh_tally_2d(self): """Set a mesh_tally_2d that is not accepted which should raise an error""" + def incorrect_mesh_tally_2d(): - odw.MeshTally2D("coucou", plane="xy") + odw.MeshTally2D( + "coucou", bounding_box=[(10, 10, 10), (-10, -10, -10)], plane="xy" + ) self.assertRaises(ValueError, incorrect_mesh_tally_2d) def test_incorrect_mesh_tally_2d_type(self): """Set a mesh_tally_2d that is the wrong type which should raise an error""" + def incorrect_mesh_tally_2d_type(): odw.MeshTally2D(1, plane="xy") @@ -56,19 +59,19 @@ def test_shape_of_resulting_png(self): tally_type="neutron_flux", plane="xy", bounding_box=self.h5m_filename_smaller, - mesh_resolution=(10, 200) + mesh_resolution=(10, 200), ) tally2 = odw.MeshTally2D( tally_type="neutron_flux", plane="xz", bounding_box=self.h5m_filename_smaller, - mesh_resolution=(20, 100) + mesh_resolution=(20, 100), ) tally3 = odw.MeshTally2D( tally_type="neutron_flux", plane="yz", bounding_box=self.h5m_filename_smaller, - mesh_resolution=(30, 500) + mesh_resolution=(30, 500), ) tallies = openmc.Tallies([tally1, tally2, tally3]) @@ -80,14 +83,12 @@ def test_shape_of_resulting_png(self): settings.source = FusionRingSource(fuel="DT", radius=1) my_model = openmc.Model( - materials=materials, - geometry=geometry, - settings=settings, - tallies=tallies) + materials=materials, geometry=geometry, settings=settings, tallies=tallies + ) statepoint_file = my_model.run() odw.process_results(statepoint_file, fusion_power=1e9) - assert Path('neutron_flux_on_2D_mesh_xy.png').exists() - assert Path('neutron_flux_on_2D_mesh_xz.png').exists() - assert Path('neutron_flux_on_2D_mesh_yz.png').exists() + assert Path("neutron_flux_on_2D_mesh_xy.png").exists() + assert Path("neutron_flux_on_2D_mesh_xz.png").exists() + assert Path("neutron_flux_on_2D_mesh_yz.png").exists() diff --git a/tests/test_tallies/test_mesh_tally_3d.py b/tests/test_tallies/test_mesh_tally_3d.py index f0fa27c..c02b24a 100644 --- a/tests/test_tallies/test_mesh_tally_3d.py +++ b/tests/test_tallies/test_mesh_tally_3d.py @@ -1,4 +1,3 @@ - import tarfile import unittest import urllib.request @@ -29,7 +28,7 @@ def test_incorrect_mesh_tally_3d(self): error""" def incorrect_mesh_tally_3d(): - odw.MeshTally3D("coucou") + odw.MeshTally3D("coucou", bounding_box=[(10, 10, 10), (-10, -10, -10)]) self.assertRaises(ValueError, incorrect_mesh_tally_3d) @@ -38,7 +37,7 @@ def test_incorrect_mesh_tally_3d_type(self): error""" def incorrect_mesh_tally_3d_type(): - odw.MeshTally3D(1) + odw.MeshTally3D(1, bounding_box=[(10, 10, 10), (-10, -10, -10)]) self.assertRaises(TypeError, incorrect_mesh_tally_3d_type) @@ -51,15 +50,15 @@ def test_meshfilter_from_h5m_file(self): expected_mesh.dimension = (100, 100, 100) # run - my_tally = odw.MeshTally3D( - "heating", bounding_box=self.h5m_filename_smaller) + my_tally = odw.MeshTally3D("heating", bounding_box=self.h5m_filename_smaller) produced_filter = my_tally.filters[-1] produced_mesh = produced_filter.mesh # test assert produced_mesh.lower_left == expected_mesh.lower_left assert produced_mesh.upper_right == expected_mesh.upper_right for produced_index, expected_index in zip( - produced_mesh.indices, expected_mesh.indices): + produced_mesh.indices, expected_mesh.indices + ): assert produced_index == expected_index def test_meshfilter_from_custom_mesh(self): @@ -71,15 +70,15 @@ def test_meshfilter_from_custom_mesh(self): expected_mesh.dimension = (100, 100, 100) # run - my_tally = odw.MeshTally3D( - "heating", bounding_box=bbox) + my_tally = odw.MeshTally3D("heating", bounding_box=bbox) produced_filter = my_tally.filters[-1] produced_mesh = produced_filter.mesh # test assert produced_mesh.lower_left == expected_mesh.lower_left assert produced_mesh.upper_right == expected_mesh.upper_right for produced_index, expected_index in zip( - produced_mesh.indices, expected_mesh.indices): + produced_mesh.indices, expected_mesh.indices + ): assert produced_index == expected_index From 41c3c7bae6e31b7c495c487111a0632dcd09841d Mon Sep 17 00:00:00 2001 From: autopep8 Date: Thu, 14 Oct 2021 11:12:47 +0000 Subject: [PATCH 09/16] Automated autopep8 fixes --- openmc_dagmc_wrapper/Tally.py | 22 +++++++++++++++++----- tests/test_tallies/test_mesh_tally_2d.py | 10 ++++++---- tests/test_tallies/test_mesh_tally_3d.py | 7 +++++-- 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/openmc_dagmc_wrapper/Tally.py b/openmc_dagmc_wrapper/Tally.py index d2a79ff..ed11173 100644 --- a/openmc_dagmc_wrapper/Tally.py +++ b/openmc_dagmc_wrapper/Tally.py @@ -166,7 +166,12 @@ class CellTallies: h5m_filename """ - def __init__(self, tally_types, targets=[None], materials=None, h5m_filename=None): + def __init__( + self, + tally_types, + targets=[None], + materials=None, + h5m_filename=None): self.tallies = [] self.tally_types = tally_types self.targets = targets @@ -183,8 +188,10 @@ def __init__(self, tally_types, targets=[None], materials=None, h5m_filename=Non for score in self.tally_types: for target in all_targets: self.tallies.append( - CellTally(tally_type=score, target=target, materials=materials) - ) + CellTally( + tally_type=score, + target=target, + materials=materials)) class TetMeshTally(Tally): @@ -236,7 +243,10 @@ def __init__(self, tally_types, filenames): self.tally_types = tally_types for score in self.tally_types: for filename in filenames: - self.tallies.append(TetMeshTally(tally_type=score, filename=filename)) + self.tallies.append( + TetMeshTally( + tally_type=score, + filename=filename)) class MeshTally3D(Tally): @@ -490,7 +500,9 @@ def compute_filters(tally_type): energy_function_filter_n = openmc.EnergyFunctionFilter( energy_bins_n, dose_coeffs_n ) - additional_filters = [neutron_particle_filter, energy_function_filter_n] + additional_filters = [ + neutron_particle_filter, + energy_function_filter_n] elif tally_type == "photon_effective_dose": energy_function_filter_p = openmc.EnergyFunctionFilter( energy_bins_p, dose_coeffs_p diff --git a/tests/test_tallies/test_mesh_tally_2d.py b/tests/test_tallies/test_mesh_tally_2d.py index 78c3716..baab124 100644 --- a/tests/test_tallies/test_mesh_tally_2d.py +++ b/tests/test_tallies/test_mesh_tally_2d.py @@ -30,8 +30,8 @@ def test_incorrect_mesh_tally_2d(self): def incorrect_mesh_tally_2d(): odw.MeshTally2D( - "coucou", bounding_box=[(10, 10, 10), (-10, -10, -10)], plane="xy" - ) + "coucou", bounding_box=[ + (10, 10, 10), (-10, -10, -10)], plane="xy") self.assertRaises(ValueError, incorrect_mesh_tally_2d) @@ -83,8 +83,10 @@ def test_shape_of_resulting_png(self): settings.source = FusionRingSource(fuel="DT", radius=1) my_model = openmc.Model( - materials=materials, geometry=geometry, settings=settings, tallies=tallies - ) + materials=materials, + geometry=geometry, + settings=settings, + tallies=tallies) statepoint_file = my_model.run() odw.process_results(statepoint_file, fusion_power=1e9) diff --git a/tests/test_tallies/test_mesh_tally_3d.py b/tests/test_tallies/test_mesh_tally_3d.py index c02b24a..f3e6b0f 100644 --- a/tests/test_tallies/test_mesh_tally_3d.py +++ b/tests/test_tallies/test_mesh_tally_3d.py @@ -28,7 +28,9 @@ def test_incorrect_mesh_tally_3d(self): error""" def incorrect_mesh_tally_3d(): - odw.MeshTally3D("coucou", bounding_box=[(10, 10, 10), (-10, -10, -10)]) + odw.MeshTally3D( + "coucou", bounding_box=[ + (10, 10, 10), (-10, -10, -10)]) self.assertRaises(ValueError, incorrect_mesh_tally_3d) @@ -50,7 +52,8 @@ def test_meshfilter_from_h5m_file(self): expected_mesh.dimension = (100, 100, 100) # run - my_tally = odw.MeshTally3D("heating", bounding_box=self.h5m_filename_smaller) + my_tally = odw.MeshTally3D( + "heating", bounding_box=self.h5m_filename_smaller) produced_filter = my_tally.filters[-1] produced_mesh = produced_filter.mesh # test From 9c7b4fc57bd60f13aba2693b7889d9b49235c48e Mon Sep 17 00:00:00 2001 From: Jonathan Date: Thu, 14 Oct 2021 22:50:39 +0100 Subject: [PATCH 10/16] added 3* radius to ensure graveyard is larger than geometry --- openmc_dagmc_wrapper/Geometry.py | 39 ++++++++------------------------ 1 file changed, 10 insertions(+), 29 deletions(-) diff --git a/openmc_dagmc_wrapper/Geometry.py b/openmc_dagmc_wrapper/Geometry.py index 584dc88..ea4aa85 100644 --- a/openmc_dagmc_wrapper/Geometry.py +++ b/openmc_dagmc_wrapper/Geometry.py @@ -89,8 +89,7 @@ def make_root(self): vac_surf = self.create_sphere_of_vacuum_surface() region = -vac_surf & -reflective_1 & +reflective_2 - containing_cell = openmc.Cell( - cell_id=9999, region=region, fill=dag_univ) + containing_cell = openmc.Cell(cell_id=9999, region=region, fill=dag_univ) root = [containing_cell] return root @@ -103,7 +102,7 @@ def create_sphere_of_vacuum_surface(self): self.graveyard_box = find_bounding_box(self.h5m_filename) bbox = [[*self.graveyard_box[0]], [*self.graveyard_box[1]]] - largest_radius = max(max(bbox[0]), max(bbox[1])) + largest_radius = 3 * max(max(bbox[0]), max(bbox[1])) sphere_surface = openmc.Sphere( r=largest_radius, surface_id=9999, boundary_type="vacuum" @@ -123,31 +122,13 @@ def create_cube_of_vacuum_surfaces(self): bbox[0][0] = 0.0 bbox[0][1] = 0.0 - lower_x = openmc.XPlane( - bbox[0][0], - surface_id=9999, - boundary_type="vacuum") - upper_x = openmc.XPlane( - bbox[1][0], - surface_id=9998, - boundary_type="vacuum") - - lower_y = openmc.YPlane( - bbox[0][1], - surface_id=9997, - boundary_type="vacuum") - upper_y = openmc.YPlane( - bbox[1][1], - surface_id=9996, - boundary_type="vacuum") - - lower_z = openmc.ZPlane( - bbox[0][2], - surface_id=9995, - boundary_type="vacuum") - upper_z = openmc.ZPlane( - bbox[1][2], - surface_id=9994, - boundary_type="vacuum") + lower_x = openmc.XPlane(bbox[0][0], surface_id=9999, boundary_type="vacuum") + upper_x = openmc.XPlane(bbox[1][0], surface_id=9998, boundary_type="vacuum") + + lower_y = openmc.YPlane(bbox[0][1], surface_id=9997, boundary_type="vacuum") + upper_y = openmc.YPlane(bbox[1][1], surface_id=9996, boundary_type="vacuum") + + lower_z = openmc.ZPlane(bbox[0][2], surface_id=9995, boundary_type="vacuum") + upper_z = openmc.ZPlane(bbox[1][2], surface_id=9994, boundary_type="vacuum") return [lower_x, upper_x, lower_y, upper_y, lower_z, upper_z] From 9c4485d4f40e7df2bac5333be68fe6d4e0caa570 Mon Sep 17 00:00:00 2001 From: autopep8 Date: Thu, 14 Oct 2021 21:52:55 +0000 Subject: [PATCH 11/16] Automated autopep8 fixes --- openmc_dagmc_wrapper/Geometry.py | 37 ++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/openmc_dagmc_wrapper/Geometry.py b/openmc_dagmc_wrapper/Geometry.py index ea4aa85..2a26366 100644 --- a/openmc_dagmc_wrapper/Geometry.py +++ b/openmc_dagmc_wrapper/Geometry.py @@ -89,7 +89,8 @@ def make_root(self): vac_surf = self.create_sphere_of_vacuum_surface() region = -vac_surf & -reflective_1 & +reflective_2 - containing_cell = openmc.Cell(cell_id=9999, region=region, fill=dag_univ) + containing_cell = openmc.Cell( + cell_id=9999, region=region, fill=dag_univ) root = [containing_cell] return root @@ -122,13 +123,31 @@ def create_cube_of_vacuum_surfaces(self): bbox[0][0] = 0.0 bbox[0][1] = 0.0 - lower_x = openmc.XPlane(bbox[0][0], surface_id=9999, boundary_type="vacuum") - upper_x = openmc.XPlane(bbox[1][0], surface_id=9998, boundary_type="vacuum") - - lower_y = openmc.YPlane(bbox[0][1], surface_id=9997, boundary_type="vacuum") - upper_y = openmc.YPlane(bbox[1][1], surface_id=9996, boundary_type="vacuum") - - lower_z = openmc.ZPlane(bbox[0][2], surface_id=9995, boundary_type="vacuum") - upper_z = openmc.ZPlane(bbox[1][2], surface_id=9994, boundary_type="vacuum") + lower_x = openmc.XPlane( + bbox[0][0], + surface_id=9999, + boundary_type="vacuum") + upper_x = openmc.XPlane( + bbox[1][0], + surface_id=9998, + boundary_type="vacuum") + + lower_y = openmc.YPlane( + bbox[0][1], + surface_id=9997, + boundary_type="vacuum") + upper_y = openmc.YPlane( + bbox[1][1], + surface_id=9996, + boundary_type="vacuum") + + lower_z = openmc.ZPlane( + bbox[0][2], + surface_id=9995, + boundary_type="vacuum") + upper_z = openmc.ZPlane( + bbox[1][2], + surface_id=9994, + boundary_type="vacuum") return [lower_x, upper_x, lower_y, upper_y, lower_z, upper_z] From 9a60433534030c6ce15684996bfeab691c14366f Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Mon, 18 Oct 2021 14:14:03 +0100 Subject: [PATCH 12/16] removed old code that has been refactored into serparate packages --- examples/cell_tally_example.ipynb | 361 -------------- examples/cell_tally_example.py | 7 - examples/regular_2d_mesh_tally_example.py | 7 - examples/regular_3d_mesh_tally_example.py | 7 - openmc_dagmc_wrapper/utils.py | 542 ---------------------- 5 files changed, 924 deletions(-) delete mode 100644 examples/cell_tally_example.ipynb diff --git a/examples/cell_tally_example.ipynb b/examples/cell_tally_example.ipynb deleted file mode 100644 index e60f2bc..0000000 --- a/examples/cell_tally_example.ipynb +++ /dev/null @@ -1,361 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is a minimal example that obtains the TBR (Tritium Breeding Ratio) for a simplified fusion reactor" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "imports required packages" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import openmc\n", - "import openmc_dagmc_wrapper as odw\n", - "import dagmc_h5m_file_inspector as di\n", - "import tarfile\n", - "import urllib.request\n", - "# import openmc_data_donloader todo add ability to downlad materials in a nmm material" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Downloads an example h5m file made using the Paramak and cad_to_h5m python packages." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "url = \"https://github.com/fusion-energy/neutronics_workflow/archive/refs/tags/v0.0.2.tar.gz\"\n", - "urllib.request.urlretrieve(url, \"v0.0.2.tar.gz\")\n", - "\n", - "tar = tarfile.open(\"v0.0.2.tar.gz\", \"r:gz\")\n", - "tar.extractall(\".\")\n", - "tar.close()\n", - "\n", - "h5m_filename = \"neutronics_workflow-0.0.2/example_02_multi_volume_cell_tally/stage_2_output/dagmc.h5m\"" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creates a simple openmc point source" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "['blanket_mat',\n", - " 'blanket_rear_wall_mat',\n", - " 'center_column_shield_mat',\n", - " 'divertor_mat',\n", - " 'firstwall_mat',\n", - " 'graveyard',\n", - " 'inboard_tf_coils_mat',\n", - " 'pf_coil_case_mat',\n", - " 'pf_coil_mat',\n", - " 'tf_coil_mat']" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "di.get_materials_from_h5m(h5m_filename)" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "source = openmc.Source()\n", - "# sets the location of the source to x=0 y=0 z=0\n", - "source.space = openmc.stats.Point((450, 0, 0))\n", - "# sets the direction to isotropic\n", - "source.angle = openmc.stats.Isotropic()\n", - "# sets the energy distribution to 100% 14MeV neutrons\n", - "source.energy = openmc.stats.Discrete([14e6], [1])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creates a NeutronicsModel object with the h5m file, openmc source and materials from the neutronic_material_maker database" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "# makes the neutronics model from the geometry and material allocations\n", - "my_model = odw.NeutronicsModel(\n", - " h5m_filename=h5m_filename,\n", - " source=source,\n", - " materials={\n", - " 'blanket_mat':'Li4SiO4',\n", - " 'blanket_rear_wall_mat':'eurofer',\n", - " 'center_column_shield_mat':'eurofer',\n", - " 'divertor_mat':'eurofer',\n", - " 'firstwall_mat':'eurofer',\n", - " 'inboard_tf_coils_mat':'eurofer',\n", - " 'pf_coil_case_mat':'eurofer',\n", - " 'pf_coil_mat':'eurofer',\n", - " 'tf_coil_mat':'eurofer'\n", - " },\n", - " cell_tallies=['TBR', 'heating'],\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Exports the xml files needed by openmc to perform the simulation. The number of batch and particles would need increasing to obtain accurate results." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=1.\n", - "\n", - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=2.\n", - "\n", - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=3.\n", - "\n", - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=4.\n", - "\n", - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=5.\n", - "\n", - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=6.\n", - "\n", - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=7.\n", - "\n", - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=8.\n", - "\n", - "/opt/openmc/openmc/mixin.py:67: IDWarning:\n", - "\n", - "Another Filter instance already exists with id=9.\n", - "\n" - ] - }, - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "my_model.export_xml(\n", - " simulation_batches=2,\n", - " simulation_particles_per_batch=100\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Simulates the model using openmc" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "2" - ] - }, - "execution_count": 16, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "statepoint_filename = my_model.simulate()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "extracts and processes the results from the statepoint file" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "processing TBR\n", - "processing blanket_mat_TBR\n", - "processing blanket_rear_wall_mat_TBR\n", - "processing center_column_shield_mat_TBR\n", - "processing divertor_mat_TBR\n", - "processing firstwall_mat_TBR\n", - "processing inboard_tf_coils_mat_TBR\n", - "processing pf_coil_case_mat_TBR\n", - "processing pf_coil_mat_TBR\n", - "processing tf_coil_mat_TBR\n", - "processing blanket_mat_heating\n", - "processing blanket_rear_wall_mat_heating\n", - "processing center_column_shield_mat_heating\n", - "processing divertor_mat_heating\n", - "processing firstwall_mat_heating\n", - "processing inboard_tf_coils_mat_heating\n", - "processing pf_coil_case_mat_heating\n", - "processing pf_coil_mat_heating\n", - "processing tf_coil_mat_heating\n" - ] - } - ], - "source": [ - "results = odw.process_results(statepoint_filename=statepoint_filename)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "prints the results of the simulation" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "defaultdict(,\n", - " {'TBR': {'result': 0.12117491318862389,\n", - " 'std. dev.': 0.03467079662507109},\n", - " 'blanket_mat_TBR': {'result': 0.12116960749504556,\n", - " 'std. dev.': 0.03467046412453008},\n", - " 'blanket_mat_heating': {'MeV per source particle': {'result': 0.6875017743640932,\n", - " 'std. dev.': 0.20629788077176192}},\n", - " 'blanket_rear_wall_mat_TBR': {'result': 0.0, 'std. dev.': 0.0},\n", - " 'blanket_rear_wall_mat_heating': {'MeV per source particle': {'result': 0.0,\n", - " 'std. dev.': 0.0}},\n", - " 'center_column_shield_mat_TBR': {'result': 3.7176088965332814e-07,\n", - " 'std. dev.': 2.6024613099955484e-07},\n", - " 'center_column_shield_mat_heating': {'MeV per source particle': {'result': 0.29760957274781974,\n", - " 'std. dev.': 0.037903132880772}},\n", - " 'divertor_mat_TBR': {'result': 1.9651809606401932e-07,\n", - " 'std. dev.': 7.124910801619062e-08},\n", - " 'divertor_mat_heating': {'MeV per source particle': {'result': 0.41733955041276444,\n", - " 'std. dev.': 0.16449821130263445}},\n", - " 'firstwall_mat_TBR': {'result': 4.737414592772001e-06,\n", - " 'std. dev.': 6.639957800907665e-07},\n", - " 'firstwall_mat_heating': {'MeV per source particle': {'result': 4.11706988422747,\n", - " 'std. dev.': 0.10782396895287244}},\n", - " 'inboard_tf_coils_mat_TBR': {'result': 0.0, 'std. dev.': 0.0},\n", - " 'inboard_tf_coils_mat_heating': {'MeV per source particle': {'result': 0.0,\n", - " 'std. dev.': 0.0}},\n", - " 'pf_coil_case_mat_TBR': {'result': 0.0, 'std. dev.': 0.0},\n", - " 'pf_coil_case_mat_heating': {'MeV per source particle': {'result': 0.0,\n", - " 'std. dev.': 0.0}},\n", - " 'pf_coil_mat_TBR': {'result': 0.0, 'std. dev.': 0.0},\n", - " 'pf_coil_mat_heating': {'MeV per source particle': {'result': 0.0,\n", - " 'std. dev.': 0.0}},\n", - " 'tf_coil_mat_TBR': {'result': 0.0, 'std. dev.': 0.0},\n", - " 'tf_coil_mat_heating': {'MeV per source particle': {'result': 0.0,\n", - " 'std. dev.': 0.0}}})\n" - ] - } - ], - "source": [ - "import pprint\n", - "pprint.pprint(results)" - ] - } - ], - "metadata": { - "interpreter": { - "hash": "71893251c0b0cd78b546a9c905312457257aecf63dc5b51c6968316964f80317" - }, - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.5" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/examples/cell_tally_example.py b/examples/cell_tally_example.py index fb0c345..47708f9 100644 --- a/examples/cell_tally_example.py +++ b/examples/cell_tally_example.py @@ -78,10 +78,3 @@ materials=materials, geometry=geometry, settings=settings, tallies=tallies ) statepoint_file = my_model.run() - -# processes the output h5 file. the process_results function contains logic on -# how to process each tally with respect to the tally multipliers and units -# involved. The fusion power input allows tallies to be scaled from the units -# of per source neutron to units such as Watts (for heating), Sv per second -# (for dose) and other convenient units. -odw.process_results(statepoint_file, fusion_power=1e9) diff --git a/examples/regular_2d_mesh_tally_example.py b/examples/regular_2d_mesh_tally_example.py index b3fafe6..4626cd3 100644 --- a/examples/regular_2d_mesh_tally_example.py +++ b/examples/regular_2d_mesh_tally_example.py @@ -77,10 +77,3 @@ materials=materials, geometry=geometry, settings=settings, tallies=tallies ) statepoint_file = my_model.run() - -# processes the output h5 file. The process_results function contains logic on -# how to process each tally with respect to the tally multipliers and units -# involved. The fusion power input allows tallies to be scaled from the units -# of per source neutron to units such as Watts (for heating), Sv per second -# (for dose) and other convenient units. -odw.process_results(statepoint_file, fusion_power=1e9) diff --git a/examples/regular_3d_mesh_tally_example.py b/examples/regular_3d_mesh_tally_example.py index 1402da6..d5dc0cb 100644 --- a/examples/regular_3d_mesh_tally_example.py +++ b/examples/regular_3d_mesh_tally_example.py @@ -70,10 +70,3 @@ materials=materials, geometry=geometry, settings=settings, tallies=tallies ) statepoint_file = my_model.run() - -# processes the output h5 file. The process_results function contains logic on -# how to process each tally with respect to the tally multipliers and units -# involved. The fusion power input allows tallies to be scaled from the units -# of per source neutron to units such as Watts (for heating), Sv per second -# (for dose) and other convenient units. -odw.process_results(statepoint_file, fusion_power=1e9) diff --git a/openmc_dagmc_wrapper/utils.py b/openmc_dagmc_wrapper/utils.py index 4d52ada..db149ba 100644 --- a/openmc_dagmc_wrapper/utils.py +++ b/openmc_dagmc_wrapper/utils.py @@ -62,548 +62,6 @@ def silently_remove_file(filename: str): pass # in some cases the file will not exist -def _save_2d_mesh_tally_as_png(filename: str, tally) -> str: - """Extracts 2D mesh tally results from a tally and saves the result as - a png image. - - Arguments: - score (str): The tally score to filter the tally with, e.g. 'flux', - 'heating', etc. - filename (str): The filename to use when saving the png output file - tally (opencmc.tally()): The OpenMC to extract the mesh tally - results from. - """ - - my_slice = tally.get_slice(scores=tally.scores) - tally_filter = tally.find_filter(filter_type=openmc.MeshFilter) - shape = tally_filter.mesh.dimension.tolist() - shape.remove(1) - my_slice.mean.shape = shape - - fig = plt.subplot() - fig.imshow(my_slice.mean).get_figure().savefig(filename, dpi=300) - fig.clear() - - return filename - - -def find_fusion_energy_per_reaction(reactants: str) -> float: - """Finds the average fusion energy produced per fusion reaction in joules - from the fule type. - - Args: - reactants: the isotopes that are combined in the fusion even. Options - are "DD" or "DT" - - Returns: - The average energy of a fusion reaction in Joules - """ - - if reactants == "DT": - fusion_energy_of_neutron_ev = 14.06 * 1e6 - fusion_energy_of_alpha_ev = 3.52 * 1e6 - fusion_energy_per_reaction_ev = ( - fusion_energy_of_neutron_ev + fusion_energy_of_alpha_ev - ) - elif reactants == "DD": - fusion_energy_of_trition_ev = 1.01 * 1e6 - fusion_energy_of_proton_ev = 3.02 * 1e6 - fusion_energy_of_he3_ev = 0.82 * 1e6 - fusion_energy_of_neutron_ev = 2.45 * 1e6 - fusion_energy_per_reaction_ev = ( - 0.5 * (fusion_energy_of_trition_ev + fusion_energy_of_proton_ev) - ) + (0.5 * (fusion_energy_of_he3_ev + fusion_energy_of_neutron_ev)) - else: - raise ValueError( - "Only fuel types of DD and DT are currently supported") - - fusion_energy_per_reaction_j = fusion_energy_per_reaction_ev * 1.602176487e-19 - - return fusion_energy_per_reaction_j - - -def process_results( - statepoint_filename: str, - fusion_power: Optional[float] = None, - fusion_energy_per_pulse: Optional[float] = None, - fusion_fuel: Optional[str] = "DT", - outputfile: Optional[str] = "results.json", -) -> dict: - """Extracts simulation results from the statepoint file. Applies post - processing to the results taking into account user specified fusion - power or fusion energy per pulse. If 3d mesh tallies are specified then - vtk files will be produced. If 2d mesh tallies are specified then png - images will be produced. The cell tallies results will be output to - a json file. - - Args: - statepoint_filename: the name of the statepoint file to extract - results from and process. - fusion_power: the power in watts emitted by the fusion reaction - recalling that each DT fusion reaction emits 17.6 MeV or - 2.819831e-12 Joules. Intended use for steady state reactors. - Providing an input can result in additional entries in the post - processed tally results. e.g heating tallies are extended to include - rate of heating deposited in Watts. - fusion_energy_per_pulse: the amount of energy released by the pulse - in Joules. Intended use for pulsed machines. Providing an input - can result in additional entries in the post processed tally - results. e.g heating tallies are extended to include Joules - deposited for the pulse. - outputfile: the filename to use when saving the cell tallies to file. - fusion_fuel: the isotopes that make up the fuel. Accepted options are - 'DT' or 'DD' used to obtain the fusion energy emitted per fusion - event. - - Returns: - A dictionary of results - """ - - fusion_energy_per_reaction_j = find_fusion_energy_per_reaction(fusion_fuel) - - if fusion_power is not None: - number_of_neutrons_per_second = fusion_power / fusion_energy_per_reaction_j - if fusion_energy_per_pulse is not None: - number_of_neutrons_per_pulse = ( - fusion_energy_per_pulse / fusion_energy_per_reaction_j - ) - - # 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() - results[tally.name] = { - "result": tally_result, - } - if "std. dev." in data_frame.keys(): - tally_std_dev = data_frame["std. dev."].sum() - results[tally.name]["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 # converts tally from eV to Joules - * number_of_neutrons_per_second, - "std. dev.": tally_std_dev - * 1.602176487e-19 # converts tally from eV to Joules - * number_of_neutrons_per_second, - } - - if fusion_energy_per_pulse is not None: - results[tally.name]["Joules"] = { - "result": tally_result - * 1.602176487e-19 # converts tally from eV to Joules - * number_of_neutrons_per_pulse, - "std. dev.": tally_std_dev - * 1.602176487e-19 # converts tally from eV to Joules - * number_of_neutrons_per_pulse, - } - - elif tally.name.endswith("fast_flux"): - - data_frame = tally.get_pandas_dataframe() - tally_result = data_frame["mean"].sum() - results[tally.name]["fast flux per source particle"] = { - "result": tally_result - } - if "std. dev." in data_frame.keys(): - tally_std_dev = data_frame["std. dev."].sum() - results[tally.name]["fast flux per source particle"][ - "std. dev." - ] = tally_std_dev - - if fusion_power is not None: - results[tally.name]["fast flux per second"] = { - "result": tally_result * number_of_neutrons_per_second - } - - if fusion_energy_per_pulse is not None: - results[tally.name]["fast flux per pulse"] = { - "result": tally_result * number_of_neutrons_per_pulse - } - - 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, - } - - if fusion_power is not None: - results[tally.name]["flux per second"] = { - "result": tally_result * number_of_neutrons_per_second - } - - if fusion_energy_per_pulse is not None: - results[tally.name]["flux per pulse"] = { - "result": tally_result * number_of_neutrons_per_pulse - } - - 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(), - } - - if fusion_power is not None: - scale_tally_result = tally_result * number_of_neutrons_per_second - scale_tally_std_dev = tally_std_dev * number_of_neutrons_per_second - results[tally.name]["flux per second"] = { - "energy": openmc.mgxs.GROUP_STRUCTURES["CCFE-709"].tolist(), - "result": scale_tally_result.tolist(), - "std. dev.": scale_tally_std_dev.tolist(), - } - - if fusion_energy_per_pulse is not None: - results[tally.name]["flux per pulse"] = { - "energy": openmc.mgxs.GROUP_STRUCTURES["CCFE-709"].tolist(), - "result": [ - result * number_of_neutrons_per_pulse - for result in tally_result.tolist() - ], - "std. dev.": [ - result * number_of_neutrons_per_pulse - for result in tally_std_dev.tolist() - ], - } - - elif tally.name.endswith("effective_dose"): - data_frame = tally.get_pandas_dataframe() - tally_result = data_frame["mean"].sum() - tally_std_dev = data_frame["std. dev."].sum() - # flux is in units of cm per source particle - # dose coefficients have units of pico Sv cm^2 - results[tally.name]["effective dose per source particle pSv cm3"] = { - "result": tally_result, "std. dev.": tally_std_dev, } - - if fusion_power is not None: - results[tally.name]["pSv cm3 per second"] = { - "result": tally_result * number_of_neutrons_per_second, - "std. dev.": tally_std_dev * number_of_neutrons_per_second, - } - - if fusion_energy_per_pulse is not None: - results[tally.name]["pSv cm3 per pulse"] = { - "result": tally_result * number_of_neutrons_per_pulse, - "std. dev.": tally_std_dev * number_of_neutrons_per_pulse, - } - - elif "_on_2D_mesh" in tally.name: - # score = tally.name.split("_")[0] - _save_2d_mesh_tally_as_png( - tally=tally, filename=tally.name.replace( - "(", "").replace( - ")", "").replace( - ",", "-"), ) - - elif "_on_3D_mesh" in tally.name: - mesh_id = 1 - mesh = statepoint.meshes[mesh_id] - - # TODO method to calculate - # import math - # print('width', mesh.width) - # print('dimension', mesh.dimension) - # element_lengths = [w/d for w,d in zip(mesh.width, mesh.dimension)] - # print('element_lengths', element_lengths) - # element_volume = math.prod(element_lengths) - # print('element_volume', element_volume) - - 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.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", - ) - - elif "_on_3D_u_mesh" in tally.name: - pass - # openmc makes vtk files for unstructured mesh files automatically - 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, - } - - if outputfile is not None: - with open(outputfile, "w") as outfile: - json.dump(results, outfile, indent=4, sort_keys=True) - - return results - - -# to do find particles from tally -# def find_particle_from_tally(tally): -# for filter in talliy.filters: -# if isinstance(filter, openmc.ParticleFilter): -# return filter.bins[0] -# return None - - -def write_3d_mesh_tally_to_vtk( - xs: np.linspace, - ys: np.linspace, - zs: np.linspace, - tally_data: List[float], - error_data: Optional[List[float]] = None, - outfile: Optional[str] = "3d_mesh_tally_data.vtk", - tally_label: Optional[str] = "3d_mesh_tally_data", -) -> str: - """Converts regular 3d data into a vtk file for visualising the data. - Programs that can visualise vtk files include Paraview - https://www.paraview.org/ and VisIt - https://wci.llnl.gov/simulation/computer-codes/visit - - Arguments: - xs: A numpy array containing evenly spaced numbers from the lowest x - coordinate value to the highest x coordinate value. - ys: A numpy array containing evenly spaced numbers from the lowest y - coordinate value to the highest y coordinate value. - zs: A numpy array containing evenly spaced numbers from the lowest z - coordinate value to the highest z coordinate value. - tally_data: A list of data values to assign to the vtk dataset. - error_data: A list of error data values to assign to the vtk dataset. - outfile: The filename of the output vtk file. - tally_label: The name to assign to the dataset in the vtk file. - - Returns: - str: the filename of the file produced - """ - try: - import vtk - except (ImportError, ModuleNotFoundError): - msg = ( - "Conversion to VTK requested," - "but the Python VTK module is not installed. Try pip install pyvtk" - ) - raise ImportError(msg) - - vtk_box = vtk.vtkRectilinearGrid() - - vtk_box.SetDimensions(len(xs), len(ys), len(zs)) - - vtk_x_array = vtk.vtkDoubleArray() - vtk_x_array.SetName("x-coords") - vtk_x_array.SetArray(xs, len(xs), True) - vtk_box.SetXCoordinates(vtk_x_array) - - vtk_y_array = vtk.vtkDoubleArray() - vtk_y_array.SetName("y-coords") - vtk_y_array.SetArray(ys, len(ys), True) - vtk_box.SetYCoordinates(vtk_y_array) - - vtk_z_array = vtk.vtkDoubleArray() - vtk_z_array.SetName("z-coords") - vtk_z_array.SetArray(zs, len(zs), True) - vtk_box.SetZCoordinates(vtk_z_array) - - tally = np.array(tally_data) - tally_data = vtk.vtkDoubleArray() - tally_data.SetName(tally_label) - tally_data.SetArray(tally, tally.size, True) - - if error_data is not None: - error = np.array(error_data) - error_data = vtk.vtkDoubleArray() - error_data.SetName("error_tag") - error_data.SetArray(error, error.size, True) - - vtk_box.GetCellData().AddArray(tally_data) - vtk_box.GetCellData().AddArray(error_data) - - writer = vtk.vtkRectilinearGridWriter() - - writer.SetFileName(outfile) - - writer.SetInputData(vtk_box) - - print("Writing %s" % outfile) - - writer.Write() - - return outfile - - -# @shimwell are we keeping this? -# def create_initial_particles( -# source, -# number_of_source_particles: int = 2000) -> str: -# """Accepts an openmc source and creates an initial_source.h5 that can be -# used to find intial xyz, direction and energy of the partice source. - -# Arguments: -# source: (openmc.Source()): the OpenMC source to create an initial source -# file from. -# number_of_source_particles: The number of particle to sample. - -# Returns: -# str: the filename of the h5 file produced -# """ - -# # MATERIALS - -# # no real materials are needed for finding the source -# mats = openmc.Materials([]) - -# # GEOMETRY - -# # just a minimal geometry -# outer_surface = openmc.Sphere(r=100000, boundary_type="vacuum") -# cell = openmc.Cell(region=-outer_surface) -# universe = openmc.Universe(cells=[cell]) -# geom = openmc.Geometry(universe) - -# # SIMULATION SETTINGS - -# # Instantiate a Settings object -# sett = openmc.Settings() -# # this will fail but it will write the initial_source.h5 file first -# sett.run_mode = "eigenvalue" -# sett.particles = number_of_source_particles -# sett.batches = 1 -# sett.inactive = 0 -# sett.write_initial_source = True - -# sett.source = source - -# model = openmc.model.Model(geom, mats, sett) - -# silently_remove_file("settings.xml") -# silently_remove_file("materials.xml") -# silently_remove_file("geometry.xml") -# silently_remove_file("settings.xml") -# silently_remove_file("tallies.xml") -# model.export_to_xml() - -# # this just adds write_initial_source == True to the settings.xml -# tree = ET.parse("settings.xml") -# root = tree.getroot() -# elem = SubElement(root, "write_initial_source") -# elem.text = "true" -# tree.write("settings.xml") - -# # This will crash hence the try except loop, but it writes the -# # initial_source.h5 -# openmc.run(output=False) -# try: -# openmc.run(output=False) -# except BaseException: -# pass - -# return "initial_source.h5" - - -# @shimwell are we keeping this? -# def extract_points_from_initial_source( -# input_filename: str = "initial_source.h5", view_plane: str = "RZ" -# ) -> list: -# """Reads in an initial source h5 file (generated by OpenMC), extracts point -# and projects them onto a view plane. - -# Arguments: -# input_filename: the OpenMC source to create an initial source -# file from. -# view_plane: The plane to project. Options are 'XZ', 'XY', 'YZ', -# 'YX', 'ZY', 'ZX', 'RZ' and 'XYZ'. Defaults to 'RZ'. Defaults to -# 'RZ'. - -# Returns: -# list: list of points extracted -# """ -# import h5py - -# h5_file = h5py.File(input_filename, "r") -# dset = h5_file["source_bank"] - -# points = [] - -# for particle in dset: -# if view_plane == "XZ": -# points.append((particle[0][0], particle[0][2])) -# elif view_plane == "XY": -# points.append((particle[0][0], particle[0][1])) -# elif view_plane == "YZ": -# points.append((particle[0][1], particle[0][2])) -# elif view_plane == "YX": -# points.append((particle[0][1], particle[0][0])) -# elif view_plane == "ZY": -# points.append((particle[0][2], particle[0][1])) -# elif view_plane == "ZX": -# points.append((particle[0][2], particle[0][0])) -# elif view_plane == "RZ": -# xy_coord = math.pow(particle[0][0], 2) + \ -# math.pow(particle[0][1], 2) -# points.append((math.sqrt(xy_coord), particle[0][2])) -# elif view_plane == "XYZ": -# points.append((particle[0][0], particle[0][1], particle[0][2])) -# else: -# raise ValueError( -# "view_plane value of ", -# view_plane, -# " is not supported") -# return points - - def diff_between_angles(angle_a: float, angle_b: float) -> float: """Calculates the difference between two angles angle_a and angle_b From 9c40a759f53d9cd83fdaf9b77dfb416e3f58632c Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Mon, 18 Oct 2021 14:17:21 +0100 Subject: [PATCH 13/16] removed function that no longer exists --- openmc_dagmc_wrapper/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc_dagmc_wrapper/__init__.py b/openmc_dagmc_wrapper/__init__.py index fe172b4..e7e9385 100644 --- a/openmc_dagmc_wrapper/__init__.py +++ b/openmc_dagmc_wrapper/__init__.py @@ -1,4 +1,4 @@ -from .utils import process_results, create_material, find_bounding_box +from .utils import create_material, find_bounding_box from .Geometry import Geometry from .Materials import Materials From 628af091e3ff38ca956ebf24aed7c771407f91df Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Mon, 18 Oct 2021 14:36:31 +0100 Subject: [PATCH 14/16] removed processing of results from tests --- tests/test_system/test_system_multi_volume.py | 183 +---------- .../test_system/test_system_single_volume.py | 309 +++--------------- tests/test_tallies/test_mesh_tally_2d.py | 6 +- 3 files changed, 50 insertions(+), 448 deletions(-) diff --git a/tests/test_system/test_system_multi_volume.py b/tests/test_system/test_system_multi_volume.py index 885d6ae..856318a 100644 --- a/tests/test_system/test_system_multi_volume.py +++ b/tests/test_system/test_system_multi_volume.py @@ -6,7 +6,6 @@ import openmc import openmc_dagmc_wrapper as odw -import pytest class TestObjectNeutronicsArguments(unittest.TestCase): @@ -58,6 +57,8 @@ def setUp(self): def test_cell_tally_simulation(self): + os.system('rm statepoint*.h5') + geometry = odw.Geometry(h5m_filename=self.h5m_filename_bigger) materials = odw.Materials( h5m_filename=self.h5m_filename_bigger, @@ -70,185 +71,9 @@ def test_cell_tally_simulation(self): settings=self.settings ) - h5m_filename = my_model.run() + statepoint_file = my_model.run() - results = odw.process_results(statepoint_filename=h5m_filename) - - assert results["TBR"]["result"] > 0.0 - - -# # move to neutronics_workflow -# class TestSimulationResultsVsCsg(unittest.TestCase): -# """Makes a geometry in the paramak and in CSG geometry, simulates and -# compares the results""" - -# 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() - -# def simulate_cylinder_cask_cad( -# self, material, source, height, outer_radius, thickness, batches, particles -# ): -# """Makes a CAD cask geometry runs a simulation and returns the result""" - -# top_cap_cell = paramak.RotateStraightShape( -# stp_filename="top_cap_cell.stp", -# material_tag="test_mat", -# points=[ -# (outer_radius, height * 0.5), -# (outer_radius, (height * 0.5) + thickness), -# (0, (height * 0.5) + thickness), -# (0, height * 0.5), -# ], -# ) - -# bottom_cap_cell = paramak.RotateStraightShape( -# stp_filename="bottom_cap_cell.stp", -# material_tag="test_mat", -# points=[ -# (outer_radius, -height * 0.5), -# (outer_radius, (-height * 0.5) - thickness), -# (0, (-height * 0.5) - thickness), -# (0, -height * 0.5), -# ], -# ) - -# cylinder_cell = paramak.CenterColumnShieldCylinder( -# height=height, -# inner_radius=outer_radius - thickness, -# outer_radius=outer_radius, -# material_tag="test_mat", -# ) - -# my_geometry = paramak.Reactor( -# shapes_and_components=[cylinder_cell, bottom_cap_cell, top_cap_cell], -# method="pymoab", -# ) - -# my_model = openmc_dagmc_wrapper.NeutronicsModel( -# h5m_filename=my_geometry.export_h5m(), -# source=source, -# simulation_batches=batches, -# simulation_particles_per_batch=particles, -# materials={"test_mat": material}, -# cell_tallies=["heating"], -# ) - -# my_model.simulate() - -# # scaled from MeV to eV -# return ( -# my_model.results["test_mat_heating"]["MeV per source particle"]["result"] -# * 1e6 -# ) - -# def test_cylinder_cask(self): -# """Runs the same source and material with CAD and CSG geoemtry""" - -# height = 100 -# outer_radius = 50 -# thickness = 10 - -# batches = 10 -# particles = 500 - -# test_material = openmc.Material(name="test_material") -# test_material.set_density("g/cm3", 7.75) -# test_material.add_element("Fe", 0.95, percent_type="wo") -# test_material.add_element("C", 0.05, percent_type="wo") - -# source = openmc.Source() -# source.space = openmc.stats.Point((0, 0, 0)) -# source.angle = openmc.stats.Isotropic() -# source.energy = openmc.stats.Discrete([14e6], [1.0]) - -# csg_result = self.simulate_cylinder_cask_csg( -# test_material, source, height, outer_radius, thickness, batches, particles -# ) - -# cad_result = self.simulate_cylinder_cask_cad( -# test_material, source, height, outer_radius, thickness, batches, particles -# ) - -# assert pytest.approx(csg_result, rel=0.02) == cad_result + assert Path(statepoint_file).exists() if __name__ == "__main__": diff --git a/tests/test_system/test_system_single_volume.py b/tests/test_system/test_system_single_volume.py index 62e063d..87e9253 100644 --- a/tests/test_system/test_system_single_volume.py +++ b/tests/test_system/test_system_single_volume.py @@ -60,6 +60,9 @@ def setUp(self): def test_simulation_with_previous_h5m_file(self): """This performs a simulation using previously created h5m file""" + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") + geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) materials = odw.Materials( h5m_filename=self.h5m_filename_smaller, @@ -72,14 +75,16 @@ def test_simulation_with_previous_h5m_file(self): settings=self.settings ) - h5m_filename = my_model.run() - results = odw.process_results(statepoint_filename=h5m_filename) + statepoint_file = my_model.run() - assert results is not None + assert Path(statepoint_file).exists() def test_neutronics_component_simulation_with_openmc_mat(self): """Makes a neutronics model and simulates with a cell tally""" + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") + test_mat = openmc.Material() test_mat.add_element("Fe", 1.0) test_mat.set_density(units="g/cm3", density=4.2) @@ -104,15 +109,13 @@ def test_neutronics_component_simulation_with_openmc_mat(self): results = openmc.StatePoint(h5m_filename) assert len(results.tallies.items()) == 1 - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_power=1e9) - # extracts the heat from the results dictionary - assert results[my_tally.name]["Watts"]["result"] > 0 def test_neutronics_component_simulation_with_nmm(self): """Makes a neutronics model and simulates with a cell tally""" + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") + test_mat = nmm.Material.from_library("Be") geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) @@ -134,12 +137,6 @@ def test_neutronics_component_simulation_with_nmm(self): results = openmc.StatePoint(h5m_filename) assert len(results.tallies.items()) == 1 - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_power=1e9) - # extracts the heat from the results dictionary - assert results[my_tally.name]["Watts"]["result"] > 0 - def test_incorrect_cell_tallies(self): """Set a cell tally that is not accepted which should raise an error""" @@ -159,7 +156,9 @@ def incorrect_cell_tally_type(): def test_neutronics_component_cell_simulation_heating(self): """Makes a neutronics model and simulates with a cell tally""" - os.system("rm *.h5") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") + mat = openmc.Material() mat.add_element("Li", 1) mat.set_density("g/cm3", 2.1) @@ -190,31 +189,12 @@ def test_neutronics_component_cell_simulation_heating(self): assert len(results.tallies.items()) == 5 assert len(results.meshes) == 0 - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_power=1e9 - ) - - # extracts the heat from the results dictionary - print(results['mat1_heating']) - heat = results["heating"]["Watts"]["result"] - flux = results["flux"]["flux per source particle"]["result"] - tbr = results["TBR"]["result"] - spectra_neutrons = results["neutron_spectra"]["flux per source particle"]["result"] - spectra_photons = results["photon_spectra"]["flux per source particle"]["result"] - energy = results["photon_spectra"]["flux per source particle"]["energy"] - - assert heat > 0 - assert flux > 0 - assert tbr > 0 - assert len(energy) == 710 - assert len(spectra_neutrons) == 709 - assert len(spectra_photons) == 709 - - def test_neutronics_spectra_post_processing(self): + def test_neutronics_spectra(self): """Makes a neutronics model and simulates with a cell tally""" - os.system("rm *.h5") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") + mat = openmc.Material() mat.add_element("Li", 1) mat.set_density("g/cm3", 2.1) @@ -234,71 +214,15 @@ def test_neutronics_spectra_post_processing(self): ) # performs an openmc simulation on the model - h5m_filename = my_model.run() + statepoint_file = my_model.run() - results = odw.process_results(statepoint_filename=h5m_filename) - assert len(results.keys()) == 2 - assert len(results['neutron_spectra'].keys()) == 1 - assert len(results['photon_spectra'].keys()) == 1 - - neutron_flux_sum = sum(results['neutron_spectra'] - ["flux per source particle"]["result"]) - photon_flux_sum = sum(results['photon_spectra'] - ["flux per source particle"]["result"]) - - # TODO change > to the actual ratio - - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_energy_per_pulse=3) - assert len(results.keys()) == 2 - assert len(results['neutron_spectra'].keys()) == 2 - assert len(results['photon_spectra'].keys()) == 2 - assert sum(results['neutron_spectra'] - ['flux per pulse']['result']) > neutron_flux_sum - assert sum(results['photon_spectra'] - ['flux per pulse']['result']) > photon_flux_sum - - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_power=2) - assert len(results.keys()) == 2 - assert len(results['neutron_spectra'].keys()) == 2 - assert len(results['photon_spectra'].keys()) == 2 - assert sum(results['neutron_spectra'] - ['flux per second']['result']) > neutron_flux_sum - assert sum(results['photon_spectra'] - ['flux per second']['result']) > photon_flux_sum - - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_energy_per_pulse=2, - fusion_power=3) - assert len(results.keys()) == 2 - assert len(results['neutron_spectra'].keys()) == 3 - assert len(results['photon_spectra'].keys()) == 3 - assert sum(results['neutron_spectra'] - ['flux per pulse']['result']) > neutron_flux_sum - assert sum(results['photon_spectra'] - ['flux per pulse']['result']) > photon_flux_sum - assert sum(results['neutron_spectra'] - ['flux per second']['result']) > neutron_flux_sum - assert sum(results['photon_spectra'] - ['flux per second']['result']) > photon_flux_sum - - spectra_neutrons = results["neutron_spectra"]["flux per source particle"]["result"] - spectra_photons = results["photon_spectra"]["flux per source particle"]["result"] - energy = results["photon_spectra"]["flux per source particle"]["energy"] - - assert len(energy) == 710 - assert len(spectra_neutrons) == 709 - assert len(spectra_photons) == 709 + assert Path(statepoint_file).exists() def test_neutronics_component_2d_mesh_simulation(self): """Makes a neutronics model and simulates with a 2D mesh tally""" - os.system("rm *_on_2D_mesh_*.png") - os.system("rm *.h5") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) materials = odw.Materials( @@ -323,21 +247,13 @@ def test_neutronics_component_2d_mesh_simulation(self): assert len(results.meshes) == 3 assert len(results.tallies.items()) == 3 - assert Path("heating_on_2D_mesh_xz.png").exists() is False - assert Path("heating_on_2D_mesh_xy.png").exists() is False - assert Path("heating_on_2D_mesh_yz.png").exists() is False - - odw.process_results(statepoint_filename=h5m_filename, fusion_power=1e9) - - assert Path("heating_on_2D_mesh_xz.png").exists() is True - assert Path("heating_on_2D_mesh_xy.png").exists() is True - assert Path("heating_on_2D_mesh_yz.png").exists() is True - def test_neutronics_component_3d_mesh_simulation(self): """Makes a neutronics model and simulates with a 3D mesh tally and checks that the vtk file is produced""" - os.system("rm *.h5 *.vtk") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") + os.system("rm *.vtk") geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) materials = odw.Materials( @@ -362,20 +278,13 @@ def test_neutronics_component_3d_mesh_simulation(self): assert len(results.tallies.items()) == 2 assert Path(h5m_filename).exists() is True - assert Path("heating_on_3D_mesh.vtk").exists() is False - assert Path("n-Xt_on_3D_mesh.vtk").exists() is False - - odw.process_results(statepoint_filename=h5m_filename, fusion_power=1e9) - - assert Path("heating_on_3D_mesh.vtk").exists() is True - assert Path("n-Xt_on_3D_mesh.vtk").exists() is True - def test_neutronics_component_3d_and_2d_mesh_simulation(self): """Makes a neutronics model and simulates with a 3D and 2D mesh tally and checks that the vtk and png files are produced. This checks the mesh ID values don't overlap""" - os.system("rm *.h5") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) materials = odw.Materials( @@ -403,21 +312,14 @@ def test_neutronics_component_3d_and_2d_mesh_simulation(self): assert len(results.meshes) == 4 # one 3D and three 2D assert len(results.tallies.items()) == 4 # one 3D and three 2D - odw.process_results(statepoint_filename=h5m_filename, fusion_power=1e9) - - assert Path(h5m_filename).exists() is True - assert Path("heating_on_3D_mesh.vtk").exists() is True - assert Path("heating_on_2D_mesh_xz.png").exists() is True - assert Path("heating_on_2D_mesh_xy.png").exists() is True - assert Path("heating_on_2D_mesh_yz.png").exists() is True - def test_neutronics_component_3d_and_2d_mesh_simulation_with_corner_points( self): """Makes a neutronics model and simulates with a 3D and 2D mesh tally and checks that the vtk and png files are produced. This checks the mesh ID values don't overlap""" - os.system("rm *.h5") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) materials = odw.Materials( @@ -453,19 +355,12 @@ def test_neutronics_component_3d_and_2d_mesh_simulation_with_corner_points( assert len(results.meshes) == 4 # one 3D and three 2D assert len(results.tallies.items()) == 4 # one 3D and three 2D - odw.process_results(statepoint_filename=h5m_filename, fusion_power=1e9) - - assert Path(h5m_filename).exists() is True - assert Path("heating_on_3D_mesh.vtk").exists() is True - assert Path("heating_on_2D_mesh_xz.png").exists() is True - assert Path("heating_on_2D_mesh_xy.png").exists() is True - assert Path("heating_on_2D_mesh_yz.png").exists() is True - def test_reactor_from_shapes_cell_tallies(self): """Makes a reactor from two shapes, then makes a neutronics model and tests the TBR simulation value""" - os.system("rm results.json") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) materials = odw.Materials( @@ -483,21 +378,16 @@ def test_reactor_from_shapes_cell_tallies(self): ) # performs an openmc simulation on the model - h5m_filename = my_model.run() - - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_power=1e9 - ) + statepoint_file = my_model.run() - assert isinstance(results["TBR"]["result"], float) - assert Path("results.json").exists() is True + assert Path(statepoint_file).exists() def test_cell_tallies_simulation_fast_flux(self): """Performs simulation with h5m file and tallies neutron and photon fast flux. Checks that entries exist in the results.""" - os.system("rm results.json") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) materials = odw.Materials( @@ -515,31 +405,16 @@ def test_cell_tallies_simulation_fast_flux(self): ) # performs an openmc simulation on the model - h5m_filename = my_model.run() - - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_power=1e9, - fusion_energy_per_pulse=1.2e6 - ) - - assert isinstance( - results["neutron_fast_flux"]["fast flux per source particle"]["result"], - float, - ) - assert isinstance( - results["flux"]["flux per source particle"]["result"], - float, - ) - - assert results["flux"]["flux per source particle"]["result"] > results[ - "neutron_fast_flux"]["fast flux per source particle"]["result"] + statepoint_file = my_model.run() + assert Path(statepoint_file).exists() + def test_cell_tallies_simulation_effective_dose(self): """Performs simulation with h5m file and tallies neutron and photon dose. Checks that entries exist in the results.""" - os.system("rm results.json statepoint*.h5") + os.system("rm statepoint.*.h5") + os.system("rm summary.h5") geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) materials = odw.Materials( @@ -557,99 +432,15 @@ def test_cell_tallies_simulation_effective_dose(self): ) # performs an openmc simulation on the model - h5m_filename = my_model.run() - - results = odw.process_results( - statepoint_filename=h5m_filename, - fusion_power=1e9, - fusion_energy_per_pulse=1.2e6 - ) + statepoint_file = my_model.run() - assert isinstance( - results["neutron_effective_dose"][ - "effective dose per source particle pSv cm3" - ]["result"], - float, - ) - assert isinstance( - results["neutron_effective_dose"][ - "pSv cm3 per pulse" - ]["result"], - float, - ) - assert isinstance( - results["neutron_effective_dose"][ - "pSv cm3 per second" - ]["result"], - float, - ) - - assert isinstance( - results["neutron_effective_dose"][ - "effective dose per source particle pSv cm3" - ]["std. dev."], - float, - ) - assert isinstance( - results["neutron_effective_dose"][ - "pSv cm3 per pulse" - ]["std. dev."], - float, - ) - assert isinstance( - results["neutron_effective_dose"][ - "pSv cm3 per second" - ]["std. dev."], - float, - ) - - assert isinstance( - results["photon_effective_dose"][ - "effective dose per source particle pSv cm3" - ]["result"], - float, - ) - assert isinstance( - results["photon_effective_dose"]["pSv cm3 per pulse"][ - "result" - ], - float, - ) - assert isinstance( - results["photon_effective_dose"][ - "pSv cm3 per second" - ]["result"], - float, - ) - - assert isinstance( - results["photon_effective_dose"][ - "effective dose per source particle pSv cm3" - ]["std. dev."], - float, - ) - assert isinstance( - results["photon_effective_dose"]["pSv cm3 per pulse"][ - "std. dev." - ], - float, - ) - assert isinstance( - results["photon_effective_dose"][ - "pSv cm3 per second" - ]["std. dev."], - float, - ) - - assert Path("results.json").exists() is True + assert Path(statepoint_file).exists() # @shimwell can you take a look at that please? # def test_reactor_from_shapes_2d_mesh_tallies(self): # """Makes a reactor from two shapes, then makes a neutronics model # and tests the TBR simulation value""" - # os.system("rm *_on_2D_mesh_*.png") - # geometry = odw.Geometry(h5m_filename=self.h5m_filename_smaller) # materials = odw.Materials( # h5m_filename=self.h5m_filename_smaller, @@ -666,19 +457,9 @@ def test_cell_tallies_simulation_effective_dose(self): # ) # # performs an openmc simulation on the model - # h5m_filename = my_model.run() - - # odw.process_results(statepoint_filename=h5m_filename, fusion_power=1e9) - - # assert Path("n-Xt_on_2D_mesh_xz.png").exists() is True - # assert Path("n-Xt_on_2D_mesh_xy.png").exists() is True - # assert Path("n-Xt_on_2D_mesh_yz.png").exists() is True - # assert Path("heating_on_2D_mesh_xz.png").exists() is True - # assert Path("heating_on_2D_mesh_xy.png").exists() is True - # assert Path("heating_on_2D_mesh_yz.png").exists() is True - # assert Path("flux_on_2D_mesh_xz.png").exists() is True - # assert Path("flux_on_2D_mesh_xy.png").exists() is True - # assert Path("flux_on_2D_mesh_yz.png").exists() is True + # statepoint_file = my_model.run() + + # assert Path(statepoint_file).exists() def test_simulations_with_missing_h5m_files(self): """Creates NeutronicsModel objects and tries to perform simulation diff --git a/tests/test_tallies/test_mesh_tally_2d.py b/tests/test_tallies/test_mesh_tally_2d.py index baab124..e6e12d2 100644 --- a/tests/test_tallies/test_mesh_tally_2d.py +++ b/tests/test_tallies/test_mesh_tally_2d.py @@ -89,8 +89,4 @@ def test_shape_of_resulting_png(self): tallies=tallies) statepoint_file = my_model.run() - odw.process_results(statepoint_file, fusion_power=1e9) - - assert Path("neutron_flux_on_2D_mesh_xy.png").exists() - assert Path("neutron_flux_on_2D_mesh_xz.png").exists() - assert Path("neutron_flux_on_2D_mesh_yz.png").exists() + assert Path(statepoint_file).exists() From 179e5349d3c0e8a1bd7a148490a0c07de61038c4 Mon Sep 17 00:00:00 2001 From: autopep8 Date: Mon, 18 Oct 2021 13:36:43 +0000 Subject: [PATCH 15/16] Automated autopep8 fixes --- tests/test_system/test_system_single_volume.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_system/test_system_single_volume.py b/tests/test_system/test_system_single_volume.py index 87e9253..a633cc8 100644 --- a/tests/test_system/test_system_single_volume.py +++ b/tests/test_system/test_system_single_volume.py @@ -109,7 +109,6 @@ def test_neutronics_component_simulation_with_openmc_mat(self): results = openmc.StatePoint(h5m_filename) assert len(results.tallies.items()) == 1 - def test_neutronics_component_simulation_with_nmm(self): """Makes a neutronics model and simulates with a cell tally""" @@ -408,7 +407,7 @@ def test_cell_tallies_simulation_fast_flux(self): statepoint_file = my_model.run() assert Path(statepoint_file).exists() - + def test_cell_tallies_simulation_effective_dose(self): """Performs simulation with h5m file and tallies neutron and photon dose. Checks that entries exist in the results.""" From 7d5f349f1da2b732fba1083db05f8f33c9892fb2 Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Thu, 21 Oct 2021 16:45:57 +0100 Subject: [PATCH 16/16] placeholder isotope material now made from cross_sections.xml contents; --- openmc_dagmc_wrapper/Geometry.py | 2 ++ openmc_dagmc_wrapper/utils.py | 41 ++++++++++++++++++++++---------- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/openmc_dagmc_wrapper/Geometry.py b/openmc_dagmc_wrapper/Geometry.py index 2a26366..bf48245 100644 --- a/openmc_dagmc_wrapper/Geometry.py +++ b/openmc_dagmc_wrapper/Geometry.py @@ -44,6 +44,7 @@ def make_root(self): if self.reflective_angles is None: # if a graveyard is not found in the dagmc geometry a CSG one is # made + if "graveyard" not in di.get_materials_from_h5m(self.h5m_filename): # vac_surfs = self.create_cube_of_vacuum_surfaces() # # creates a cube of surfaces for the boundary conditions @@ -93,6 +94,7 @@ def make_root(self): cell_id=9999, region=region, fill=dag_univ) root = [containing_cell] + return root def create_sphere_of_vacuum_surface(self): diff --git a/openmc_dagmc_wrapper/utils.py b/openmc_dagmc_wrapper/utils.py index db149ba..968796a 100644 --- a/openmc_dagmc_wrapper/utils.py +++ b/openmc_dagmc_wrapper/utils.py @@ -19,8 +19,7 @@ def create_material(material_tag: str, material_entry): if isinstance(material_entry, str): - openmc_material = nmm.Material.from_library( - name=material_entry, material_id=None + openmc_material = nmm.Material.from_library(name=material_entry, material_id=None ).openmc_material elif isinstance(material_entry, openmc.Material): # sets the material name in the event that it had not been set @@ -40,16 +39,38 @@ def create_material(material_tag: str, material_entry): return openmc_material -def create_openmc_materials(h5m_filename): +def get_an_isotope_present_in_cross_sections_xml(): + """Opens the xml file found with the OPENMC_CROSS_SECTIONS environmental + variable""" + + cross_sections_xml = os.getenv('OPENMC_CROSS_SECTIONS') + import xml.etree.ElementTree as ET + tree = ET.parse(cross_sections_xml) + root = tree.getroot() + for child in root[:1]: + available_isotope = child.attrib['materials'] + return available_isotope + + +def create_placeholder_openmc_materials(h5m_filename): + """This function creates a list of openmc materials with a single isotope. + The isotope used is found by opening the cross_sections.xml file and is + therefore likely to be available to openmc. When finding the bounding box + the DAGMC geometry is initialized and this requires a materials.xml file + with materials names that match the contents of the and the materials need + at least one isotope.""" materials_in_h5m = di.get_materials_from_h5m(h5m_filename) - openmc_materials = {} + openmc_materials = [] + placeholder_isotope = get_an_isotope_present_in_cross_sections_xml() for material_tag in materials_in_h5m: if material_tag != "graveyard": - openmc_material = create_material(material_tag, "Be") - openmc_materials[material_tag] = openmc_material + void_mat = openmc.Material() + void_mat.add_nuclide(placeholder_isotope, 1) + void_mat.name = material_tag + openmc_materials.append(void_mat) - return openmc.Materials(list(openmc_materials.values())) + return openmc.Materials(openmc_materials) def silently_remove_file(filename: str): @@ -97,12 +118,8 @@ def find_bounding_box(h5m_filename: str) -> List[Tuple[float, float, float]]: geometry.root_universe = dag_univ geometry.export_to_xml() - # exports materials.xml - # replace this with a empty materisl with the correct names - # self.create_openmc_materials() # @shimwell do we need this? - # openmc.Materials().export_to_xml() silently_remove_file("materials.xml") - materials = create_openmc_materials(h5m_filename) + materials = create_placeholder_openmc_materials(h5m_filename) materials.export_to_xml() openmc.Plots().export_to_xml()