Esempio n. 1
0
def test_analog_multiple_hex():
    """This test tests that particle are sampled uniformly from a uniform source
    defined on eight mesh volume elements in two energy groups. This is done
    using the exact same method ass test_analog_multiple_hex.
    """
    seed(1953)
    m = Mesh(structured=True, structured_coords=[[0, 0.5, 1], [0, 0.5, 1], [0, 0.5, 1]], mats=None)
    m.src = IMeshTag(2, float)
    m.src[:] = np.ones(shape=(8, 2))
    m.mesh.save("sampling_mesh.h5m")
    sampler = Sampler("sampling_mesh.h5m", "src", np.array([0, 0.5, 1]), False)

    num_samples = 5000
    score = 1.0 / num_samples
    num_divs = 2
    tally = np.zeros(shape=(num_divs, num_divs, num_divs, num_divs))
    for i in range(num_samples):
        s = sampler.particle_birth([uniform(0, 1) for x in range(6)])
        assert_equal(s[4], 1.0)
        tally[int(s[0] * num_divs), int(s[1] * num_divs), int(s[2] * num_divs), int(s[3] * num_divs)] += score

    for i in range(0, 4):
        for j in range(0, 2):
            halfspace_sum = np.sum(np.rollaxis(tally, i)[j, :, :, :])
            assert abs(halfspace_sum - 0.5) / 0.5 < 0.1
Esempio n. 2
0
def test_vtx_iterator():
    #use vanilla izip as we"ll test using non-equal-length iterators
    izip = itertools.izip

    sm = Mesh(structured=True,
             structured_coords =[range(10,15), range(21,25), range(31,34)])
    it = sm.structured_set.iterate(iBase.Type.vertex, iMesh.Topology.point)

    # test the default order
    for (it_x, sm_x) in itertools.izip_longest(it, 
                                           sm.structured_iterate_vertex("zyx")):
        assert_equal(it_x,sm_x)

    # Do the same again, but use an arbitrary kwarg to structured_iterate_vertex 
    # to prevent optimization from kicking in
    it.reset()
    for (it_x, sm_x) in itertools.izip_longest(it,
                            sm.structured_iterate_vertex("zyx", no_opt=True)):
        assert_equal(it_x,sm_x)

    it.reset()
    for (it_x, sm_x) in izip(it, 
                               sm.structured_iterate_vertex("yx",z=sm.dims[2])):
        assert_equal(it_x,sm_x)

    it.reset()
    for (it_x, sm_x) in izip(it, sm.structured_iterate_vertex("x")):
        assert_equal(it_x,sm_x)
Esempio n. 3
0
def test_analog_single_tet():
    """This test tests uniform sampling within a single tetrahedron. This is
    done by dividing the tetrahedron in 4 smaller tetrahedrons and ensuring
    that each sub-tet is sampled equally.
    """
    seed(1953)
    mesh = iMesh.Mesh()
    v1 = [0, 0, 0]
    v2 = [1, 0, 0]
    v3 = [0, 1, 0]
    v4 = [0, 0, 1]
    verts = mesh.createVtx([v1, v2, v3, v4])
    mesh.createEnt(iMesh.Topology.tetrahedron, verts)
    m = Mesh(structured=False, mesh=mesh)
    m.src = IMeshTag(1, float)
    m.src[:] = np.array([1])
    m.mesh.save("tet.h5m")
    center = m.ve_center(list(m.iter_ve())[0])

    subtets = [[center, v1, v2, v3], [center, v1, v2, v4], [center, v1, v3, v4], [center, v2, v3, v4]]

    sampler = Sampler("tet.h5m", "src", np.array([0, 1]), False)
    num_samples = 5000
    score = 1.0 / num_samples
    tally = np.zeros(shape=(4))
    for i in range(num_samples):
        s = sampler.particle_birth([uniform(0, 1) for x in range(6)])
        assert_equal(s[4], 1.0)
        for i, tet in enumerate(subtets):
            if point_in_tet(tet, [s[0], s[1], s[2]]):
                tally[i] += score
                break

    for t in tally:
        assert abs(t - 0.25) / 0.25 < 0.2
Esempio n. 4
0
def test_photon_source_hdf5_to_mesh():
    """Tests the function photon source_h5_to_mesh."""

    if not HAVE_PYTAPS:
        raise SkipTest

    filename = os.path.join(thisdir, "files_test_alara", "phtn_src")
    photon_source_to_hdf5(filename, chunkshape=(10,))
    assert_true(os.path.exists(filename + ".h5"))

    mesh = Mesh(structured=True, structured_coords=[[0, 1, 2], [0, 1, 2], [0, 1]])

    tags = {("1001", "shutdown"): "tag1", ("TOTAL", "1 h"): "tag2"}
    photon_source_hdf5_to_mesh(mesh, filename + ".h5", tags)

    # create lists of lists of expected results
    tag1_answers = [[1] + [0] * 41, [2] + [0] * 41, [3] + [0] * 41, [4] + [0] * 41]
    tag2_answers = [[5] + [0] * 41, [6] + [0] * 41, [7] + [0] * 41, [8] + [0] * 41]

    ves = list(mesh.structured_iterate_hex("xyz"))
    for i, ve in enumerate(ves):
        assert_array_equal(mesh.mesh.getTagHandle("tag1")[ve], tag1_answers[i])
        assert_array_equal(mesh.mesh.getTagHandle("tag2")[ve], tag2_answers[i])

    if os.path.isfile(filename + ".h5"):
        os.remove(filename + ".h5")
Esempio n. 5
0
def test_write_fluxin_single():
    """This function tests the flux_mesh_to_fluxin function for a single energy
    group case.
    """

    if not HAVE_PYTAPS:
        raise SkipTest

    output_name = "fluxin.out"
    forward_fluxin = os.path.join(thisdir, "files_test_alara", "fluxin_single_forward.txt")
    output = os.path.join(os.getcwd(), output_name)

    flux_mesh = Mesh(structured=True, structured_coords=[[0, 1, 2], [0, 1, 2], [0, 1]])
    tag_flux = flux_mesh.mesh.createTag("flux", 1, float)
    flux_data = [1, 2, 3, 4]
    ves = flux_mesh.structured_iterate_hex("xyz")
    for i, ve in enumerate(ves):
        tag_flux[ve] = flux_data[i]

    # test forward writting
    mesh_to_fluxin(flux_mesh, "flux", output_name, False)

    with open(output) as f:
        written = f.readlines()

    with open(forward_fluxin) as f:
        expected = f.readlines()

    assert_equal(written, expected)
    if os.path.isfile(output):
        os.remove(output)
Esempio n. 6
0
def test_analog_single_hex():
    """This test tests that particles of sampled evenly within the phase-space 
    of a single mesh volume element with one energy group in an analog sampling
    scheme. This done by dividing each dimension (x, y, z, E) in half, then 
    sampling particles and tallying on the basis of which of the 2^4 = 8 regions
    of phase space the particle is born into. 
    """
    seed(1953)
    m = Mesh(structured=True, structured_coords=[[0, 1], [0, 1], [0, 1]], mats=None)
    m.src = IMeshTag(1, float)
    m.src[0] = 1.0
    m.mesh.save("sampling_mesh.h5m")
    sampler = Sampler("sampling_mesh.h5m", "src", np.array([0, 1]), False)

    num_samples = 5000
    score = 1.0 / num_samples
    num_divs = 2
    tally = np.zeros(shape=(num_divs, num_divs, num_divs, num_divs))

    for i in range(num_samples):
        s = sampler.particle_birth(np.array([uniform(0, 1) for x in range(6)]))
        assert_equal(s[4], 1.0)  # analog: all weights must be one
        tally[int(s[0] * num_divs), int(s[1] * num_divs), int(s[2] * num_divs), int(s[3] * num_divs)] += score

    # Test that each half-space of phase space (e.g. x > 0.5) is sampled about
    # half the time.
    for i in range(0, 4):
        for j in range(0, 2):
            assert abs(np.sum(np.rollaxis(tally, i)[j, :, :, :]) - 0.5) < 0.05
Esempio n. 7
0
def gen_mesh(mats=()):
    mesh_1 = Mesh(structured_coords=[[-1,0,1],[-1,0,1],[0,1]], structured=True, 
                  structured_ordering='zyx', mats=mats)
    volumes1 = list(mesh_1.structured_iterate_hex("xyz"))
    flux_tag = mesh_1.mesh.createTag("flux", 1, float)
    flux_data = [1.0, 2.0, 3.0, 4.0]
    flux_tag[volumes1] = flux_data
    return mesh_1
Esempio n. 8
0
def test_get_divs():
    x = [1, 2.5, 4, 6.9]
    y = [-12, -10, -.5]
    z = [100, 200]

    sm = Mesh(structured_coords=[x, y, z], structured=True)

    assert_equal(sm.structured_get_divisions("x"), x)
    assert_equal(sm.structured_get_divisions("y"), y)
    assert_equal(sm.structured_get_divisions("z"), z)
Esempio n. 9
0
def test_iterate_3d():        
    # use izip_longest in the lockstep iterations below; this will catch any
    # situations where one iterator turns out to be longer than expected.
    sm = Mesh(structured=True,
             structured_coords =[range(10,15), range(21,25), range(31,34)])
    I = range(0,4)
    J = range(0,3)
    K = range(0,2)
    izip = itertools.izip_longest

    it = sm.structured_set.iterate(iBase.Type.region, 
                                 iMesh.Topology.hexahedron)

    # Test the zyx order, which is default; it should be equivalent
    # to the standard imesh iterator
    for it_x, sm_x in izip(it, sm.structured_iterate_hex()):
        assert_equal(it_x, sm_x)

    #testing xyz

    all_indices_zyx = itertools.product(I, J, K)
    # Test the xyz order, the default from original mmGridGen
    for ijk_index, sm_x in izip(all_indices_zyx, 
                                 sm.structured_iterate_hex("xyz")):
        assert_equal(sm.structured_get_hex(*ijk_index), sm_x )

    def _tuple_sort(collection, indices ):
        # sorting function for order test
        def t(tup):
            # sort this 3-tuple according to the order of x, y, and z in 
            #indices
            return (tup["xyz".find(indices[0])]*100 +
                    tup["xyz".find(indices[1])]*10 +
                    tup["xyz".find(indices[2])])
        return sorted(collection, key = t)

    def test_order(order, *args,  **kw):
        all_indices = itertools.product(*args)
        for ijk_index, sm_x in izip(_tuple_sort(all_indices, order),
                                     sm.structured_iterate_hex(order,**kw)):
            assert_equal(sm.structured_get_hex(*ijk_index), sm_x)

    test_order("yxz", I, J, K)
    test_order("yzx", I, J, K)
    test_order("xzy", I, J, K)
    test_order("zxy", I, J, K)

    # Specify z=[1] to iterator
    test_order("xyz", I, J, [1], z=[1])
    # Specify y=2 to iterator
    test_order("zyx", I, [2], K, y=2)
    # specify x and y both to iterator
    test_order("yzx", [1,2,3],J[:-1], K, y=J[:-1], x=[1,2,3])
