def test_magic_multi_bins(): """Test multiple energy bins MAGIC case""" # create a basic meshtally coords = [[0, 1, 2], [-1, 3, 4], [10, 12]] flux_data = [[1.2, 3.3], [1.6, 1.7], [1.5, 1.4], [2.6, 1.0]] flux_error = [[0.11, 0.013], [0.14, 0.19], [0.02, 0.16], [0.04, 0.09]] tally = Mesh(structured=True, structured_coords=coords) tally.particle = "neutron" tally.e_bounds = [0.0, 0.5, 1.0] tally.n_flux = NativeMeshTag(2, float) tally.n_flux[:] = flux_data tally.n_rel_error = NativeMeshTag(2, float) tally.n_rel_error[:] = flux_error tolerance = 0.15 null_value = 0.001 magic(tally, "n_flux", "n_rel_error", tolerance=tolerance, null_value=null_value) expected_ww = [[0.2307692308, 0.5], [0.3076923077, 0.001], [0.2884615385, 0.001], [0.5, 0.15151515]] assert_array_almost_equal(tally.ww_x[:], expected_ww[:])
def test_magic_e_total(): """Test total energy group MAGIC case""" # create mesh coords = [[0, 1, 2], [-1, 3, 4], [10, 12]] flux_data = [1.2, 3.3, 1.6, 1.7] flux_error = [0.11, 0.013, 0.14, 0.19] tally = Mesh(structured=True, structured_coords=coords) tally.particle = "neutron" tally.e_bounds = [0.0, 0.5, 1.0] tally.n_total_flux = NativeMeshTag(1, float) tally.n_total_flux[:] = flux_data tally.n_rel_error = NativeMeshTag(1, float) tally.n_rel_error[:] = flux_error tolerance = 0.15 null_value = 0.001 magic(tally, "n_total_flux", "n_rel_error", tolerance=tolerance, null_value=null_value) expected_ww = [0.181818182, 0.5, 0.2424242, 0.001] assert_array_almost_equal(tally.ww_x[:], expected_ww[:])
def test_cadis_multiple_e(): """Test multiple energy group CADIS case""" adj_flux_tag = "adj_flux" q_tag = "q" ww_tag = "ww" q_bias_tag = "q_bias" # create meshes coords = [[0, 1, 2], [-1, 3, 4], [10, 12]] adj_flux_mesh = Mesh(structured=True, structured_coords=coords) q_mesh = Mesh(structured=True, structured_coords=coords) ww_mesh = Mesh(structured=True, structured_coords=coords) q_bias_mesh = Mesh(structured=True, structured_coords=coords) # add tags to input meshes adj_flux_mesh.adj_flux = NativeMeshTag(2, float) q_mesh.q = NativeMeshTag(2, float) # create data for input meshes adj_flux_data = [[1.1, 1.2], [1.3, 1.4], [0.0, 1.6], [1.7, 1.9]] q_data = [[2.9, 2.8], [2.6, 2.5], [2.4, 2.2], [2.9, 0.0]] # data data to mesh adj_flux_mesh.adj_flux[:] = adj_flux_data q_mesh.q[:] = q_data # run cadis cadis( adj_flux_mesh, adj_flux_tag, q_mesh, q_tag, ww_mesh, ww_tag, q_bias_mesh, q_bias_tag, beta=5, ) # expected results expected_q_bias = [ [0.0306200806, 0.0322518718], [0.0324438472, 0.0335956998], [0.0, 0.0337876752], [0.0473219428, 0.0], ] expected_ww = [ [0.3208302538, 0.2940943993], [0.2714717532, 0.2520809137], [0.0, 0.2205707995], [0.2075960465, 0.1857438311], ] ww_mesh.ww = NativeMeshTag(2, float) q_bias_mesh.q_bias = NativeMeshTag(2, float) assert_array_almost_equal(ww_mesh.ww[:], expected_ww[:]) assert_array_almost_equal(q_bias_mesh.q_bias[:], expected_q_bias[:])
def test_nativetag_broadcasting(): m = gen_mesh() # tags of length 1 m.horse = NativeMeshTag(1, float) m.horse[:] = 2.0 assert_array_equal(m.horse[:], [2.0] * 4) # tags of length > 1 m.grape = NativeMeshTag(2, float) # test broadcasing m.grape[[2, 0]] = [7.0, 8.0] assert_array_equal(m.grape[:], [[7.0, 8.0], [0.0, 0.0], [7.0, 8.0], [0.0, 0.0]])
def test_cadis_single_e(): """Test single energy group cadis case""" adj_flux_tag = "adj_flux" q_tag = "q" ww_tag = "ww" q_bias_tag = "q_bias" # create meshes coords = [[0, 1, 2], [-1, 3, 4], [10, 12]] adj_flux_mesh = Mesh(structured=True, structured_coords=coords) q_mesh = Mesh(structured=True, structured_coords=coords) ww_mesh = Mesh(structured=True, structured_coords=coords) q_bias_mesh = Mesh(structured=True, structured_coords=coords) # add tags to meshes adj_flux_mesh.adj_flux = NativeMeshTag(1, float) q_mesh.q = NativeMeshTag(1, float) # create data for input meshes adj_flux_data = [1.1, 1.3, 1.5, 1.7] q_data = [2.9, 2.6, 2.4, 2.2] # data data to mesh adj_flux_mesh.adj_flux[:] = adj_flux_data q_mesh.q[:] = q_data # run CADIS cadis( adj_flux_mesh, adj_flux_tag, q_mesh, q_tag, ww_mesh, ww_tag, q_bias_mesh, q_bias_tag, beta=5, ) # checkout output meshes expected_ww = [0.3995338, 0.33806706, 0.29299145, 0.258521908] expected_q_bias = [0.04652859, 0.04929988, 0.052508751, 0.0545507858] ww_mesh.ww = NativeMeshTag(1, float) q_bias_mesh.q_bias = NativeMeshTag(1, float) assert_array_almost_equal(ww_mesh.ww[:], expected_ww[:]) assert_array_almost_equal(q_bias_mesh.q_bias[:], expected_q_bias[:])
def test_rtflux_2D(): if not HAVE_PYMOAB: raise SkipTest from pyne.mesh import Mesh, NativeMeshTag rt = Rtflux("files_test_cccc/rtflux_2D") structured_coords = [[10 * x for x in range(8)], [0.0, 10, 20, 30, 40], [0.0, 1.0]] m = Mesh(structured=True, structured_coords=structured_coords) rt.to_mesh(m, "flux") m.tag = NativeMeshTag(4, float, name="flux") flux = m.tag[:] # test energy ordering assert (np.allclose( flux[0], [1.66764798e-03, 4.59426961e-02, 7.35252284e-02, 1.54202809e-02])) # test spatial ordering exp = [ 1.54202809e-02, 1.22833140e-02, 8.24652761e-03, 4.10247328e-03, 1.29812236e-02, 7.31613464e-03, 4.27769488e-03, 2.96312777e-03, 9.98971577e-03, 4.57188750e-03, 2.15025301e-03, 1.86188954e-03, 7.46111984e-03, 3.45483912e-03, 1.54143733e-03, 1.24946029e-03, 5.24386070e-03, 2.36004487e-03, 1.01537828e-03, 8.43692879e-04, 3.31488925e-03, 1.52156795e-03, 6.57790710e-04, 5.31460286e-04, 1.52433295e-03, 7.17349305e-04, 3.12441756e-04, 2.43518040e-04 ] assert (np.allclose(exp, flux[:, 3]))
def test_isotropic_vol_source(): """Test isotropic volumetric source generation from DAGMC geometry. """ try: from pyne import dagmc except: raise SkipTest if not HAVE_PYMOAB: raise SkipTest sc = np.linspace(-25, 25, 6) m = Mesh(structured=True, structured_coords=[sc, sc, sc]) cells = [14, 15] spectra = [[0.1, 0.1, 0.1, 0.7], [0.3, 0.3, 0.3, 0.1]] intensities = [1, 2] dg, s = partisn.isotropic_vol_source("files_test_partisn/source_boxes.h5m", m, cells, spectra, intensities, num_rays=4, tag_name="src", grid=True) m.src = NativeMeshTag(4, float) data = m.src[:] # setup expected result, confirmed by hand calcs and inspection exp = np.zeros(shape=((len(sc) - 1)**3, len(spectra[0]))) exp[22, :] = [0.025, 0.025, 0.025, 0.175] exp[62, :] = [0.075, 0.075, 0.075, 0.025] exp[63, :] = [0.075, 0.075, 0.075, 0.025] exp[87, :] = [0.075, 0.075, 0.075, 0.025] exp[88, :] = [0.075, 0.075, 0.075, 0.025] assert(np.allclose(data, exp))
def _create_mesh(self, part_data, error_data): """This will create the mesh object with the name of the tally specified by the user. One mesh object contains both the part_data and the error_data. """ super(UsrbinTally, self).__init__(structured_coords=[self.x_bounds, self.y_bounds, self.z_bounds], structured=True, structured_ordering='zyx', mats=None) self.part_data_tag = NativeMeshTag(size=1, dtype=float, mesh=self, name="part_data_{0}".format(self.particle)) self.error_data_tag = NativeMeshTag(size=1, dtype=float, mesh=self, name="error_data_{0}".format(self.particle)) self.part_data_tag[:] = part_data self.error_data_tag[:] = error_data
def test_total_photon_source_intensity_subvoxel(): # In the calculation of the total photon source intensities under subvoxel # mode, the volume fractions of each subvoxel should be multiplied # Set up 4 voxels with the volume of: 1, 2, 1, 2 m = Mesh(structured=True, structured_coords=[[0, 1, 2], [0, 1, 3], [0, 1]]) # 4 voxels, each voxel contains two subvoxels -> 8 subvoxels # The volume fraction of each subvoxel is 0.5 cell_fracs = np.zeros(8, dtype=[('idx', np.int64), ('cell', np.int64), ('vol_frac', np.float64), ('rel_error', np.float64)]) cell_fracs[:] = [(0, 11, 0.5, 0.0), (0, 12, 0.5, 0.0), (1, 11, 0.5, 0.0), (1, 12, 0.5, 0.0), (2, 13, 0.5, 0.0), (2, 11, 0.5, 0.0), (3, 12, 0.5, 0.0), (3, 13, 0.5, 0.0)] m.tag_cell_fracs(cell_fracs) # Set up the source density with energy group number of 2 m.source_density = NativeMeshTag(4, float) m.source_density[:] = [[0.0, 0.0, 1.0, 1.0], [2.0, 2.0, 3.0, 3.0], [4.0, 4.0, 5.0, 5.0], [6.0, 6.0, 7.0, 7.0]] intensity = total_photon_source_intensity(m, "source_density", True) # expected intensity: each line represents a mesh voxel # for each subvoxel: voxel_vol * cell_fracs * photon_intensity expected_intensity = 1 * 0.5 * (0.0 + 0.0) + 1 * 0.5 * (1.0 + 1.0) expected_intensity += 2 * 0.5 * (2.0 + 2.0) + 2 * 0.5 * (3.0 + 3.0) expected_intensity += 1 * 0.5 * (4.0 + 4.0) + 1 * 0.5 * (5.0 + 5.0) expected_intensity += 2 * 0.5 * (6.0 + 6.0) + 2 * 0.5 * (7.0 + 7.0) assert_equal(intensity, expected_intensity)
def to_mesh(self, m, tag_name): """This member function tags supplied PyNE Mesh object with the fluxes contained in the rtflux file. Parameters ---------- m: PyNE Mesh A PyNE Mesh object with same x, y, z intervals used to generate the rtflux file. tag_name: str The tag name to use to tag the fluxes onto the mesh. """ from pyne.mesh import HAVE_PYMOAB if HAVE_PYMOAB: from pyne.mesh import Mesh, NativeMeshTag else: warn( "The PyMOAB optional dependency could not be imported. " "All aspects of the partisn module are not imported.", QAWarning) if not m.structured: raise ValueError("Only structured mesh is supported.") mesh_dims = [len(x) - 1 for x in m.structured_coords] if mesh_dims != [self.ninti, self.nintj, self.nintk]: raise ValueError("Supplied mesh does not comform to rtflux bounds") temp = m.structured_ordering m.structured_ordering = 'zyx' m.tag = NativeMeshTag(self.ngroup, float, name=tag_name) m.tag[:] = self.flux m.structured_ordering = temp
def main(): msg = ("This script reads a mesh (.h5m) file and, for each vector tag of\n" "length N, creates N scalar tags. This is useful for visualizing\n" "data on mesh with programs that do not support vector tags.\n") parser = argparse.ArgumentParser(msg) parser.add_argument('mesh_file', help="The path the mesh file") parser.add_argument('-o', dest='output', default='expanded_tags.vtk', help="The name of the output file") parser.add_argument( "-t", "--tags", dest='tags', default=None, help=("Instead of expanding all tags, only expand tags\n" "within this list. Tag names listed here should\n" "be seperated by commas without spaces.\n")) args = parser.parse_args() try: from pymoab import types except ImportError: warn( "The PyMOAB optional dependency could not be imported. " "Some aspects of the mesh module may be incomplete.", ImportWarning) try: m = Mesh(structured=True, mesh=args.mesh_file) except types.MB_TAG_NOT_FOUND: sys.stderr.write('Structured mesh not found\n \ trying unstructured mesh \n') m = Mesh(structured=False, mesh=args.mesh_file) if args.tags is not None: tags = args.tags.split(',') else: tags = [] for name, tag in m.tags.items(): if isinstance(tag, NativeMeshTag) and name != 'idx': tags.append(name) for tag in tags: m.tag = NativeMeshTag(name=tag) # there may be vector tags try: # this line fails if the tag is a scalar tag m.tag.size = len(m.tag[0]) except TypeError: sys.stderr.write('Vector tag not found, assuming scalar tag \n') m.tag.size = 1 if m.tag.size > 1: print("Expanding tag: {}".format(tag)) m.tag.expand() print("Saving file {}".format(args.output)) m.write_hdf5(args.output) print("Complete")
def test_photon_sampling_setup_structured(): phtn_src = os.path.join(thisdir, "files_test_r2s", "phtn_src") coords = [[0, 1, 2], [0, 1, 2], [0, 1]] m = Mesh(structured=True, structured_coords=coords) tags = {(10010000, "1 h"): "tag1", ("TOTAL", "shutdown"): "tag2"} photon_sampling_setup(m, phtn_src, tags) exp_tag1 = [[1.1, 2.2], [3.3, 4.4], [5.5, 6.6], [7.7, 8.8]] exp_tag2 = [[11.1, 12.2], [13.3, 14.4], [15.5, 16.6], [17.7, 18.8]] m.tag1 = NativeMeshTag(2, float) m.tag2 = NativeMeshTag(2, float) for i, mat, ve in m: assert_array_equal(m.tag1[i], exp_tag1[i]) assert_array_equal(m.tag2[i], exp_tag2[i])
def test_total_photon_source_intensity(): m = Mesh(structured=True, structured_coords=[[0, 1, 2], [0, 1, 3], [0, 1]]) m.source_density = NativeMeshTag(2, float) m.source_density[:] = [[1., 2.], [3., 4.], [5., 6.], [7., 8.]] intensity = total_photon_source_intensity(m, "source_density") assert_equal(intensity, 58)
def test_del_nativetag(): mats = { 0: Material({ 'H1': 1.0, 'K39': 1.0 }, density=42.0), 1: Material({ 'H1': 0.1, 'O16': 1.0 }, density=43.0), 2: Material({'He4': 42.0}, density=44.0), 3: Material({'Tm171': 171.0}, density=45.0), } m = gen_mesh(mats=mats) m.f = NativeMeshTag(mesh=m, name='f') m.f[:] = [1.0, 2.0, 3.0, 4.0] m.g = NativeMeshTag(mesh=m, name='g') m.g[:] = [1.0, 2.0, 3.0, 4.0] assert_raises(ValueError, m.delete_tag, -12) import sys # make a new reference to the tag that will not # be deleted tag_ref = m.f # deleting tag by tag name m.delete_tag('f') # ensure that there are only 2 references to this tag # 1. is the tag_ref created above # 2. is the one that automatically is the temporary # reference created as the argument to getrefcount assert_equal(2, sys.getrefcount(tag_ref)) assert_raises(RuntimeError, m.mesh.tag_get_handle, 'f') # deleting tag by tag handle tag_ref = m.g m.delete_tag(m.g) assert_equal(2, sys.getrefcount(tag_ref)) assert_raises(RuntimeError, m.mesh.tag_get_handle, 'g')
def mesh_to_isotropic_source(m, tag): """This function reads an isotropic source definition from a supplied mesh and creates a corresponding PARTISN SOURCF input card. The input card wraps to 80 characters and utilizes the "R" repeation notation for zero values (e.g. 4R 0 = 0 0 0 0). Parameters: ----------- m : PyNE Mesh The mesh tagged with an energy-dependent source distribution. tag : str The tag on the mesh with the source information. Returns: -------- s : str SOURF input card wrapped to 80 characters. """ # get data temp = m.structured_ordering m.structured_ordering = "zyx" m.src = NativeMeshTag(name=tag) data = m.src[:].transpose()[::-1] m.structured_ordering = temp ninti = len(m.structured_coords[0]) - 1 # format output s = "sourcf=" count = 1 zero_count = 0 for e_row in data: for src in e_row: if src == 0.0: zero_count += 1 else: if zero_count != 0: if zero_count == 1: s += " 0" else: s += " {}R 0".format(zero_count) zero_count = 0 s += " {0:9.5E}".format(src) if count % ninti == 0: if zero_count != 0: if zero_count == 1: s += " 0" else: s += " {}R 0".format(zero_count) zero_count = 0 s += ";" count += 1 # wrap to 80 characters s = "\n".join(wrap(s, 80)) return s
def test_lazytaginit(): m = gen_mesh() m.cactus = NativeMeshTag(3, 'i') m.cactus[:] = np.array([42, 43, 44]) assert_in('cactus', m.tags) assert_array_equal(m.cactus[0], [42, 43, 44]) x = np.arange(len(m))[:, np.newaxis] * np.array([42, 43, 44]) m.cactus[:] = x assert_array_equal(m.cactus[2], x[2])
def test_magic_below_tolerance(): """Test MAGIC case when all flux errors are below the default tolerance""" # create mesh coords = [[0, 1, 2], [-1, 3, 4], [10, 12]] flux_data = [1.2, 3.3, 1.6, 1.7] flux_error = [0.11, 0.013, 0.14, 0.19] tally = Mesh(structured=True, structured_coords=coords) tally.particle = "neutron" tally.e_bounds = [0.0, 0.5, 1.0] tally.n_total_flux = NativeMeshTag(1, float) tally.n_total_flux[:] = flux_data tally.n_rel_error = NativeMeshTag(1, float) tally.n_rel_error[:] = flux_error magic(tally, "n_total_flux", "n_rel_error") expected_ww = [0.181818182, 0.5, 0.2424242, 0.2575757576] assert_array_almost_equal(tally.ww_x[:], expected_ww[:])
def test_nativetag_fancy_indexing(): m = gen_mesh() # tags of length 1 m.horse = NativeMeshTag(1, float) # test fancy indexing m.horse[[2, 0]] = [3.0, 1.0] assert_array_equal(m.horse[:], [1.0, 0.0, 3.0, 0.0]) m.horse[[2]] = [7.0] assert_array_equal(m.horse[:], [1.0, 0.0, 7.0, 0.0]) # tags of length > 1 m.grape = NativeMeshTag(2, float) # test fancy indexing m.grape[[2, 0]] = [[3.0, 4.0], [5.0, 6.0]] assert_array_equal(m.grape[:], [[5.0, 6.0], [0.0, 0.0], [3.0, 4.0], [0.0, 0.0]]) m.grape[[2]] = [[13.0, 14.0]] assert_array_equal(m.grape[:], [[5.0, 6.0], [0.0, 0.0], [13.0, 14.0], [0.0, 0.0]]) m.grape[1] = [23.0, 24.0] assert_array_equal(m.grape[:], [[5.0, 6.0], [23.0, 24.0], [13.0, 14.0], [0.0, 0.0]])
def test_mesh_to_isotropic_source(): """Test isotropic SOURCF generation. """ try: from pyne import dagmc except: raise SkipTest if not HAVE_PYMOAB: raise SkipTest m = Mesh(structured=True, structured_coords=[range(5), range(5), range(5)]) m.src = NativeMeshTag(4, float) # These source values were carefully choosen so that: # 1. The iteration order could be visually checked based on RTFLUX output using # the resulting SOURCF card. # 2. The repeation capability (i.e. 3R 0 = 0 0 0) could be tested. m.src[:] = [[0, 0, 0, 100], [0, 0, 0, 0], [0, 0, 0, 6], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [ 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 100, 0], [0, 0, 0, 5], [0, 0, 0, 6], [ 0, 0, 0, 0], [0, 0, 0, 8], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [ 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 100, 0, 0], [0, 0, 0, 5], [0, 0, 0, 0], [ 0, 0, 0, 7], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [ 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [ 0, 0, 0, 7], [0, 0, 0, 8], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [ 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] out = partisn.mesh_to_isotropic_source(m, "src") exp = ("sourcf= 1.00000E+02 3R 0; 0 8.00000E+00 0 8.00000E+00; 4R 0; 4R 0; 0 5.00000E+00\n" "5.00000E+00 0; 4R 0; 4R 0; 4R 0; 6.00000E+00 6.00000E+00 2R 0; 4R 0; 4R 0; 4R 0;\n" "2R 0 7.00000E+00 7.00000E+00; 4R 0; 4R 0; 4R 0; 0 1.00000E+02 2R 0; 4R 0; 4R 0;\n" "4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 2R\n" "0 1.00000E+02 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R\n" "0; 4R 0; 4R 0; 4R 0; 4R 0; 3R 0 1.00000E+02; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0;\n" "4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0; 4R 0;") assert(out == exp)
def test_nativetag(): mats = { 0: Material({ 'H1': 1.0, 'K39': 1.0 }, density=42.0), 1: Material({ 'H1': 0.1, 'O16': 1.0 }, density=43.0), 2: Material({'He4': 42.0}, density=44.0), 3: Material({'Tm171': 171.0}, density=45.0), } m = gen_mesh(mats=mats) m.f = NativeMeshTag(mesh=m, name='f') m.f[:] = [1.0, 2.0, 3.0, 4.0] # Getting tags assert_equal(m.f[0], 1.0) assert_array_equal(m.f[::2], [1.0, 3.0]) mask = np.array([True, False, True, True], dtype=bool) assert_array_equal(m.f[mask], [1.0, 3.0, 4.0]) assert_array_equal(m.f[1, 0, 1, 3], [2.0, 1.0, 2.0, 4.0]) # setting tags m.f[0] = 65.0 assert_equal(m.f[0], 65.0) m.f[::2] = 18.0 m.f[1::2] = [36.0, 54.0] assert_array_equal(m.f[:], np.array([18.0, 36.0, 18.0, 54.0])) mask = np.array([True, False, True, True], dtype=bool) m.f[mask] = 9.0 mask = np.array([True, True, False, False], dtype=bool) m.f[mask] = (19.0, 29.0) assert_array_equal(m.f[:], np.array([19.0, 29.0, 9.0, 9.0])) m.f[[2]] = 28.0 m.f[3, 1] = 6.0, 4128.0 assert_array_equal(m.f[1:], np.array([4128.0, 28.0, 6.0])) # deleting tag del m.f[:]
def test_rt_flux_1D(): if not HAVE_PYMOAB: raise SkipTest from pyne.mesh import Mesh, NativeMeshTag rt = Rtflux("files_test_cccc/rtflux_1D") structured_coords = [[10 * x for x in range(8)], [0.0, 1.0], [0.0, 1.0]] m = Mesh(structured=True, structured_coords=structured_coords) rt.to_mesh(m, "flux") m.tag = NativeMeshTag(4, float, name="flux") flux = m.tag[:] exp = [[1.13102481e-03, 2.48423595e-02, 4.07499865e-02, 1.12382315e-02], [1.22305619e-03, 2.06497203e-02, 2.49217686e-02, 4.70910079e-03], [9.99735815e-04, 1.35176066e-02, 1.08674872e-02, 1.10359953e-03], [6.18705350e-04, 7.42586666e-03, 4.91338778e-03, 5.60093921e-04], [3.40591572e-04, 3.81165736e-03, 2.18964779e-03, 1.75256136e-04], [1.65193192e-04, 1.78217782e-03, 9.88094844e-04, 1.16255047e-04], [5.67537762e-05, 6.01543637e-04, 3.08311260e-04, 1.42177473e-05]] assert (np.allclose(exp, flux))
def test_atflux_eng_order(): """Ensure the energy order is read in reverse for atflux file.""" if not HAVE_PYMOAB: raise SkipTest from pyne.mesh import Mesh, NativeMeshTag # This file is created with: source=1 174R 0 0 1 40R 0 # So only the 2 highest energy photon groups and the 1 highest energy # neutron group should have non-zero fluxes. at = Atflux("files_test_cccc/atflux_eng_order") sc = [np.linspace(-100, 100, 5), np.linspace(-100, 100, 5), np.linspace(0, 330, 5)] m = Mesh(structured=True, structured_coords=sc, mats=None) at.to_mesh(m, "flux") m.flux = NativeMeshTag(217, float) assert_array_almost_equal( m.flux[0], np.array( [0] * 40 + [57.3204927667, 1.16690395827] + [0] * 174 + [14.2312186922] ), )
def test_rtflux_3D(): if not HAVE_PYMOAB: raise SkipTest from pyne.mesh import Mesh, NativeMeshTag rt = Rtflux("files_test_cccc/rtflux_3D") structured_coords = [[0.0, 30.0, 40.0, 50.0, 70.0], [0.0, 15.0, 40.0, 50.0, 70.0], [0.0, 20.0, 75.0, 130.0, 150.0]] m = Mesh(structured=True, structured_coords=structured_coords) rt.to_mesh(m, "flux") m.tag = NativeMeshTag(4, float, name="flux") flux = m.tag[:] # test energy ordering assert (np.allclose( flux[0], [2.66320088e-06, 7.48262958e-05, 1.20151503e-04, 2.34609601e-05])) # test spatial ordering exp = [ 2.34609601e-05, 6.06449525e-05, 6.06449525e-05, 2.34609601e-05, 1.93416323e-05, 4.99965586e-05, 4.99965586e-05, 1.93416323e-05, 1.37740815e-05, 3.55703333e-05, 3.55703333e-05, 1.37740815e-05, 6.93809615e-06, 1.78326363e-05, 1.78326363e-05, 6.93809615e-06, 7.28244260e-06, 1.82284016e-05, 1.82284016e-05, 7.28244260e-06, 6.00219150e-06, 1.50229626e-05, 1.50229626e-05, 6.00219150e-06, 4.28577852e-06, 1.07128320e-05, 1.07128320e-05, 4.28577852e-06, 2.22228994e-06, 5.52725252e-06, 5.52725252e-06, 2.22228994e-06, 2.09818192e-06, 4.99869927e-06, 4.99869927e-06, 2.09818192e-06, 1.72912792e-06, 4.11851949e-06, 4.11851949e-06, 1.72912792e-06, 1.24560384e-06, 2.96332430e-06, 2.96332430e-06, 1.24560384e-06, 6.68628056e-07, 1.58531510e-06, 1.58531510e-06, 6.68628056e-07, 5.91257887e-07, 1.38688199e-06, 1.38688199e-06, 5.91257887e-07, 4.88278620e-07, 1.14497300e-06, 1.14497300e-06, 4.88278620e-07, 3.55008243e-07, 8.31776241e-07, 8.31776241e-07, 3.55008243e-07, 1.91609508e-07, 4.46100170e-07, 4.46100170e-07, 1.91609508e-07 ] assert (np.allclose(exp, flux[:, 3]))
def test_nativetag_expand(): m = Mesh(structured=True, structured_coords=[[-1, 0, 1], [0, 1], [0, 1]]) m.clam = NativeMeshTag(2, float) m.clam[:] = [[1.1, 2.2], [3.3, 4.4]] m.clam.expand() m.clam_000 = NativeMeshTag(1, float) assert_array_equal(m.clam_000[:], [1.1, 3.3]) m.clam_001 = NativeMeshTag(1, float) assert_array_equal(m.clam_001[:], [2.2, 4.4]) # corner case: mesh with a single volume element m = Mesh(structured=True, structured_coords=[[0, 1], [0, 1], [0, 1]]) m.clam = NativeMeshTag(2, float) m.clam[:] = [[1.1, 2.2]] m.clam.expand() m.clam_000 = NativeMeshTag(1, float) assert_array_equal(m.clam_000[:], 1.1) m.clam_001 = NativeMeshTag(1, float) assert_array_equal(m.clam_001[:], 2.2)
def isotropic_vol_source(geom, mesh, cells, spectra, intensities, **kwargs): """This function creates an isotropic volumetric source within each requested geometry cell of a DAGMC CAD geometry. This is done by Monte Carlo ray tracing to determine volume fractions of each source cell within each mesh volume element. The PARTISN SOURCF card is returned, as well as the ray-traced volume fractions (dagmc.discretize_geom output), so that ray tracing does not have to be done twice when using this function with write_partisn_input. The supplied mesh is also tagged with the calculated source distribution using this function. Parameters: ----------- geom : str The DAGMC geometry (.h5m) file containing the geometry of interest. mesh : PyNE Mesh The superimposed Cartesian mesh that will be used to define the source for PARTISN transport. cells : list of ints The cell numbers of DAGMC geometry cells which have non-zero source intensity. spectra : list of list of floats The normalized energy spectrum for each of the cells. If spectra are not normalized, they will be normalized in this function. intensities : list of floats The volumetric intensity (i.e. s^-1 cm^-3) for each geometry cell. tag_name : str, optional, default = 'src' The name of the tag for which source data will be tagged on the mesh. num_rays : int, optional, default = 10 For discretize_geom. The number of rays to fire in each mesh row for each direction. grid : boolean, optional, default = False For discretize_geom. If false, rays starting points are chosen randomly (on the boundary) for each mesh row. If true, a linearly spaced grid of starting points is used, with dimension sqrt(num_rays) x sqrt(num_rays). In this case, "num_rays" must be a perfect square. Returns: -------- output : str PARTISN SOURF card representing the requested source dg : record array The output of dagmc.discretize_geom; stored in a one dimensional array, each entry containing the following fields: :idx: int The volume element index. :cell: int The geometry cell number. :vol_frac: float The volume fraction of the cell withing the mesh ve. :rel_error: float The relative error associated with the volume fraction. This array is returned in sorted order with respect to idx and cell, with cell changing fastest. """ # discretize_geom inputs tag_name = kwargs.get("tag_name", "src") num_rays = kwargs.get("num_rays", 10) grid = kwargs.get("grid", False) # Check lengths of input if len(cells) != len(spectra) or len(cells) != len(intensities): raise ValueError("Cells, spectra, intensities must be the same length") lengths = [len(x) for x in spectra] if not all(lengths[0] == length for length in lengths): raise ValueError("Spectra must all be the same length") # Normalize spectra norm_spectra = [] for spec in spectra: total = np.sum(spec) norm_spectra.append(np.array(spec) / total) norm_spectra = {cell: spec for cell, spec in zip(cells, norm_spectra)} intensities = {cell: inten for cell, inten in zip(cells, intensities)} # ray trace if not HAVE_DAGMC: raise RuntimeError("DAGMC is not available." "Cannot run isotropic_vol_source().") else: dagmc.load(geom) dg = dagmc.discretize_geom(mesh, num_rays=num_rays, grid=grid) # determine source intensities data = np.zeros(shape=(len(mesh), len(spectra[0]))) for row in dg: if row[1] in cells: data[row[0], :] += np.multiply(row[2] * intensities[row[1]], norm_spectra[row[1]]) mesh.tag = NativeMeshTag(len(spectra[0]), float, name=tag_name) mesh.tag[:] = data output = mesh_to_isotropic_source(mesh, tag_name) return output, dg
def irradiation_setup_unstructured(flux_tag="n_flux"): meshtal_filename = "meshtal_2x2x1" meshtal_file = os.path.join(thisdir, "files_test_r2s", meshtal_filename) meshtal = Meshtal( meshtal_file, { 4: (flux_tag, flux_tag + "_err", flux_tag + "_total", flux_tag + "_err_total") }) # Explicitly make this mesh unstructured, it will now iterate in yxz # order which is MOAB structured mesh creation order. meshtal = Mesh(structured=False, mesh=meshtal.tally[4].mesh) meshtal_mesh_file = os.path.join(thisdir, "meshtal.h5m") meshtal.write_hdf5(meshtal_mesh_file, write_mats=False) if flux_tag != "n_flux": # if not using n_flux makes a mesh containing n_flux tag, and then # makes a new tag called flux_tag, to use later in the test flux_tag_name = "n_flux" meshtal = Meshtal( meshtal_file, { 4: (flux_tag_name, flux_tag_name + "_err", flux_tag_name + "_total", flux_tag_name + "_err_total") }) # Explicitly make this mesh unstructured, it will now iterate in yxz # order which is MOAB structured mesh creation order. meshtal = Mesh(structured=False, mesh=meshtal.tally[4].mesh) meshtal_mesh_file = os.path.join(thisdir, "meshtal.h5m") meshtal.write_hdf5(meshtal_mesh_file, write_mats=False) new_mesh = Mesh(structured=False, mesh=meshtal_mesh_file) new_mesh.TALLY_TAG = NativeMeshTag(2, float) # 2 egroups new_mesh.TALLY_TAG = meshtal.n_flux[:] # overwrite the mesh file new_mesh.write_hdf5(meshtal_mesh_file, write_mats=False) cell_mats = { 2: Material({2004: 1.0}, density=1.0, metadata={'name': 'mat_11'}), 3: Material({ 3007: 0.4, 3006: 0.6 }, density=2.0, metadata={'name': 'mat_12'}) } alara_params = "Bogus line for testing\n" geom = os.path.join(thisdir, "unitbox.h5m") fluxin = os.path.join(os.getcwd(), "alara_fluxin") reverse = True alara_inp = os.path.join(os.getcwd(), "alara_inp") alara_matlib = os.path.join(os.getcwd(), "alara_matlib") output_mesh = os.path.join(os.getcwd(), "r2s_step1.h5m") output_material = True cell_fracs = np.zeros(4, dtype=[('idx', np.int64), ('cell', np.int64), ('vol_frac', np.float64), ('rel_error', np.float64)]) cell_fracs[:] = [(0, 3, 1.0, 1.0), (1, 3, 1.0, 1.0), (2, 3, 1.0, 1.0), (3, 3, 1.0, 1.0)] irradiation_setup(flux_mesh=meshtal_mesh_file, cell_mats=cell_mats, cell_fracs=cell_fracs, alara_params=alara_params, flux_tag=flux_tag, fluxin=fluxin, reverse=reverse, alara_inp=alara_inp, alara_matlib=alara_matlib, output_mesh=output_mesh, output_material=output_material) # expected output files exp_alara_inp = os.path.join(thisdir, "files_test_r2s", "exp_alara_inp_un") exp_alara_matlib = os.path.join(thisdir, "files_test_r2s", "exp_alara_matlib") exp_fluxin = os.path.join(thisdir, "files_test_r2s", "exp_fluxin_un") # test files f1 = filecmp.cmp(alara_inp, exp_alara_inp) f2 = filecmp.cmp(alara_matlib, exp_alara_matlib) f3 = filecmp.cmp(fluxin, exp_fluxin) m = Mesh(structured=True, mesh=output_mesh, mats=output_mesh) out = [ m.n_flux[:].tolist(), m.n_flux_err[:].tolist(), m.n_flux_total[:].tolist(), m.n_flux_err_total[:].tolist(), [x.comp.items() for y, x, z in m], [x.density for y, x, z in m] ] n_flux = out[0] n_flux_err = out[1] n_flux_total = out[2] n_flux_err_total = out[3] densities = out[5] comps = np.zeros(shape=(len(out[4])), dtype=dict) for i, comp in enumerate(out[4]): comps[i] = {} for nucid in comp: comps[i][nucid[0]] = nucid[1] # test r2s step 1 output mesh fluxes = [[6.93088E-07, 1.04838E-06], [6.36368E-07, 9.78475E-07], [5.16309E-07, 9.86586E-07], [6.36887E-07, 9.29879E-07]] errs = [[9.67452E-02, 7.55950E-02], [9.88806E-02, 7.61482E-02], [1.04090E-01, 7.69284E-02], [9.75826E-02, 7.54181E-02]] tot_fluxes = [1.74147E-06, 1.61484E-06, 1.50290E-06, 1.56677E-06] tot_errs = [6.01522E-02, 6.13336E-02, 6.19920E-02, 5.98742E-02] i = 0 for nf, nfe, nft, nfte, comp, density in izip(n_flux, n_flux_err, n_flux_total, n_flux_err_total, comps, densities): assert_almost_equal(density, 2.0) assert_equal(len(comp), 2) assert_almost_equal(comp[30060000], 0.6) assert_almost_equal(comp[30070000], 0.4) assert_array_equal(nf, fluxes[i]) assert_array_equal(nfe, errs[i]) assert_almost_equal(nft, tot_fluxes[i]) assert_almost_equal(nfte, tot_errs[i]) i += 1 os.remove(meshtal_mesh_file) os.remove(alara_inp) os.remove(alara_matlib) os.remove(fluxin) os.remove(output_mesh) return [f1, f2, f3]
def step5(cfg, cfg2, cfg5): """ This function creates the adjoint neutron source and writes the PARTISN input file for adjoint neutron transport. Parameters ---------- cfg : dictionary User input from 'general' section of config.yml file cfg2 : dictionary User input for step 2 from the config.yml file cfg5 : dictionary User input for step 3 from the config.yml file """ # Get user-input from config file num_n_groups = cfg['n_groups'] num_p_groups = cfg['p_groups'] n_geom = cfg2['n_geom_file'] decay_times = str(cfg2['decay_times']).split(' ') meshflux = cfg5['meshflux'] # Base of geometry file name basename = n_geom.split("/")[-1].split(".")[0] # The total number of photon and neutron energy groups total_num_groups = num_n_groups + num_p_groups # Read given flux file and tag to a mesh if meshflux: # Adjoint flux file is an hdf5 mesh file fw_n_err = meshflux m = Mesh(structured=True, mesh=fw_n_err, mats=None) else: raise RuntimeError("No neutron flux file given") # Size of flux tag is equal to the total number of energy groups m.ERROR_TAG = NativeMeshTag(num_n_groups, name="ERROR_TAG") fw_n_err = m.ERROR_TAG[:] # Load geometry and get material assignments load(n_geom) ml = MaterialLibrary(n_geom) mat_names = list(ml.keys()) cell_mats = cell_material_assignments(n_geom) # Load T matrix if not os.path.exists('step2_T.npy'): raise RuntimeError("T matrix from step 2 (step2_T.npy) not found") T = np.load('step2_T.npy') # Loop over mesh voxels and calculate the error in the photon source by multiplying neutron flux and T matrix dg = discretize_geom(m) for t, dt in enumerate(decay_times): temp = np.zeros(shape=(len(m), num_p_groups)) for i in range(len(m)): for row in np.atleast_1d(dg[dg["idx"] == i]): cell = row[1] if not cell_mats[cell] in mat_names: continue vol_frac = row[2] mat = mat_names.index(cell_mats[cell]) for h in range(num_p_groups): for g in range(num_n_groups): temp[i, h] += (fw_n_err[i, g]**2) * T[mat, t, g, h] * vol_frac print("err ", temp[i, h]) # Tag the mesh with the squared error in the photon source values tag_name = "sq_err_q_src_{0}".format(dt) m.err_q_src = NativeMeshTag(num_p_groups, name=tag_name) m.err_q_src[:] = temp # Save adjoint neutron source mesh file tagged with values for all decay times m.save("sq_err_q_src.h5m")
def irradiation_setup_unstructured(flux_tag="n_flux"): meshtal_filename = "meshtal_2x2x1" meshtal_file = os.path.join(thisdir, "files_test_r2s", meshtal_filename) meshtal = Meshtal( meshtal_file, { 4: (flux_tag, flux_tag + "_err", flux_tag + "_total", flux_tag + "_err_total") }) # Explicitly make this mesh unstructured, it will now iterate in yxz # order which is MOAB structured mesh creation order. meshtal = Mesh(structured=False, mesh=meshtal.tally[4].mesh) meshtal_mesh_file = os.path.join(thisdir, "meshtal.h5m") meshtal.write_hdf5(meshtal_mesh_file, write_mats=False) if flux_tag != "n_flux": # if not using n_flux makes a mesh containing n_flux tag, and then # makes a new tag called flux_tag, to use later in the test flux_tag_name = "n_flux" meshtal = Meshtal( meshtal_file, { 4: (flux_tag_name, flux_tag_name + "_err", flux_tag_name + "_total", flux_tag_name + "_err_total") }) # Explicitly make this mesh unstructured, it will now iterate in yxz # order which is MOAB structured mesh creation order. meshtal = Mesh(structured=False, mesh=meshtal.tally[4].mesh) meshtal_mesh_file = os.path.join(thisdir, "meshtal.h5m") meshtal.write_hdf5(meshtal_mesh_file, write_mats=False) new_mesh = Mesh(structured=False, mesh=meshtal_mesh_file) new_mesh.TALLY_TAG = NativeMeshTag(2, float) # 2 egroups new_mesh.TALLY_TAG = meshtal.n_flux[:] # overwrite the mesh file new_mesh.write_hdf5(meshtal_mesh_file, write_mats=False) cell_mats = { 2: Material({2004: 1.0}, density=1.0, metadata={'name': 'mat_11'}), 3: Material({ 3007: 0.4, 3006: 0.6 }, density=2.0, metadata={'name': 'mat_12'}) } alara_params = "Bogus line for testing\n" geom = os.path.join(thisdir, "unitbox.h5m") fluxin = os.path.join(os.getcwd(), "alara_fluxin") reverse = True alara_inp = os.path.join(os.getcwd(), "alara_inp") alara_matlib = os.path.join(os.getcwd(), "alara_matlib") output_mesh = os.path.join(os.getcwd(), "r2s_step1.h5m") output_material = True cell_fracs = np.zeros(4, dtype=[('idx', np.int64), ('cell', np.int64), ('vol_frac', np.float64), ('rel_error', np.float64)]) cell_fracs[:] = [(0, 3, 1.0, 1.0), (1, 3, 1.0, 1.0), (2, 3, 1.0, 1.0), (3, 3, 1.0, 1.0)] irradiation_setup(flux_mesh=meshtal_mesh_file, cell_mats=cell_mats, cell_fracs=cell_fracs, alara_params=alara_params, flux_tag=flux_tag, fluxin=fluxin, reverse=reverse, alara_inp=alara_inp, alara_matlib=alara_matlib, output_mesh=output_mesh, output_material=output_material) # expected output files exp_alara_inp = os.path.join(thisdir, "files_test_r2s", "exp_alara_inp_un") exp_alara_matlib = os.path.join(thisdir, "files_test_r2s", "exp_alara_matlib") exp_fluxin = os.path.join(thisdir, "files_test_r2s", "exp_fluxin_un") # test files f1 = filecmp.cmp(alara_inp, exp_alara_inp) f2 = filecmp.cmp(alara_matlib, exp_alara_matlib) f3 = filecmp.cmp(fluxin, exp_fluxin) m = Mesh(structured=True, mesh=output_mesh, mats=output_mesh) m_out = [ m.n_flux[:].tolist(), m.n_flux_err[:].tolist(), m.n_flux_total[:].tolist(), m.n_flux_err_total[:].tolist(), [x.comp.items() for y, x, z in m], [x.density for y, x, z in m] ] os.remove(meshtal_mesh_file) os.remove(alara_inp) os.remove(alara_matlib) os.remove(fluxin) os.remove(output_mesh) return [m_out, f1, f2, f3]
def magic(meshtally, tag_name, tag_name_error, **kwargs): """This function reads a PyNE mcnp.MeshTally object and preforms the MAGIC algorithm and returns the resulting weight window mesh. Parameters: ----------- meshtally : a single PyNE mcnp.MeshTally obj tag_name : string The meshtally tag_name (example: n_result or n_total_result). tag_name_error : string The meshtally tag_name for the error associated with provided tag_name. Example: n_rel_error tolerance : float, optional The maximum relative error allowable for the MAGIC algorithm to create a weight window lower bound for for a given mesh volume element for the intial weight window lower bound generation, or overwrite preexisting weight window lower bounds for subsequent iterations. null_value : float, optional The weight window lower bound value that is assigned to mesh volume elements where the relative error on flux exceeds the tolerance. """ tolerance = kwargs.get('tolerance', 0.5) null_value = kwargs.get('null_value', 0.0) # Convert particle name to the recognized abbreviation particle = (meshtally.particle.capitalize()) if particle == ("Neutron" or "Photon" or "Electron"): meshtally.particle = mcnp(particle).lower() # Create tags for values and errors meshtally.vals = NativeMeshTag(mesh=meshtally, name=tag_name) meshtally.errors = NativeMeshTag(mesh=meshtally, name=tag_name_error) # Create weight window tags tag_size = meshtally.vals[0].size meshtally.ww_x = NativeMeshTag(tag_size, float, name="ww_{0}".format(meshtally.particle)) meshtally.tag("{0}_e_upper_bounds".format(meshtally.particle), np.zeros(tag_size, dtype=float), 'nat_mesh', size=tag_size, dtype=float) root_tag = meshtally.get_tag("{0}_e_upper_bounds".format( meshtally.particle)) # Determine if total energy or single energy bin or multiple energy bins if tag_size == 1 and len(meshtally.e_bounds) > 1: total = True elif tag_size == 1 and len(meshtally.e_bounds) == 1: total = True elif tag_size > 1 and len(meshtally.e_bounds) > 1: total = False # Reassign arrays for total and not total case if total: # get value tagged on the mesh itself root_tag[meshtally] = np.max(meshtally.e_bounds[:]) max_val = np.max(meshtally.vals[:]) vals = [] errors = [] for flux, error in zip(meshtally.vals[:], meshtally.errors[:]): vals.append(np.atleast_1d(flux)) errors.append(np.atleast_1d(error)) vals = np.array(vals) errors = np.array(errors) else: root_tag[meshtally] = meshtally.e_bounds[1:] vals = meshtally.vals[:] errors = meshtally.errors[:] # Determine the max values for each energy bin max_val = [] for i in range(tag_size): vals_in_e = [] for ve, flux in enumerate(vals[:]): vals_in_e.append(vals[ve][i]) max_val.append(np.max(vals_in_e)) # Apply normalization to create weight windows ww = [] for ve, flux_list in enumerate(vals[:]): tally_list = errors[ve] flux = [] for i, value in enumerate(flux_list): if tally_list[i] > tolerance: flux.append(null_value) else: flux.append(value / (2.0 * max_val[i])) ww.append(flux) # Resassign weight windows to meshtally if total: meshtally.ww_x[:] = np.reshape(ww, len(ww)) else: meshtally.ww_x[:] = ww # Create wwinp mesh wwinp = Wwinp() wwinp.read_mesh(meshtally.mesh)
def test_issue360(): a = Mesh(structured=True, structured_coords=[[0, 1, 2], [0, 1], [0, 1]]) a.cat = NativeMeshTag(3, float) a.cat[:] = [[0.11, 0.22, 0.33], [0.44, 0.55, 0.66]] a.cat[:] = np.array([[0.11, 0.22, 0.33], [0.44, 0.55, 0.66]])