Esempio n. 10
0
def test_bias_spatial():
    """This test tests a user-specified biasing scheme for which the only 1
    bias group is supplied for a source distribution containing two energy 
    groups. This bias group is applied to both energy groups. In this test,
    the user-supplied bias distribution that was choosen, correspondes to 
    uniform sampling, so that results can be checked against Case 1 in the
    theory manual.
    """
    seed(1953)
    m = Mesh(structured=True, structured_coords=[[0, 3, 3.5], [0, 1], [0, 1]], mats=None)
    m.src = IMeshTag(2, float)
    m.src[:] = [[2.0, 1.0], [9.0, 3.0]]
    m.bias = IMeshTag(1, float)
    m.bias[:] = [1, 1]
    e_bounds = np.array([0, 0.5, 1.0])
    m.mesh.save("sampling_mesh.h5m")
    sampler = Sampler("sampling_mesh.h5m", "src", e_bounds, "bias")

    num_samples = 10000
    score = 1.0 / num_samples
    num_divs = 2
    num_e = 2
    spatial_tally = np.zeros(shape=(num_divs, num_divs, num_divs))
    e_tally = np.zeros(shape=(4))  # number of phase space groups
    for i in range(num_samples):
        s = sampler.particle_birth(np.array([uniform(0, 1) for x in range(6)]))
        if s[0] < 3.0:
            assert_almost_equal(s[4], 0.7)  # hand calcs
        else:
            assert_almost_equal(s[4], 2.8)  # hand calcs

        spatial_tally[int(s[0] * num_divs / 3.5), int(s[1] * num_divs / 1.0), int(s[2] * num_divs / 1.0)] += score

        if s[0] < 3 and s[3] < 0.5:
            e_tally[0] += score
        elif s[0] < 3 and s[3] > 0.5:
            e_tally[1] += score
        if s[0] > 3 and s[3] < 0.5:
            e_tally[2] += score
        if s[0] > 3 and s[3] > 0.5:
            e_tally[3] += score

    for i in range(0, 3):
        for j in range(0, 2):
            halfspace_sum = np.sum(np.rollaxis(spatial_tally, i)[j, :, :])
            assert abs(halfspace_sum - 0.5) / 0.5 < 0.1

    expected_e_tally = [4.0 / 7, 2.0 / 7, 3.0 / 28, 1.0 / 28]  # hand calcs
    for i in range(4):
        assert abs(e_tally[i] - expected_e_tally[i]) / expected_e_tally[i] < 0.1
Esempio n. 11
0
 def arithmetic_mesh_setup(self):
     self.mesh_1 = Mesh(structured_coords=[[-1,0,1],[-1,0,1],[0,1]], structured=True)
     volumes1 = list(self.mesh_1.structured_iterate_hex("xyz"))
     volumes2 = list(self.mesh_1.structured_iterate_hex("xyz"))
     flux_tag = self.mesh_1.mesh.createTag("flux", 1, float)
     flux_data = [1.0, 2.0, 3.0, 4.0]
     flux_tag[volumes1] = flux_data    
 
     self.mesh_2 = Mesh(structured_coords=[[-1,0,1],[-1,0,1],[0,1]], structured=True)
     volumes1 = list(self.mesh_2.structured_iterate_hex("xyz"))
     volumes2 = list(self.mesh_2.structured_iterate_hex("xyz"))
     flux_tag = self.mesh_2.mesh.createTag("flux", 1, float)
     flux_data = [1.1, 2.2, 3.3, 4.4]
     flux_tag[volumes1] = flux_data
Esempio n. 12
0
def test_structured_get_hex():
    # mesh with valid i values 0-4, j values 0-3, k values 0-2
    sm = Mesh(structured_coords = [range(11,16), range(21,25), range(31,34)], 
              structured=True)
    def check(e):
        assert_true(isinstance(e, iBase.Entity))
    check(sm.structured_get_hex(0, 0, 0))
    check(sm.structured_get_hex(1, 1, 1))
    check(sm.structured_get_hex(3, 0, 0))
    check(sm.structured_get_hex(3, 2, 1))

    assert_raises(MeshError, sm.structured_get_hex,-1,-1,-1)
    assert_raises(MeshError, sm.structured_get_hex, 4, 0, 0)
    assert_raises(MeshError, sm.structured_get_hex, 0, 3, 0)
    assert_raises(MeshError, sm.structured_get_hex, 0, 0, 2)
Esempio n. 13
0
def test_structured_get_vertex():
    # mesh with valid i values 0-4, j values 0-3, k values 0-2
    x_range = np.array(range(10,15),dtype=np.float64)
    y_range = np.array(range(21,24),dtype=np.float64)
    z_range = np.array(range(31,33),dtype=np.float64)

    sm = Mesh(structured_coords=[x_range, y_range, z_range], structured=True)

    for i,x in enumerate(x_range):
        for j,y in enumerate(y_range):
            for k,z in enumerate(z_range):
                print("{0} {1} {2}".format(i, j, k))
                vtx = sm.structured_get_vertex(i,j,k)
                vcoord = sm.mesh.getVtxCoords(vtx)
                assert_true(all(vcoord == [x,y,z]))
Esempio n. 14
0
def test_uniform():
    """This test tests that the uniform biasing scheme:
    1. Samples space uniformly. This is checked using the same method
       described in test_analog_single_hex().
    2. Adjusts weights accordingly. Sample calculations are provided in Case 1
       in the Theory Manual.
    """
    seed(1953)
    m = Mesh(structured=True, structured_coords=[[0, 3, 3.5], [0, 1], [0, 1]], mats=None)
    m.src = IMeshTag(2, float)
    m.src[:] = [[2.0, 1.0], [9.0, 3.0]]
    e_bounds = np.array([0, 0.5, 1.0])
    m.mesh.save("sampling_mesh.h5m")
    sampler = Sampler("sampling_mesh.h5m", "src", e_bounds, True)

    num_samples = 10000
    score = 1.0 / num_samples
    num_divs = 2
    num_e = 2
    spatial_tally = np.zeros(shape=(num_divs, num_divs, num_divs))
    e_tally = np.zeros(shape=(4))  # number of phase space groups
    for i in range(num_samples):
        s = sampler.particle_birth(np.array([uniform(0, 1) for x in range(6)]))
        if s[0] < 3.0:
            assert_almost_equal(s[4], 0.7)  # hand calcs
        else:
            assert_almost_equal(s[4], 2.8)  # hand calcs

        spatial_tally[int(s[0] * num_divs / 3.5), int(s[1] * num_divs / 1.0), int(s[2] * num_divs / 1.0)] += score

        if s[0] < 3 and s[3] < 0.5:
            e_tally[0] += score
        elif s[0] < 3 and s[3] > 0.5:
            e_tally[1] += score
        if s[0] > 3 and s[3] < 0.5:
            e_tally[2] += score
        if s[0] > 3 and s[3] > 0.5:
            e_tally[3] += score

    for i in range(0, 3):
        for j in range(0, 2):
            halfspace_sum = np.sum(np.rollaxis(spatial_tally, i)[j, :, :])
            assert abs(halfspace_sum - 0.5) / 0.5 < 0.1

    expected_e_tally = [4.0 / 7, 2.0 / 7, 3.0 / 28, 1.0 / 28]  # hand calcs
    for i in range(4):
        assert abs(e_tally[i] - expected_e_tally[i]) / expected_e_tally[i] < 0.1
Esempio n. 15
0
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 = IMeshTag(2, float)
    m.tag2 = IMeshTag(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])
Esempio n. 16
0
def test_magic_single_e():
    """Test a single 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, 1.0]
    tally.n_flux = IMeshTag(1, float)
    tally.n_flux[:] = flux_data
    
    tally.n_rel_error = IMeshTag(1, 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.181818182, 0.5, 0.2424242, 0.001]
    
    assert_array_almost_equal(tally.ww_x[:], expected_ww[:])
Esempio n. 17
0
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 = IMeshTag(2, float)
    tally.n_flux[:] = flux_data
    
    tally.n_rel_error = IMeshTag(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[:])
Esempio n. 18
0
def test_iterate_1d():
    sm = Mesh(structured=True,
             structured_coords =[range(10,15), range(21,25), range(31,34)])
    
    def test_equal(ijk_list, miter):
        for ijk, i in itertools.izip_longest(ijk_list, miter):
            assert_equal(sm.structured_get_hex(*ijk), i)

    test_equal([[0,0,0],[0,0,1]], 
                sm.structured_iterate_hex("z"))

    test_equal([[0,1,1],[0,2,1]],
                sm.structured_iterate_hex("y", y=[1,2], z=1))

    test_equal([[2,0,0],[2,1,0],[2,2,0]],
                sm.structured_iterate_hex("y", x=2)) 
    test_equal([[0,0,0],[1,0,0],[2,0,0]], 
        sm.structured_iterate_hex("x", x=[0,1,2]))
Esempio n. 19
0
def discretize_geom_centers():
    from pyne import dagmc
    dagmc.load(path)

    coords = [0, 1]
    coords2 = [0, 2, 4]
    mesh = Mesh(structured=True, 
                structured_coords=[coords2, coords, coords])
    #  explicitly set to unstructured to trigger the ve centers sampling
    #  method
    mesh.structured = False
    res = dagmc.discretize_geom(mesh)
    assert_array_equal(res["idx"], [0, 1])
    assert_array_equal(res["cell"], [2, 3])
    assert_array_equal(res["vol_frac"], [1.0, 1.0])
    assert_array_equal(res["rel_error"], [1.0, 1.0])

    #  ensure kwargs are not accepted for unstructured mesh
    assert_raises(ValueError, dagmc.discretize_geom, mesh, num_rays=3, grid=True)
Esempio n. 20
0
def test_create_by_file():
    filename = os.path.join(os.path.dirname(__file__), 
                            "files_mesh_test/grid543.h5m")
    sm = Mesh(mesh=filename, structured=True)
    assert_true(all(sm.dims == [1, 11, -5, 5, 14, -3]))

    # This mesh is interesting because the i/j/k space is not numbered from
    # zero. Check that divisions are correct

    assert_equal(sm.structured_get_divisions("x"), range(1,6))
    assert_equal(sm.structured_get_divisions("y"), [1.0, 5.0, 10.0, 15.0] )
    assert_equal(sm.structured_get_divisions("z"), [-10.0, 2.0, 12.0] )

    # loading a test file without structured mesh metadata should raise an 
    # error
    filename2 = os.path.join(os.path.dirname(__file__), 
                             "files_mesh_test/no_str_mesh.h5m")
    assert_raises(iBase.TagNotFoundError, Mesh, mesh=filename2, 
                       structured=True)
Esempio n. 21
0
def test_imeshtag_expand():
    m = Mesh(structured=True, structured_coords=[[-1, 0, 1],[0, 1],[0, 1]])
    m.clam = IMeshTag(2, float)
    m.clam[:] = [[1.1, 2.2], [3.3, 4.4]]
    m.clam.expand()
    m.clam_000 = IMeshTag(1, float)
    assert_array_equal(m.clam_000[:], [1.1, 3.3])
    m.clam_001 = IMeshTag(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 = IMeshTag(2, float)
    m.clam[:] = [[1.1, 2.2]]
    m.clam.expand()
    m.clam_000 = IMeshTag(1, float)
    assert_array_equal(m.clam_000[:], 1.1)
    m.clam_001 = IMeshTag(1, float)
    assert_array_equal(m.clam_001[:], 2.2)
Esempio n. 22
0
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 = IMeshTag(2, float)
    q_mesh.q = IMeshTag(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 = IMeshTag(2, float)
    q_bias_mesh.q_bias = IMeshTag(2, float)
    
    assert_array_almost_equal(ww_mesh.ww[:], expected_ww[:])
    assert_array_almost_equal(q_bias_mesh.q_bias[:], expected_q_bias[:])
Esempio n. 23
0
    def test_discretize_geom_centers(self):
        """Test that unstructured mesh is sampled by mesh ve centers.
        """
        if not HAVE_IMESH:
            raise SkipTest
        coords = [0, 1]
        coords2 = [0, 2, 4]
        mesh = Mesh(structured=True, 
                    structured_coords=[coords2, coords, coords])
        #  explicitly set to unstructured to trigger the ve centers sampling
        #  method
        mesh.structured = False
        res = dagmc.discretize_geom(mesh)
        assert_array_equal(res["idx"], [0, 1])
        assert_array_equal(res["cell"], [2, 3])
        assert_array_equal(res["vol_frac"], [1.0, 1.0])
        assert_array_equal(res["rel_error"], [1.0, 1.0])

        #  ensure kwargs are not accepted for unstructured mesh
        assert_raises(ValueError, dagmc.discretize_geom, mesh, num_rays=3, grid=True)
Esempio n. 24
0
def test_bias():
    """This test tests that a user-specified biasing scheme:
    1. Samples space uniformly according to the scheme.
    2. Adjusts weights accordingly. Sample calculations are provided in Case 2
       in the Theory Manual.
    """
    seed(1953)
    m = Mesh(structured=True, structured_coords=[[0, 3, 3.5], [0, 1], [0, 1]], mats=None)
    m.src = IMeshTag(2, float)
    m.src[:] = [[2.0, 1.0], [9.0, 3.0]]
    e_bounds = np.array([0, 0.5, 1.0])
    m.bias = IMeshTag(2, float)
    m.bias[:] = [[1.0, 2.0], [3.0, 3.0]]
    m.mesh.save("sampling_mesh.h5m")
    sampler = Sampler("sampling_mesh.h5m", "src", e_bounds, "bias")

    num_samples = 10000
    score = 1.0 / num_samples
    num_divs = 2
    tally = np.zeros(shape=(4))
    for i in range(num_samples):
        s = sampler.particle_birth(np.array([uniform(0, 1) for x in range(6)]))
        if s[0] < 3:
            if s[3] < 0.5:
                assert_almost_equal(s[4], 1.6)  # hand calcs
                tally[0] += score
            else:
                assert_almost_equal(s[4], 0.4)  # hand calcs
                tally[1] += score
        else:
            if s[3] < 0.5:
                assert_almost_equal(s[4], 2.4)  # hand calcs
                tally[2] += score
            else:
                assert_almost_equal(s[4], 0.8)  # hand calcs
                tally[3] += score

    expected_tally = [0.25, 0.5, 0.125, 0.125]  # hand calcs
    for a, b in zip(tally, expected_tally):
        assert abs(a - b) / b < 0.25
Esempio n. 25
0
def test_iterate_2d():
    sm = Mesh(structured=True,
             structured_coords =[range(10,15), range(21,25), range(31,34)])
    def test_order(iter1, iter2):
        for i1, i2 in itertools.izip_longest(iter1, iter2):
            assert_equal(i1, i2)

    test_order(sm.structured_iterate_hex("yx"), 
               sm.structured_iterate_hex("zyx", z=[0]))
    test_order(sm.structured_iterate_hex("yx",z=1), 
               sm.structured_iterate_hex("zyx",z=[1]))
    test_order(sm.structured_iterate_hex("yx",z=1), 
               sm.structured_iterate_hex("yzx",z=[1]))
    test_order(sm.structured_iterate_hex("zy",x=[3]), 
               sm.structured_iterate_hex("zxy",x=3))

    # Cannot iterate over multiple z's without specifing z order
    assert_raises(MeshError, sm.structured_iterate_hex, "yx", z=[0,1])
Esempio n. 26
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 = IMeshTag(1, float)
    q_mesh.q = IMeshTag(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 = IMeshTag(1, float)
    q_bias_mesh.q_bias = IMeshTag(1, float)
    
    assert_array_almost_equal(ww_mesh.ww[:], expected_ww[:])

    assert_array_almost_equal(q_bias_mesh.q_bias[:], expected_q_bias[:])
Esempio n. 27
0
def test_elem_volume():
    """Test the get_elem_volume method"""
    # Test tet elements recognition and calculation
    filename = os.path.join(os.path.dirname(__file__),
                            "files_mesh_test/unstr.h5m")
    tetmesh = Mesh(mesh=filename)
    vols = list()
    for __, __, ve in tetmesh:
        vols.append(tetmesh.elem_volume(ve))

    assert_almost_equal(np.min(vols), 0.13973, places=5)
    assert_almost_equal(np.max(vols), 2.1783, places=4)
    assert_almost_equal(np.mean(vols), 0.52702, places=5)

    # Test hex elements recognition and calculation
    filename = os.path.join(os.path.dirname(__file__),
                            "files_mesh_test/grid543.h5m")
    mesh = Mesh(mesh=filename)
    vols = list()
    for __, __, ve in mesh:
        vols.append(mesh.elem_volume(ve))
    assert_almost_equal(np.mean(vols), 51.3333, places=4)
Esempio n. 28
0
def test_structured_hex_volume():

    sm = Mesh(structured_coords = [[0,1,3], [-3,-2,0], [12,13,15]], 
              structured=True)
    assert_equal(sm.structured_hex_volume(0,0,0), 1)
    assert_equal(sm.structured_hex_volume(1,0,0), 2)
    assert_equal(sm.structured_hex_volume(0,1,0), 2)
    assert_equal(sm.structured_hex_volume(1,1,0), 4)
    assert_equal(sm.structured_hex_volume(1,1,1), 8)

    ijk_all = itertools.product(*([[0,1]]*3))

    for V, ijk in itertools.izip_longest(sm.structured_iterate_hex_volumes(), 
                                         ijk_all):
        assert_equal(V, sm.structured_hex_volume(*ijk))
Esempio n. 29
0
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 = IMeshTag(1, float)
    tally.n_total_flux[:] = flux_data
    
    tally.n_rel_error = IMeshTag(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[:])
Esempio n. 30
0
def test_ve_center():
    m = Mesh(structured=True, structured_coords=[[-1, 3, 5], [-1, 1], [-1, 1]])
    exp_centers = [(1, 0, 0), (4, 0, 0)]
    for i, mat, ve in m:
        assert_equal(m.ve_center(ve), exp_centers[i])
Esempio n. 31
0
def irradiation_setup_structured(flux_tag="n_flux",
                                 meshtal_file="meshtal_2x2x1"):

    meshtal = os.path.join(thisdir, "files_test_r2s", meshtal_file)
    tally_num = 4
    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")
    num_rays = 9
    grid = True
    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(8,
                          dtype=[('idx', np.int64), ('cell', np.int64),
                                 ('vol_frac', np.float64),
                                 ('rel_error', np.float64)])
    cell_fracs[:] = [(0, 2, 0.037037037037037035, 0.5443310539518174),
                     (0, 3, 0.9629629629629631, 0.010467904883688123),
                     (1, 2, 0.037037037037037035, 0.5443310539518174),
                     (1, 3, 0.9629629629629629, 0.010467904883688454),
                     (2, 2, 0.037037037037037035, 0.5443310539518174),
                     (2, 3, 0.9629629629629629, 0.010467904883688454),
                     (3, 2, 0.037037037037037035, 0.5443310539518174),
                     (3, 3, 0.9629629629629629, 0.010467904883688454)]

    irradiation_setup(meshtal, cell_mats, cell_fracs, alara_params, tally_num,
                      num_rays, grid, flux_tag, fluxin, reverse, alara_inp,
                      alara_matlib, output_mesh, output_material)

    #  expected output files
    exp_alara_inp = os.path.join(thisdir, "files_test_r2s", "exp_alara_inp")
    exp_alara_matlib = os.path.join(thisdir, "files_test_r2s",
                                    "exp_alara_matlib")
    exp_fluxin = os.path.join(thisdir, "files_test_r2s", "exp_fluxin")

    # 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, 1.962963E+00)
        assert_equal(len(comp), 3)
        assert_almost_equal(comp[20040000], 1.886792E-02)
        assert_almost_equal(comp[30060000], 5.886792E-01)
        assert_almost_equal(comp[30070000], 3.924528E-01)
        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(alara_inp)
    os.remove(alara_matlib)
    os.remove(fluxin)
    os.remove(output_mesh)

    return [f1, f2, f3]
Esempio n. 32
0
def test_mesh_to_geom():
    if not HAVE_PYMOAB:
        raise SkipTest

    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),
        4: Material({'C12': 1.0}, density=47.0),
        5: Material({'1002': 1.0}, density=5.0),
    }

    m = Mesh(structured_coords=[[0, 1, 2, 3], [0, 1, 2], [0, 1]],
             mats=mats,
             structured=True)

    geom = mcnp.mesh_to_geom(m)

    exp_geom = ("Generated from PyNE Mesh\n"
                "1 1 42.0 1 -2 5 -6 8 -9\n"
                "2 2 43.0 1 -2 6 -7 8 -9\n"
                "3 3 44.0 2 -3 5 -6 8 -9\n"
                "4 4 45.0 2 -3 6 -7 8 -9\n"
                "5 5 47.0 3 -4 5 -6 8 -9\n"
                "6 6 5.0 3 -4 6 -7 8 -9\n"
                "7 0 -1:4:-5:7:-8:9\n"
                "\n"
                "1 px 0.0\n"
                "2 px 1.0\n"
                "3 px 2.0\n"
                "4 px 3.0\n"
                "5 py 0.0\n"
                "6 py 1.0\n"
                "7 py 2.0\n"
                "8 pz 0.0\n"
                "9 pz 1.0\n"
                "\n"
                "C density = 42.0\n"
                "m1\n"
                "     1001 -5.0000e-01\n"
                "     19039 -5.0000e-01\n"
                "C density = 43.0\n"
                "m2\n"
                "     1001 -9.0909e-02\n"
                "     8016 -9.0909e-01\n"
                "C density = 44.0\n"
                "m3\n"
                "     2004 -1.0000e+00\n"
                "C density = 45.0\n"
                "m4\n"
                "     69171 -1.0000e+00\n"
                "C density = 47.0\n"
                "m5\n"
                "     6012 -1.0000e+00\n"
                "C density = 5.0\n"
                "m6\n"
                "     1002 -1.0000e+00\n")

    assert_equal(geom, exp_geom)
Esempio n. 33
0
def test_structured_mesh_from_coords():
    sm = Mesh(structured_coords = [range(1,5), range(1,4), range(1,3)], \
              structured=True)
    assert_true(all(sm.dims == [0, 0, 0, 3, 2, 1]))
Esempio n. 34
0
def write_partisn_input_options():
    if not HAVE_PYMOAB:
        raise SkipTest
    """Test PARTISN input file creation with a slew of keyword arguments
    """

    THIS_DIR = os.path.dirname(os.path.realpath(__file__))
    hdf5 = os.path.join(THIS_DIR, "files_test_partisn",
                        "partisn_test_geom.h5m")
    input_file = os.path.join(THIS_DIR, "files_test_partisn",
                              "partisn_options.inp")
    file_expected = os.path.join(THIS_DIR, "files_test_partisn",
                                 "partisn_options_expected.inp")

    sc = [-5.0, 0.0, 10.0, 15.0], [-5.0, 5.0], [-5.0, 5.0]
    mesh = Mesh(structured_coords=sc, structured=True)
    ngroup = 66

    dg = np.zeros(
        4,
        dtype=[
            ("idx", np.int64),
            ("cell", np.int64),
            ("vol_frac", np.float64),
            ("rel_error", np.float64),
        ],
    )
    dg[:] = [
        (0, 1, 1.0, 0.0),
        (1, 1, 0.5, 0.04714045207910317),
        (1, 2, 0.5, 0.04714045207910317),
        (2, 2, 1.0, 0.0),
    ]
    mat_assigns = {
        1: "mat:Helium, Natural",
        2: "mat:Mercury",
        5: "mat:Graveyard",
        6: "mat:Vacuum",
    }

    cards = {
        "block1": {
            "isn": 6,
            "maxlcm": 6000000,
            "maxscm": 3000000,
        },
        "block2": {
            "hello": "from block2"
        },
        "block3": {
            "i2lp1": 0,
            "ifido": 1,
            "ihm": 227,
            "ihs": 11,
            "iht": 10,
            "ititl": 1,
            "kwikrd": 1,
            "lib": "xsf21-71",
            "lng": 175,
            "maxord": 5,
            "savbxs": 1,
        },
        "block4": {
            "hello": "from block4"
        },
        "block5": {
            "source": "<this is a dummy source>"
        },
    }

    with warnings.catch_warnings(record=True) as w:
        partisn.write_partisn_input(
            mesh,
            hdf5,
            ngroup,
            input_file=input_file,
            dg=dg,
            mat_assigns=mat_assigns,
            fine_per_coarse=3,
            cards=cards,
            num_rays=9,
        )  # include num_rays to get warning

    # verify we get a warning from including num_rays and dg
    out1 = len(w) == 1
    out2 = filecmp.cmp(input_file, file_expected)
    os.remove(input_file)
    return out1 and out2
Esempio n. 35
0
def test_unstructured_mesh_from_instance():
    filename = os.path.join(os.path.dirname(__file__),
                            "files_mesh_test/unstr.h5m")
    mesh = mb_core.Core()
    mesh.load_file(filename)
    sm = Mesh(mesh=mesh)
Esempio n. 36
0
def test_irradiation_setup_unstructured():

    flux_tag = "n_flux"
    meshtal_file = os.path.join(thisdir, "files_test_r2s", "meshtal_2x2x1")
    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.mesh.save(meshtal_mesh_file)

    cell_mats = {
        2: Material({2004: 1.0}, density=1.0),
        3: Material({
            3007: 0.4,
            3006: 0.6
        }, density=2.0)
    }
    alara_params = "Bogus line for testing"
    geom = os.path.join(thisdir, "unitbox.h5m")
    flux_tag = "n_flux"
    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")

    irradiation_setup(flux_mesh=meshtal_mesh_file,
                      cell_mats=cell_mats,
                      alara_params=alara_params,
                      geom=geom,
                      flux_tag=flux_tag,
                      fluxin=fluxin,
                      reverse=reverse,
                      alara_inp=alara_inp,
                      alara_matlib=alara_matlib,
                      output_mesh=output_mesh)

    #  expected output files
    exp_alara_inp = os.path.join(thisdir, "files_test_r2s", "exp_alara_inp")
    exp_alara_matlib = os.path.join(thisdir, "files_test_r2s",
                                    "exp_alara_matlib_un")
    exp_fluxin = os.path.join(thisdir, "files_test_r2s", "exp_fluxin_un")

    #  test alara input file
    with open(alara_inp, 'r') as f1, open(exp_alara_inp, 'r') as f2:
        for a, b in zip(f1.readlines(), f2.readlines()):
            assert_equal(a, b)

    #  test alara matlibe file
    with open(alara_matlib, 'r') as f1, open(exp_alara_matlib) as f2:
        for a, b in zip(f1.readlines(), f2.readlines()):
            assert_equal(a, b)

    #  test alara fluxin file
    with open(fluxin, 'r') as f1, open(exp_fluxin) as f2:
        for a, b in zip(f1.readlines(), f2.readlines()):
            assert_equal(a, b)

    # 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]

    m = Mesh(structured=True, mesh=output_mesh, mats=output_mesh)
    for i, mat, _ in m:
        assert_almost_equal(mat.density, 2.0)
        assert_equal(len(mat.comp), 2)
        assert_almost_equal(mat.comp[30060000], 0.6)
        assert_almost_equal(mat.comp[30070000], 0.4)
        assert_array_equal(m.n_flux[i], fluxes[i])
        assert_array_equal(m.n_flux_err[i], errs[i])
        assert_almost_equal(m.n_flux_total[i], tot_fluxes[i])
        assert_almost_equal(m.n_flux_err_total[i], tot_errs[i])

    os.remove(meshtal_mesh_file)
    os.remove(alara_inp)
    os.remove(alara_matlib)
    os.remove(fluxin)
    os.remove(output_mesh)
Esempio n. 37
0
import numpy as np

from pyne.cccc import Atflux
from pyne.mesh import Mesh, NativeMeshTag

sc = [
    np.linspace(-600, 1200, 46),
    np.linspace(-800, 500, 31),
    np.linspace(-500, 500, 26)
]

m = Mesh(structured=True, structured_coords=sc, mats=None)

at = Atflux("atflux")
at.to_mesh(m, "flux")

m.flux = NativeMeshTag(217, float)
m.save("adj_p.h5m")
Esempio n. 38
0
def get_zones_iteration_order():
    """Test that _get_zones function gives results in zyx order.
    """
    try:
        from pyne import dagmc
    except:
        raise SkipTest

    if not HAVE_PYMOAB:
        raise SkipTest

    # hdf5 test file
    THIS_DIR = os.path.dirname(os.path.realpath(__file__))
    hdf5 = THIS_DIR + '/files_test_partisn/fractal_box.h5m'
    data_hdf5path = '/materials'
    nuc_hdf5path = '/nucid'

    # Load dagmc geometry
    dagmc.load(hdf5)

    bounds = [-5., 0., 5.]
    sc = [bounds] * 3
    mesh = Mesh(structured_coords=sc, structured=True)
    bounds = {'x': bounds, 'y': bounds, 'z': bounds}
    num_rays = 9
    grid = True
    dg = None
    mat_assigns = None
    unique_names = {
        'mat:m1': 'M1',
        'mat:m2': 'M2',
        'mat:m3': 'M3',
        'mat:m4': 'M4'
    }

    voxel_zones, zones = partisn._get_zones(mesh, hdf5, bounds, num_rays, grid,
                                            dg, mat_assigns, unique_names)

    voxel_zones_expected = np.array([[1, 2], [1, 4], [1, 3], [1, 4]])
    zones_expected = {
        1: {
            'vol_frac': [1.0],
            'mat': ['M2']
        },
        2: {
            'vol_frac': [1.0],
            'mat': ['M4']
        },
        3: {
            'vol_frac': [1.0],
            'mat': ['M1']
        },
        4: {
            'vol_frac': [1.0],
            'mat': ['M3']
        }
    }

    vz_tf = voxel_zones.all() == voxel_zones_expected.all()
    z_tf = zones == zones_expected
    return [vz_tf, z_tf]
Esempio n. 39
0
def get_zones_with_void():
    """Test the _get_zones function if a void is present.
    """
    try:
        from pyne import dagmc
    except:
        raise SkipTest

    if not HAVE_PYMOAB:
        raise SkipTest

    # hdf5 test file
    THIS_DIR = os.path.dirname(os.path.realpath(__file__))
    hdf5 = THIS_DIR + '/files_test_partisn/partisn_test_geom.h5m'
    data_hdf5path = '/materials'
    nuc_hdf5path = '/nucid'

    dagmc.load(hdf5)

    # mesh
    xvals = [-5., 0., 10., 15., 15.1]
    yvals = [-5., 0., 5.]
    zvals = [-5., 0., 5.]
    mesh = Mesh(structured_coords=[xvals, yvals, zvals],
                structured=True,
                structured_ordering='xyz')
    # more inputs
    bounds = {'x': xvals, 'y': yvals, 'z': zvals}
    num_rays = 400
    grid = True
    dg = None
    mat_assigns = None

    unique_names = {
        'mat:Helium, Natural': 'HELIUMNA',
        'mat:Mercury': 'MERCURY1'
    }
    voxel_zones, zones = partisn._get_zones(mesh, hdf5, bounds, num_rays, grid,
                                            dg, mat_assigns, unique_names)

    # expected results
    voxel_zones_expected = np.array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3],
                                     [0, 0, 0, 0]])
    zones_expected = {
        1: {
            'vol_frac': [1.0],
            'mat': [u'HELIUMNA']
        },
        2: {
            'vol_frac': [0.5, 0.5],
            'mat': [u'HELIUMNA', u'MERCURY1']
        },
        3: {
            'vol_frac': [1.0],
            'mat': [u'MERCURY1']
        }
    }

    vz_tf = False
    z_tf = False
    if voxel_zones.all() == voxel_zones_expected.all():
        vz_tf = True
    if zones == zones_expected:
        z_tf = True
    #assert(voxel_zones.all() == voxel_zones_expected.all())
    #assert(zones == zones_expected)
    return [vz_tf, z_tf]
Esempio n. 40
0
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[:])
Esempio n. 41
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[:])
Esempio n. 42
0
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")
Esempio n. 43
0
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)
Esempio n. 44
0
def test_multiple_meshtally_meshtal():
    """Test a meshtal file containing 4 mesh tallies including neutron and
    photon, single energy group and multiple energy group.
    """

    if not HAVE_PYMOAB:
        raise SkipTest

    thisdir = os.path.dirname(__file__)
    meshtal_file = os.path.join(thisdir, "mcnp_meshtal_multiple_meshtal.txt")

    expected_h5m_4 = os.path.join(thisdir, "mcnp_meshtal_tally_4.h5m")
    expected_sm_4 = Mesh(mesh=expected_h5m_4, structured=True)

    expected_h5m_14 = os.path.join(thisdir, "mcnp_meshtal_tally_14.h5m")
    expected_sm_14 = Mesh(mesh=expected_h5m_14, structured=True)

    expected_h5m_24 = os.path.join(thisdir, "mcnp_meshtal_tally_24.h5m")
    expected_sm_24 = Mesh(mesh=expected_h5m_24, structured=True)

    expected_h5m_34 = os.path.join(thisdir, "mcnp_meshtal_tally_34.h5m")
    expected_sm_34 = Mesh(mesh=expected_h5m_34, structured=True)

    tags = {
        4: ["n_result", "n_rel_error", "n_total_result", "n_total_rel_error"],
        14: ["n_result", "n_rel_error", "n_total_result", "n_total_rel_error"],
        24: ["p_result", "p_rel_error", "p_total_result", "p_total_rel_error"],
        34: ["p_result", "p_rel_error", "p_total_result", "p_total_rel_error"]
    }
    meshtal_object = mcnp.Meshtal(meshtal_file, tags)
    assert_equal(meshtal_object.version, '5')
    assert_equal(meshtal_object.tally[4].mats, None)

    # test meshtally 4
    for v_e, expected_v_e in zip(
            meshtal_object.tally[4].structured_iterate_hex("xyz"),
            expected_sm_4.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[4].n_result[v_e]
        expected = expected_sm_4.n_result[expected_v_e]
        assert_array_equal(written, expected)

    for v_e, expected_v_e in zip(
            meshtal_object.tally[4].structured_iterate_hex("xyz"),
            expected_sm_4.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[4].n_rel_error[v_e]
        expected = expected_sm_4.n_rel_error[expected_v_e]
        assert_array_equal(written, expected)

    for v_e, expected_v_e in zip(
            meshtal_object.tally[4].structured_iterate_hex("xyz"),
            expected_sm_4.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[4].n_total_result[v_e]
        expected = expected_sm_4.n_total_result[expected_v_e]
        assert_equal(written, expected)

    for v_e, expected_v_e in zip(
            meshtal_object.tally[4].structured_iterate_hex("xyz"),
            expected_sm_4.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[4].n_total_rel_error[v_e]
        expected = expected_sm_4.n_total_rel_error[expected_v_e]
        assert_equal(written, expected)

    # test meshtally 14
    for v_e, expected_v_e in zip(
            meshtal_object.tally[14].structured_iterate_hex("xyz"),
            expected_sm_14.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[14].n_result[v_e]
        expected = expected_sm_14.n_result[expected_v_e]
        assert_array_equal(written, expected)

    for v_e, expected_v_e in zip(
            meshtal_object.tally[14].structured_iterate_hex("xyz"),
            expected_sm_14.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[14].n_rel_error[v_e]
        expected = expected_sm_14.n_rel_error[expected_v_e]
        assert_array_equal(written, expected)

    # test meshtally 24
    for v_e, expected_v_e in zip(
            meshtal_object.tally[24].structured_iterate_hex("xyz"),
            expected_sm_24.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[24].p_result[v_e]
        expected = expected_sm_24.p_result[expected_v_e]
        assert_array_equal(written, expected)

    for v_e, expected_v_e in zip(
            meshtal_object.tally[24].structured_iterate_hex("xyz"),
            expected_sm_24.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[24].p_rel_error[v_e]
        expected = expected_sm_24.p_rel_error[expected_v_e]
        assert_array_equal(written, expected)

    for v_e, expected_v_e in zip(
            meshtal_object.tally[24].structured_iterate_hex("xyz"),
            expected_sm_24.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[24].p_total_result[v_e]
        expected = expected_sm_24.p_total_result[expected_v_e]
        assert_equal(written, expected)

    for v_e, expected_v_e in zip(
            meshtal_object.tally[24].structured_iterate_hex("xyz"),
            expected_sm_24.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[24].p_total_rel_error[v_e]
        expected = expected_sm_24.p_total_rel_error[expected_v_e]
        assert_equal(written, expected)

    # test meshtally 34
    for v_e, expected_v_e in zip(
            meshtal_object.tally[34].structured_iterate_hex("xyz"),
            expected_sm_34.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[34].p_result[v_e]
        expected = expected_sm_34.p_result[expected_v_e]
        assert_array_equal(written, expected)

    for v_e, expected_v_e in zip(
            meshtal_object.tally[34].structured_iterate_hex("xyz"),
            expected_sm_34.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[34].p_rel_error[v_e]
        expected = expected_sm_34.p_rel_error[expected_v_e]
        assert_array_equal(written, expected)
Esempio n. 45
0
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]
Esempio n. 46
0
def irradiation_setup(flux_mesh, cell_mats, alara_params, tally_num=4,
                      geom=None, num_rays=10, grid=False, flux_tag="n_flux",
                      fluxin="alara_fluxin", reverse=False,
                      alara_inp="alara_geom", alara_matlib="alara_matlib",
                      output_mesh="r2s_step1.h5m", output_material=False):
    """This function is used to setup the irradiation inputs after the first
    R2S transport step.

    Parameters
    ----------
    flux_mesh : PyNE Meshtal object, Mesh object, or str
        The source of the neutron flux information. This can be a PyNE Meshtal
        object, a pyne Mesh object, or the filename an MCNP meshtal file, or
        the filename of an unstructured mesh tagged with fluxes.
    tally_num : int
        The MCNP FMESH4 tally number of the neutron flux tally within the
        meshtal file.
    cell_mats : dict
        Maps geometry cell numbers to PyNE Material objects.
    alara_params : str
        The ALARA input blocks specifying everything except the geometry
        and materials. This can either be passed as string or as a file name.
    geom : str, optional
        The file name of a DAGMC-loadable faceted geometry. This is only
        necessary if the geometry is not already loaded into memory.
    num_rays : int, optional
        The number of rays to fire down a mesh row for geometry discretization.
        This number must be a perfect square if grid=True.
    grid : bool, optional
        The if False, geometry discretization will be done with randomly fired
        rays. If true, a grid of sqrt(num_rays) x sqrt(num_rays) rays is used
        for each mesh row.
    flux_tag : str, optional
        The iMesh tag for the neutron flux.
    fluxin : str, optional
        The name of the ALARA fluxin file to be created.
    reverse : bool, optional
        If True the fluxes in the fluxin file will be printed in the reverse
        order of how they appear within the flux vector tag. Since MCNP and
        the Meshtal class order fluxes from low energy to high energy, this
        option should only be true if the transmutation data being used is
        ordered from high energy to low energy.
    alara_inp : str, optional
        The name of the ALARA input file to be created.
    alara_matlib : str, optional
        The name of the alara_matlib file to be created.
    output_mesh : str, optional
        A mesh containing all the fluxes and materials used for irradiation
        setup.
    output_material : bool, optional
        If true, output mesh will have materials as determined by
        dagmc.discretize_geom()
    """
    from pyne.dagmc import load, discretize_geom
    if geom is not None and isfile(geom):
        load(geom)

    #  flux_mesh is Mesh object
    if isinstance(flux_mesh, Mesh):
        m = flux_mesh
    #  flux_mesh is unstructured mesh file
    elif isinstance(flux_mesh, str) and isfile(flux_mesh) \
         and flux_mesh.endswith(".h5m"):
            m = Mesh(structured=False, mesh=flux_mesh)
    #  flux_mesh is Meshtal or meshtal file
    else:
        #  flux_mesh is meshtal file
        if isinstance(flux_mesh, str) and isfile(flux_mesh):
            flux_mesh = Meshtal(flux_mesh,
                                {tally_num: (flux_tag, flux_tag + "_err",
                                             flux_tag + "_total",
                                             flux_tag + "_err_total")},
                                meshes_have_mats=output_material)
            m = flux_mesh.tally[tally_num]
        #  flux_mesh is Meshtal object
        elif isinstance(flux_mesh, Meshtal):
            m = flux_mesh.tally[tally_num]
        else:
            raise ValueError("meshtal argument not a Mesh object, Meshtal"
                             " object, MCNP meshtal file or meshtal.h5m file.")

    if m.structured:
        cell_fracs = discretize_geom(m, num_rays=num_rays, grid=grid)
    else:
        cell_fracs = discretize_geom(m)

    if output_material:
        m.cell_fracs_to_mats(cell_fracs, cell_mats)

    mesh_to_fluxin(m, flux_tag, fluxin, reverse)
    record_to_geom(m, cell_fracs, cell_mats, alara_inp, alara_matlib)

    if isfile(alara_params):
        with open(alara_params, 'r') as f:
            alara_params = f.read()

    with open(alara_inp, 'a') as f:
        f.write("\n" + alara_params)

    m.write_hdf5(output_mesh)
Esempio n. 47
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
Esempio n. 48
0
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]])
Esempio n. 49
0
def get_zones_with_void():
    """Test the _get_zones function if a void is present."""
    try:
        from pyne import dagmc
    except:
        raise SkipTest

    if not HAVE_PYMOAB:
        raise SkipTest

    # hdf5 test file
    THIS_DIR = os.path.dirname(os.path.realpath(__file__))
    hdf5 = THIS_DIR + "/files_test_partisn/partisn_test_geom.h5m"
    data_hdf5path = "/materials"

    dagmc.load(hdf5)

    # mesh
    xvals = [-5.0, 0.0, 10.0, 15.0, 15.1]
    yvals = [-5.0, 0.0, 5.0]
    zvals = [-5.0, 0.0, 5.0]
    mesh = Mesh(
        structured_coords=[xvals, yvals, zvals],
        structured=True,
        structured_ordering="xyz",
    )
    # more inputs
    bounds = {"x": xvals, "y": yvals, "z": zvals}
    num_rays = 400
    grid = True
    dg = None
    mat_assigns = None

    unique_names = {
        "mat:Helium, Natural": "HELIUMNA",
        "mat:Mercury": "MERCURY1"
    }
    voxel_zones, zones = partisn._get_zones(mesh, hdf5, bounds, num_rays, grid,
                                            dg, mat_assigns, unique_names)

    # expected results
    voxel_zones_expected = np.array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3],
                                     [0, 0, 0, 0]])
    zones_expected = {
        1: {
            "vol_frac": [1.0],
            "mat": ["HELIUMNA"]
        },
        2: {
            "vol_frac": [0.5, 0.5],
            "mat": ["HELIUMNA", "MERCURY1"]
        },
        3: {
            "vol_frac": [1.0],
            "mat": ["MERCURY1"]
        },
    }

    vz_tf = False
    z_tf = False
    if voxel_zones.all() == voxel_zones_expected.all():
        vz_tf = True
    if zones == zones_expected:
        z_tf = True
    # assert(voxel_zones.all() == voxel_zones_expected.all())
    # assert(zones == zones_expected)
    return [vz_tf, z_tf]
Esempio n. 50
0
def test_unstructured_mesh_from_file():
    filename = os.path.join(os.path.dirname(__file__),
                            "files_mesh_test/unstr.h5m")
    sm = Mesh(mesh=filename)
Esempio n. 51
0
def test_wwinp_np():
    if not HAVE_PYMOAB:
        raise SkipTest

    thisdir = os.path.dirname(__file__)
    wwinp_file = os.path.join(thisdir, 'mcnp_wwinp_wwinp_np.txt')
    expected_h5m = os.path.join(thisdir, 'mcnp_wwinp_mesh_np.h5m')
    expected_sm = Mesh(mesh=expected_h5m, structured=True)
    output = os.path.join(os.getcwd(), 'test_wwinp')

    # Read in the wwinp file to an object and check resulting attributes.
    ww1 = mcnp.Wwinp()
    ww1.read_wwinp(wwinp_file)
    assert_equal(ww1.ni, 2)
    assert_equal(ww1.nr, 10)
    assert_equal(ww1.ne, [7, 1])
    assert_equal(ww1.nf, [1, 8, 6])
    assert_equal(ww1.origin, [-100, -100, -100])
    assert_equal(ww1.nc, [1, 3, 1])
    assert_equal(ww1.nwg, 1)
    assert_equal(ww1.cm, [[100], [-50, 60, 100], [100]])
    assert_equal(ww1.fm, [[1], [1, 3, 4], [6]])
    assert_equal(ww1.e[0],
                 [0.1, 0.14678, 0.21544, 0.31623, 0.46416, 0.68129, 1.0000])
    assert_array_equal(ww1.e[1], [100])
    assert_equal(ww1.bounds,
                 [[-100.0, 100],
                  [
                      -100.0, -50.0, -13.333333333333336, 23.333333333333329,
                      60.0, 70.0, 80.0, 90.0, 100.0
                  ],
                  [
                      -100.0, -66.666666666666657, -33.333333333333329, 0.0,
                      33.333333333333343, 66.666666666666657, 100.0
                  ]])

    expected_ves = list(expected_sm.structured_iterate_hex("zyx"))
    written_ves = list(expected_sm.structured_iterate_hex("zyx"))
    for expected_ve, written_ve in zip(expected_ves, written_ves):
        expected = expected_sm.ww_n[expected_ve]
        written = ww1.ww_n[written_ve]
        assert_array_equal(written, expected)

    expected_ves = list(expected_sm.structured_iterate_hex("zyx"))
    written_ves = list(expected_sm.structured_iterate_hex("zyx"))
    for expected_ve, written_ve in zip(expected_ves, written_ves):
        expected = expected_sm.ww_p[expected_ve]
        written = ww1.ww_p[written_ve]
        assert_array_equal(written, expected)

    # Create an new object based off of only the mesh attribute of the first
    # object and check resutling attributes.
    ww2 = mcnp.Wwinp()
    ww2.read_mesh(ww1.mesh)
    assert_equal(ww2.ni, 2)
    assert_equal(ww2.nr, 10)
    assert_equal(ww2.ne, [7, 1])
    assert_equal(ww2.nf, [1, 8, 6])
    assert_equal(ww2.origin, [-100, -100, -100])
    assert_equal(ww2.nc, [1, 3, 1])
    assert_equal(ww2.nwg, 1)
    assert_equal(ww2.cm, [[100], [-50, 60, 100], [100]])
    assert_equal(ww2.fm, [[1], [1, 3, 4], [6]])
    assert_array_equal(
        ww2.e[0], [0.1, 0.14678, 0.21544, 0.31623, 0.46416, 0.68129, 1.0000])
    assert_array_equal(ww2.e[1], [100])
    assert_equal(ww2.bounds,
                 [[-100.0, 100],
                  [
                      -100.0, -50.0, -13.333333333333336, 23.333333333333329,
                      60.0, 70.0, 80.0, 90.0, 100.0
                  ],
                  [
                      -100.0, -66.666666666666657, -33.333333333333329, 0.0,
                      33.333333333333343, 66.666666666666657, 100.0
                  ]])

    expected_ves = list(expected_sm.structured_iterate_hex("zyx"))
    written_ves = list(expected_sm.structured_iterate_hex("zyx"))
    for expected_ve, written_ve in zip(expected_ves, written_ves):
        expected = expected_sm.ww_n[expected_ve]
        written = ww2.ww_n[written_ve]
        assert_array_equal(written, expected)

    expected_ves = list(expected_sm.structured_iterate_hex("zyx"))
    written_ves = list(expected_sm.structured_iterate_hex("zyx"))
    for expected_ve, written_ve in zip(expected_ves, written_ves):
        expected = expected_sm.ww_p[expected_ve]
        written = ww2.ww_p[written_ve]
        assert_array_equal(written, expected)

    # write a new wwinp file and verify that is same wwinp file used as an
    # input to this test
    ww2.write_wwinp(output)
    expected_output = wwinp_file

    with open(output) as f:
        written = f.readlines()

    with open(expected_output) as f:
        expected = f.readlines()

    # check to make sure file are the same except for the data/time info
    # on line 1
    assert_equal(written[0].split()[:-2], expected[0].split()[:-2])
    assert_equal(len(written), len(expected))
    for i in range(1, len(expected)):
        for j in range(0, len(expected[i].split())):
            assert_equal(float(written[i].split()[j]),
                         float(expected[i].split()[j]))

    os.remove(output)
Esempio n. 52
0
def test_tag_e_bounds():
    m = Mesh(structured=True, structured_coords=[[0, 1, 2], [0, 1, 3], [0, 1]])
    e_bounds = np.array([0.0, 0.1, 20])
    m = tag_e_bounds(m, e_bounds)
    assert_array_equal(m.e_bounds[m], e_bounds)
Esempio n. 53
0
def test_irradiation_setup_structured():

    meshtal = os.path.join(thisdir, "files_test_r2s", "meshtal_2x2x1")
    tally_num = 4
    cell_mats = {
        2: Material({2004: 1.0}, density=1.0),
        3: Material({
            3007: 0.4,
            3006: 0.6
        }, density=2.0)
    }
    alara_params = "Bogus line for testing"
    geom = os.path.join(thisdir, "unitbox.h5m")
    num_rays = 9
    grid = True
    flux_tag = "n_flux"
    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")

    irradiation_setup(meshtal, cell_mats, alara_params, tally_num, geom,
                      num_rays, grid, flux_tag, fluxin, reverse, alara_inp,
                      alara_matlib, output_mesh)

    #  expected output files
    exp_alara_inp = os.path.join(thisdir, "files_test_r2s", "exp_alara_inp")
    exp_alara_matlib = os.path.join(thisdir, "files_test_r2s",
                                    "exp_alara_matlib")
    exp_fluxin = os.path.join(thisdir, "files_test_r2s", "exp_fluxin")

    #  test alara input file
    with open(alara_inp, 'r') as f1, open(exp_alara_inp, 'r') as f2:
        for a, b in zip(f1.readlines(), f2.readlines()):
            assert_equal(a, b)

    #  test alara matlibe file
    with open(alara_matlib, 'r') as f1, open(exp_alara_matlib) as f2:
        for a, b in zip(f1.readlines(), f2.readlines()):
            assert_equal(a, b)

    #  test alara fluxin file
    with open(fluxin, 'r') as f1, open(exp_fluxin) as f2:
        for a, b in zip(f1.readlines(), f2.readlines()):
            assert_equal(a, b)

    # 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]

    m = Mesh(structured=True, mesh=output_mesh, mats=output_mesh)
    for i, mat, _ in m:
        assert_almost_equal(mat.density, 1.962963E+00)
        assert_equal(len(mat.comp), 3)
        assert_almost_equal(mat.comp[20040000], 1.886792E-02)
        assert_almost_equal(mat.comp[30060000], 5.886792E-01)
        assert_almost_equal(mat.comp[30070000], 3.924528E-01)
        assert_array_equal(m.n_flux[i], fluxes[i])
        assert_array_equal(m.n_flux_err[i], errs[i])
        assert_almost_equal(m.n_flux_total[i], tot_fluxes[i])
        assert_almost_equal(m.n_flux_err_total[i], tot_errs[i])

    os.remove(alara_inp)
    os.remove(alara_matlib)
    os.remove(fluxin)
    os.remove(output_mesh)
Esempio n. 54
0
def test_write_fluxin_multiple_subvoxel():
    """This function tests the flux_mesh_to_fluxin function for a multiple
    energy group case under sub-voxel r2s.
    """

    if not HAVE_PYMOAB:
        raise SkipTest

    output_name = "fluxin_subvoxel.out"
    forward_fluxin = os.path.join(thisdir, "files_test_alara",
                                  "fluxin_multiple_forward_subvoxel.txt")
    reverse_fluxin = os.path.join(thisdir, "files_test_alara",
                                  "fluxin_multiple_reverse_subvoxel.txt")
    output = os.path.join(os.getcwd(), output_name)

    flux_mesh = Mesh(structured=True,
                     structured_coords=[[0, 1, 2], [0, 1, 2], [0, 1]])
    flux_data = [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14],
                 [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28]]
    flux_mesh.tag("flux", flux_data, 'nat_mesh', size=7, dtype=float)

    cell_fracs = np.zeros(6,
                          dtype=[('idx', np.int64), ('cell', np.int64),
                                 ('vol_frac', np.float64),
                                 ('rel_error', np.float64)])

    cell_fracs[:] = [(0, 11, 1, 0.0), (1, 11, 0.5, 0.0), (1, 12, 0.5, 0.0),
                     (2, 11, 0.5, 0.0), (2, 13, 0.5, 0.0), (3, 13, 1, 0.0)]

    cell_mats = {
        11: Material({'H': 1.0}, density=1.0),
        12: Material({'He': 1.0}, density=1.0),
        13: Material({}, density=0.0, metadata={'name': 'void'})
    }

    # test forward writting
    mesh_to_fluxin(flux_mesh, "flux", output_name, False, True, cell_fracs,
                   cell_mats)

    with open(output) as f:
        written = f.readlines()

    with open(forward_fluxin) as f:
        expected = f.readlines()

    assert_equal(written, expected)
    if os.path.isfile(output):
        os.remove(output)

    # test reverse writting
    mesh_to_fluxin(flux_mesh, "flux", output_name, True, True, cell_fracs,
                   cell_mats)

    with open(output) as f:
        written = f.readlines()

    with open(reverse_fluxin) as f:
        expected = f.readlines()

    assert_equal(written, expected)
    if os.path.isfile(output):
        os.remove(output)
Esempio n. 55
0
def test_tag_source_intensity():
    m = Mesh(structured=True, structured_coords=[[0, 1, 2], [0, 1, 3], [0, 1]])
    source_intensity = 1.0
    m = tag_source_intensity(m, source_intensity)
    assert_array_equal(m.source_intensity[m], source_intensity)
Esempio n. 56
0
class TestArithmetic():
    def arithmetic_mesh_setup(self):
        self.mesh_1 = Mesh(structured_coords=[[-1, 0, 1], [-1, 0, 1], [0, 1]],
                           structured=True)
        volumes1 = list(self.mesh_1.structured_iterate_hex("xyz"))
        volumes2 = list(self.mesh_1.structured_iterate_hex("xyz"))
        flux_tag = self.mesh_1.mesh.tag_get_handle("flux",
                                                   1,
                                                   types.MB_TYPE_DOUBLE,
                                                   types.MB_TAG_DENSE,
                                                   create_if_missing=True)
        flux_data = [1.0, 2.0, 3.0, 4.0]
        self.mesh_1.mesh.tag_set_data(flux_tag, volumes1, flux_data)

        self.mesh_2 = Mesh(structured_coords=[[-1, 0, 1], [-1, 0, 1], [0, 1]],
                           structured=True)
        volumes1 = list(self.mesh_2.structured_iterate_hex("xyz"))
        volumes2 = list(self.mesh_2.structured_iterate_hex("xyz"))
        flux_tag = self.mesh_2.mesh.tag_get_handle("flux",
                                                   1,
                                                   types.MB_TYPE_DOUBLE,
                                                   types.MB_TAG_DENSE,
                                                   create_if_missing=True)
        flux_data = [1.1, 2.2, 3.3, 4.4]
        self.mesh_2.mesh.tag_set_data(flux_tag, volumes1, flux_data)

    def arithmetic_statmesh_setup(self):
        self.statmesh_1 = StatMesh(structured_coords=[[-1, 0, 1], [-1, 0, 1],
                                                      [0, 1]],
                                   structured=True)
        volumes1 = list(self.statmesh_1.structured_iterate_hex("xyz"))
        volumes2 = list(self.statmesh_1.structured_iterate_hex("xyz"))
        flux_tag = self.statmesh_1.mesh.tag_get_handle("flux",
                                                       1,
                                                       types.MB_TYPE_DOUBLE,
                                                       types.MB_TAG_DENSE,
                                                       create_if_missing=True)
        error_tag = self.statmesh_1.mesh.tag_get_handle("flux_rel_error",
                                                        1,
                                                        types.MB_TYPE_DOUBLE,
                                                        types.MB_TAG_DENSE,
                                                        create_if_missing=True)
        flux_data = [1.0, 2.0, 3.0, 4.0]
        error_data = [0.1, 0.2, 0.3, 0.4]
        self.statmesh_1.mesh.tag_set_data(flux_tag, volumes1, flux_data)
        self.statmesh_1.mesh.tag_set_data(error_tag, volumes2, error_data)

        self.statmesh_2 = StatMesh(structured_coords=[[-1, 0, 1], [-1, 0, 1],
                                                      [0, 1]],
                                   structured=True)
        volumes1 = list(self.statmesh_2.structured_iterate_hex("xyz"))
        volumes2 = list(self.statmesh_2.structured_iterate_hex("xyz"))
        flux_tag = self.statmesh_2.mesh.tag_get_handle("flux",
                                                       1,
                                                       types.MB_TYPE_DOUBLE,
                                                       types.MB_TAG_DENSE,
                                                       create_if_missing=True)
        error_tag = self.statmesh_2.mesh.tag_get_handle("flux_rel_error",
                                                        1,
                                                        types.MB_TYPE_DOUBLE,
                                                        types.MB_TAG_DENSE,
                                                        create_if_missing=True)
        flux_data = [1.1, 2.2, 3.3, 4.4]
        error_data = [0.1, 0.2, 0.3, 0.4]
        self.statmesh_2.mesh.tag_set_data(flux_tag, volumes1, flux_data)
        self.statmesh_2.mesh.tag_set_data(error_tag, volumes2, error_data)

    def test_add_mesh(self):
        self.arithmetic_mesh_setup()
        self.mesh_1 += self.mesh_2
        exp_res = [2.1, 4.2, 6.3, 8.4]
        flux_tag = self.mesh_1.mesh.tag_get_handle("flux")
        obs_res = [
            self.mesh_1.mesh.tag_get_data(flux_tag, vol, flat=True)[0]
            for vol in self.mesh_1.structured_iterate_hex("xyz")
        ]
        assert_array_almost_equal(exp_res, obs_res)

    def test_subtract_mesh(self):
        self.arithmetic_mesh_setup()
        self.mesh_1 -= self.mesh_2
        exp_res = [-0.1, -0.2, -0.3, -0.4]
        flux_tag = self.mesh_1.mesh.tag_get_handle("flux")
        obs_res = [
            self.mesh_1.mesh.tag_get_data(flux_tag, vol, flat=True)[0]
            for vol in self.mesh_1.structured_iterate_hex("xyz")
        ]
        assert_array_almost_equal(exp_res, obs_res)

    def test_multiply_mesh(self):
        self.arithmetic_mesh_setup()
        self.mesh_1 *= self.mesh_2
        exp_res = [1.1, 4.4, 9.9, 17.6]
        flux_tag = self.mesh_1.mesh.tag_get_handle("flux")
        obs_res = [
            self.mesh_1.mesh.tag_get_data(flux_tag, vol, flat=True)[0]
            for vol in self.mesh_1.structured_iterate_hex("xyz")
        ]
        assert_array_almost_equal(exp_res, obs_res)

    def test_divide_mesh(self):
        self.arithmetic_mesh_setup()
        self.mesh_1 /= self.mesh_2
        exp_res = [0.9090909091, 0.9090909091, 0.9090909091, 0.9090909091]
        flux_tag = self.mesh_1.mesh.tag_get_handle("flux")
        obs_res = [
            self.mesh_1.mesh.tag_get_data(flux_tag, vol, flat=True)[0]
            for vol in self.mesh_1.structured_iterate_hex("xyz")
        ]
        assert_array_almost_equal(exp_res, obs_res)

    def test_add_statmesh(self):
        self.arithmetic_statmesh_setup()
        self.statmesh_1 += self.statmesh_2
        exp_res = [2.1, 4.2, 6.3, 8.4]
        exp_err = [
            0.070790803558659549, 0.1415816071173191, 0.21237241067597862,
            0.28316321423463819
        ]
        flux_tag = self.statmesh_1.mesh.tag_get_handle("flux")
        obs_res = [
            self.statmesh_1.mesh.tag_get_data(flux_tag, vol, flat=True)[0]
            for vol in self.statmesh_1.structured_iterate_hex("xyz")
        ]
        flux_err_tag = self.statmesh_1.mesh.tag_get_handle("flux_rel_error")
        obs_err = [
            self.statmesh_1.mesh.tag_get_data(flux_err_tag, vol, flat=True)[0]
            for vol in self.statmesh_1.structured_iterate_hex("xyz")
        ]
        assert_array_almost_equal(exp_res, obs_res)
        assert_array_almost_equal(exp_err, obs_err)

    def test_subtract_statmesh(self):
        self.arithmetic_statmesh_setup()
        self.statmesh_1 -= self.statmesh_2
        exp_res = [-0.1, -0.2, -0.3, -0.4]
        exp_err = [-1.4866068747, -2.9732137495, -4.4598206242, -5.9464274989]
        flux_tag = self.statmesh_1.mesh.tag_get_handle("flux")
        obs_res = [
            self.statmesh_1.mesh.tag_get_data(flux_tag, vol, flat=True)[0]
            for vol in self.statmesh_1.structured_iterate_hex("xyz")
        ]
        flux_err_tag = self.statmesh_1.mesh.tag_get_handle("flux_rel_error")
        obs_err = [
            self.statmesh_1.mesh.tag_get_data(flux_err_tag, vol, flat=True)[0]
            for vol in self.statmesh_1.structured_iterate_hex("xyz")
        ]
        assert_array_almost_equal(exp_res, obs_res)
        assert_array_almost_equal(exp_err, obs_err)

    def test_multiply_statmesh(self):
        self.arithmetic_statmesh_setup()
        self.statmesh_1 *= self.statmesh_2
        exp_res = [1.1, 4.4, 9.9, 17.6]
        exp_err = [
            0.1414213562,
            0.2828427125,
            0.4242640687,
            0.5656854249,
        ]
        flux_tag = self.statmesh_1.mesh.tag_get_handle("flux")
        obs_res = [
            self.statmesh_1.mesh.tag_get_data(flux_tag, vol, flat=True)[0]
            for vol in self.statmesh_1.structured_iterate_hex("xyz")
        ]
        flux_err_tag = self.statmesh_1.mesh.tag_get_handle("flux_rel_error")
        obs_err = [
            self.statmesh_1.mesh.tag_get_data(flux_err_tag, vol, flat=True)[0]
            for vol in self.statmesh_1.structured_iterate_hex("xyz")
        ]
        assert_array_almost_equal(exp_res, obs_res)
        assert_array_almost_equal(exp_err, obs_err)

    def test_divide_statmesh(self):
        self.arithmetic_statmesh_setup()
        self.statmesh_1 /= self.statmesh_2
        exp_res = [0.9090909091, 0.9090909091, 0.9090909091, 0.9090909091]
        exp_err = [0.1414213562, 0.2828427125, 0.4242640687, 0.5656854249]
        flux_tag = self.statmesh_1.mesh.tag_get_handle("flux")
        obs_res = [
            self.statmesh_1.mesh.tag_get_data(flux_tag, vol, flat=True)[0]
            for vol in self.statmesh_1.structured_iterate_hex("xyz")
        ]
        flux_err_tag = self.statmesh_1.mesh.tag_get_handle("flux_rel_error")
        obs_err = [
            self.statmesh_1.mesh.tag_get_data(flux_err_tag, vol, flat=True)[0]
            for vol in self.statmesh_1.structured_iterate_hex("xyz")
        ]
        assert_array_almost_equal(exp_res, obs_res)
        assert_array_almost_equal(exp_err, obs_err)
Esempio n. 57
0
def test_single_meshtally_meshtal():
    """Test a meshtal file containing a single mesh tally.
    """

    if not HAVE_PYMOAB:
        raise SkipTest

    thisdir = os.path.dirname(__file__)
    meshtal_file = os.path.join(thisdir, "mcnp_meshtal_single_meshtal.txt")
    expected_h5m = os.path.join(thisdir, "mcnp_meshtal_single_mesh.h5m")
    expected_sm = Mesh(mesh=expected_h5m, structured=True)

    tags = {
        4: ["n_result", "n_rel_error", "n_total_result", "n_total_rel_error"]
    }

    meshtal_object = mcnp.Meshtal(meshtal_file, tags, meshes_have_mats=True)
    assert_not_equal(meshtal_object.tally[4].mats, None)

    # test Meshtal attributes
    assert_equal(meshtal_object.version, '5.mpi')

    assert_equal(meshtal_object.ld, "09282010")

    assert_equal(meshtal_object.title,
                 "Input file to general test meshtal file")

    assert_equal(meshtal_object.histories, 100000)

    # test MeshTally attributes
    assert_equal(meshtal_object.tally[4].tally_number, 4)
    assert_equal(meshtal_object.tally[4].particle, "neutron")
    assert_equal(meshtal_object.tally[4].dose_response, True)
    assert_equal(meshtal_object.tally[4].x_bounds,
                 [-200.00, -66.67, 66.67, 200.00])
    assert_equal(meshtal_object.tally[4].y_bounds,
                 [-200.00, -120.00, -40.00, 40.00, 120.00, 200.00])
    assert_equal(meshtal_object.tally[4].z_bounds,
                 [-200.00, -50.00, 100.00, 200.00])
    assert_equal(meshtal_object.tally[4].e_bounds,
                 [0.00E+00, 1.00E-01, 2.00E-01, 1.00E+00])

    # test vector tags
    for v_e, expected_v_e in zip(
            meshtal_object.tally[4].structured_iterate_hex("xyz"),
            expected_sm.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[4].n_result[v_e]
        expected = expected_sm.n_result[expected_v_e]
        assert_array_equal(written, expected)
    for v_e, expected_v_e in zip(
            meshtal_object.tally[4].structured_iterate_hex("xyz"),
            expected_sm.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[4].n_rel_error[v_e]
        expected = expected_sm.n_rel_error[expected_v_e]
        assert_array_equal(written, expected)

    # test total tag
    for v_e, expected_v_e in zip(
            meshtal_object.tally[4].structured_iterate_hex("xyz"),
            expected_sm.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[4].n_total_result[v_e]
        expected = expected_sm.n_total_result[expected_v_e]
        assert_equal(written, expected)
    for v_e, expected_v_e in zip(
            meshtal_object.tally[4].structured_iterate_hex("xyz"),
            expected_sm.structured_iterate_hex("xyz")):
        written = meshtal_object.tally[4].n_total_rel_error[v_e]
        expected = expected_sm.n_total_rel_error[expected_v_e]
        assert_equal(written, expected)
Esempio n. 58
0
def step1(cfg):
    """ This function writes the PARTISN input file for the adjoint photon 
    transport   
    Parameters
    ----------
    cfg : dictionary
        User input for step 1 from the config.yml file
    """
    # Get user-input from config file
    geom = cfg['geom_file']
    cells = [cfg['src_cell']]
    src_vol = [float(cfg['src_vol'])]

    try:
        origin_x, origin_y, origin_z = cfg['origin'].split(' ')
    except:
        print("Too few entries in origin location")

    xmesh = cfg['xmesh']
    xints = cfg['xints']
    ymesh = cfg['ymesh']
    yints = cfg['yints']
    zmesh = cfg['zmesh']
    zints = cfg['zints']

    # Create structured mesh
    sc = [
        np.linspace(float(origin_x), float(xmesh),
                    float(xints) + 1),
        np.linspace(float(origin_y), float(ymesh),
                    float(yints) + 1),
        np.linspace(float(origin_z), float(zmesh),
                    float(zints) + 1)
    ]
    m = Mesh(structured=True, structured_coords=sc)
    m.write_hdf5("blank_mesh.h5m")

    # Generate 42 photon energy bins [eV]
    #  First bin has been replaced with 1 for log interpolation
    photon_bins = np.array([
        1e-6, 0.01, 0.02, 0.03, 0.045, 0.06, 0.07, 0.075, 0.1, 0.15, 0.2, 0.3,
        0.4, 0.45, 0.51, 0.512, 0.6, 0.7, 0.8, 1, 1.33, 1.34, 1.5, 1.66, 2,
        2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 10, 12, 14, 20, 30, 50
    ])
    # ICRP 74 flux-to-dose conversion factors in pico-Sv/s per photon flux
    de = np.array([
        0.01, 0.015, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.15, 0.2,
        0.3, 0.4, 0.5, 0.6, 0.8, 1, 2, 4, 6, 8, 10
    ])
    df = np.array([
        0.0485, 0.1254, 0.205, 0.2999, 0.3381, 0.3572, 0.378, 0.4066, 0.4399,
        0.5172, 0.7523, 1.0041, 1.5083, 1.9958, 2.4657, 2.9082, 3.7269, 4.4834,
        7.4896, 12.0153, 15.9873, 19.9191, 23.76
    ])
    # Convert to Sv/s per photon FLUX
    pico = 1.0e-12
    df = df * pico
    # Convert pointwise data to group data for log interpolation
    photon_spectrum = pointwise_collapse(photon_bins,
                                         de,
                                         df,
                                         logx=True,
                                         logy=True)
    #  Anything below 0.01 MeV should be assigned the DF value of 0.01 MeV
    photon_spectrum[0] = df[0]
    # Total number of groups is 217 (42 photon + 175 neutron)
    spectra = [np.append(photon_spectrum, np.zeros(175))]
    # The spectrum is normalized by PyNE, so we need to mutliply by the sum of
    # intensities in the spectrum.
    # Additionally, we divide by the volume of the source cell in order to get
    # source density.
    intensities = [np.sum(spectra) / src_vol]

    # Load geometry into DAGMC
    load(geom)
    # Generate isotropic photon volume source
    source, dg = isotropic_vol_source(geom, m, cells, spectra, intensities)

    # PARTISN input
    ngroup = 217  # total number of energy groups
    cards = _cards(source)  # block 1, 3, 5 input values
    names_dict = _names_dict(
    )  # dictionary of isotopes (PyNE nucids to bxslib names)

    write_partisn_input(m,
                        geom,
                        ngroup,
                        cards=cards,
                        dg=dg,
                        names_dict=names_dict,
                        data_hdf5path="/materials",
                        nuc_hdf5path="/nucid",
                        fine_per_coarse=1)
Esempio n. 59
0
def test_record_to_geom_subvoxel():

    if not HAVE_PYMOAB:
        raise SkipTest

    expected_geom = os.path.join(thisdir, "files_test_alara",
                                 "alara_record_geom_subvoxel.txt")
    expected_matlib = os.path.join(thisdir, "files_test_alara",
                                   "alara_record_matlib_subvoxel.txt")
    geom = os.path.join(os.getcwd(), "alara_record_geom")
    matlib = os.path.join(os.getcwd(), "alara_record_matlib")
    cell_fracs = np.zeros(11,
                          dtype=[('idx', np.int64), ('cell', np.int64),
                                 ('vol_frac', np.float64),
                                 ('rel_error', np.float64)])

    cell_mats = {
        11:
        Material({
            'H1': 1.0,
            'K39': 1.0
        },
                 density=1.1,
                 metadata={'name': 'fake_mat'}),
        12:
        Material({
            'H1': 0.1,
            'O16': 1.0
        },
                 density=1.2,
                 metadata={'name': 'water'}),
        13:
        Material({'He4': 42.0}, density=1.3, metadata={'name': 'helium'}),
        14:
        Material({}, density=0.0, metadata={'name': 'void'}),
        15:
        Material({}, density=0.0, metadata={'name': 'void'}),
        16:
        Material({
            'H1': 1.0,
            'K39': 1.0
        },
                 density=1.1,
                 metadata={'name': 'fake_mat'})
    }

    cell_fracs[:] = [(0, 11, 0.55, 0.0), (0, 12, 0.45, 0.0), (1, 11, 0.2, 0.0),
                     (1, 12, 0.3, 0.0), (1, 13, 0.5, 0.0), (2, 11, 0.15, 0.0),
                     (2, 14, 0.01, 0.0), (2, 15, 0.04, 0.0), (2, 16, 0.8, 0.0),
                     (3, 11, 0.55, 0.0), (3, 12, 0.45, 0.0)]

    m = Mesh(structured_coords=[[-1, 0, 1], [-1, 0, 1], [0, 1]],
             structured=True,
             mats=None)

    record_to_geom(m, cell_fracs, cell_mats, geom, matlib, sub_voxel=True)

    assert (filecmp.cmp(geom, expected_geom))
    if os.path.isfile(geom):
        os.remove(geom)

    assert (filecmp.cmp(matlib, expected_matlib))
    if os.path.isfile(matlib):
        os.remove(matlib)
Esempio n. 60
0
def test_tag_decay_time():
    m = Mesh(structured=True, structured_coords=[[0, 1, 2], [0, 1, 3], [0, 1]])
    decay_time = 1.0
    m = tag_decay_time(m, decay_time)
    assert_array_equal(m.decay_time[m], decay_time)