示例#1
0
def test_wwinp_to_h5m():
    thisdir = os.path.dirname(__file__)
    wwinp = os.path.join(thisdir, "files_test_wwinp_to_h5m/wwinp_test.e")
    output = os.path.join(os.getcwd(), "wwinp_mesh.h5m")

    if output in os.listdir("."):
        os.remove(output)

    wwinp_to_h5m.cartesian(wwinp, output)

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

    expected_sm = ScdMesh.fromFile(os.path.join(thisdir, "files_test_wwinp_to_h5m/expected_wwinp_mesh.h5m"))
    written_sm = ScdMesh.fromFile(output)

    for x in range(0, 5):
        for y in range(0, 6):
            for z in range(0, 10):
                expected_voxel = expected_sm.getHex(x, y, z)
                expected = expected_sm.imesh.getTagHandle("ww_n_group_001")[expected_voxel]
                written_voxel = written_sm.getHex(x, y, z)
                written = written_sm.imesh.getTagHandle("ww_n_group_001")[written_voxel]
                assert_equal(written, expected)

    os.remove(output)
示例#2
0
def test_wwinp_to_h5m():
    wwinp = 'files_test_wwinp_to_h5m/wwinp_test.txt'
    output = 'wwinp_mesh.h5m'
    
    if output in os.listdir('.'):
        os.remove(output)
    
    wwinp_to_h5m.cartesian(wwinp, output)
    
    with open(output) as f:
        written = f.read()
    
    expected_sm = ScdMesh.fromFile('files_test_wwinp_to_h5m/expected_wwinp_mesh.h5m')
    written_sm = ScdMesh.fromFile(output)
    
    for x in range(0,5):
        for y in range(0,6):
            for z in range(0,10):
                expected_voxel = expected_sm.getHex(x,y,z)
                expected = expected_sm.imesh.getTagHandle('ww_n_group_001')[expected_voxel]
                written_voxel = written_sm.getHex(x,y,z)
                written = written_sm.imesh.getTagHandle('ww_n_group_001')[written_voxel]
                assert_equal(written, expected)
    
    os.remove(output)
示例#3
0
    def test_large_iterator(self):

        print "building large mesh"
        big = ScdMesh(range(1,100), range(101,200), range(201,300))
        print "iterating (1)"
        for i in big.iterateHex():
            pass
        print "iterating (2)"
        for i in big.iterateHex( 'yzx' ):
            pass
示例#4
0
    def test_get_divs(self):
        x = [1, 2.5, 4, 6.9]
        y = [-12, -10, -.5]
        z = [100, 200]

        sm = ScdMesh( x, y, z )

        self.assertEqual( sm.getDivisions('x'), x )
        self.assertEqual( sm.getDivisions('y'), y )
        self.assertEqual( sm.getDivisions('z'), z )
示例#5
0
    def setUp(self):
        self.mesh = iMesh.Mesh()
        self.sm = ScdMesh( range(10,15), # i = 0,1,2,3
                           range(21,25), # j = 0,1,2
                           range(31,34), # k = 0,1
                           self.mesh )

        self.I = range(0,4)
        self.J = range(0,3)
        self.K = range(0,2)
示例#6
0
    def test_get_hex(self):
        # mesh with valid i values 0-4, j values 0-3, k values 0-2
        sm = ScdMesh( range(11,16), range(21,25), range(31,34) )
        def check( e ):
            self.assertTrue( isinstance(e, iBase.Entity) )
        check(sm.getHex(0, 0, 0))
        check(sm.getHex(1, 1, 1))
        check(sm.getHex(3, 0, 0))
        check(sm.getHex(3, 2, 1))

        self.assertRaises(ScdMeshError, sm.getHex, -1,-1,-1)
        self.assertRaises(ScdMeshError, sm.getHex, 4, 0, 0)
        self.assertRaises(ScdMeshError, sm.getHex, 0, 3, 0)
        self.assertRaises(ScdMeshError, sm.getHex, 0, 0, 2)
示例#7
0
    def test_get_vtx(self):
        # mesh with valid i values 0-4, j values 0-3, k values 0-2
        x_range = numpy.array(range(10,15),dtype=numpy.float64)
        y_range = numpy.array(range(21,24),dtype=numpy.float64)
        z_range = numpy.array(range(31,33),dtype=numpy.float64)

        sm = ScdMesh( x_range, y_range, z_range, self.mesh ) 

        for i,x in enumerate(x_range):
            for j,y in enumerate(y_range):
                for k,z in enumerate(z_range):
                    vtx = sm.getVtx(i,j,k)
                    vcoord = self.mesh.getVtxCoords( vtx )
                    self.assertTrue( all( vcoord == [x,y,z]) )
示例#8
0
def test_h5m_to_wwinp_3D_n():
    thisdir = os.path.dirname(__file__)
    ww_sm_filename = os.path.join(thisdir, 'files_test_wwinp_to_h5m/expected_ww_mesh_3D_n.h5m')
    ww_sm = ScdMesh.fromFile(ww_sm_filename)
    output = os.path.join(os.getcwd(), 'test.e')
    expected_output = os.path.join(thisdir, 'files_test_wwinp_to_h5m/3D_n.e')
    
    if output in os.listdir('.'):
        os.remove(output)
    
    totals_bool = False 
    h5m_to_wwinp.write_wwinp(ww_sm, totals_bool, output)
    
    with open(output) as f:
        written = f.readlines()

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

    # check to make sure the first line is the same except for the date
    assert_equal(written[0].split()[:-2], expected[0].split()[:-2])

    # check to make sure files are the same length
    assert_equal(len(written), len(expected))

    # check to make sure the rest of the lines have the same values
    # since the number formats are different, float comparisons are used
    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)
示例#9
0
def main(arguments=None):

    #Instatiate options parser
    parser = OptionParser\
             (usage='%prog <ww mesh> [options]')

    parser.add_option('-o', dest='output_name', default='wwinp.out',\
        help='Name of WWINP output file, default=%default')

    parser.add_option('-t', action='store_true', dest='totals_bool',\
        default=False, \
        help='If multiple energy groups exist, only use Total \
         default=%default'                          )

    (opts, args) = parser.parse_args(arguments)

    if len(args) != 1:
        parser.error\
        ( '\nNeed exactly 1 argument: <ww mesh>' )

    # load mesh
    ww_mesh = ScdMesh.fromFile(args[0])

    write_wwinp(ww_mesh, opts.totals_bool, opts.output_name)

    print "\tWrote WWINP file '{0}'".format(opts.output_name)

    print "Complete"
示例#10
0
def main():
    """ACTION: Method defines an option parser and handles command-line
    usage of this module.
    REQUIRES: command line arguments to be passed - otherwise prints help
    information.
    """

    usage = "usage: %prog ENERGY_FILE MESH_FILE [options] \n\n" \
            "ENERGY_FILE is a list of the energy bins for each photon energy " \
            "group, with a single energy per line. MESH_FILE is the MOAB " \
            "mesh that will store the contents of ENERGY_FILE in the tag " \
            "'PHTN_ERGS'."
    parser = OptionParser(usage)

    (options, args) = parser.parse_args()

    fr = open(args[0])
    sm = ScdMesh.fromFile(args[1])

    # Call the method to read fr and tag mesh
    read_and_tag_phtn_ergs(fr, sm)

    sm.scdset.save(args[1])
    fr.close()

    return 1
示例#11
0
def test_wwinp_to_h5m_3D_n():
    thisdir = os.path.dirname(__file__)
    wwinp = os.path.join(thisdir, 'files_test_wwinp_to_h5m/3D_n.e')
    expected_file = os.path.join(thisdir, 'files_test_wwinp_to_h5m/expected_ww_mesh_3D_n.h5m')

    written_sm = wwinp_to_h5m.cartesian(wwinp)
    expected_sm = ScdMesh.fromFile(expected_file)
    
    #verify weight window lower bounds are the same
    for x in range(0,14):
        for y in range(0,8):
            for z in range(0,6):
                for e_group in range(1, 8):
                    expected_voxel = expected_sm.getHex(x,y,z)
                    expected = expected_sm.imesh.getTagHandle('ww_n_group_00{0}'.format(e_group))[expected_voxel]
                    written_voxel = written_sm.getHex(x,y,z)
                    written = written_sm.imesh.getTagHandle('ww_n_group_00{0}'.format(e_group))[written_voxel]
                    assert_equal(written, expected)

    #verify correct particle identifier
    assert_equal(written_sm.imesh.getTagHandle('particle')[written_sm.imesh.rootSet], 1)

    #verify correct energy upper bounds
    expected_E = [1E-9, 1E-8, 1E-7, 1E-6, 1E-5, 1E-4, 1E-3]
    written_E = written_sm.imesh.getTagHandle('E_upper_bounds')[written_sm.imesh.rootSet]
    
    for i in range(0, len(expected_E)):
        assert_equal(written_E[i], expected_E[i])
示例#12
0
def test_wwinp_to_h5m_1D_p():
    thisdir = os.path.dirname(__file__)
    wwinp = os.path.join(thisdir, 'files_test_wwinp_to_h5m/1D_p.e')
    expected_file = os.path.join(thisdir, 'files_test_wwinp_to_h5m/expected_ww_mesh_1D_p.h5m')

    written_sm = wwinp_to_h5m.cartesian(wwinp)
    expected_sm = ScdMesh.fromFile(expected_file)
 
    #verify weight window lower bounds are the same
    for x in range(0,1):
        for y in range(0,1):
            for z in range(0,9):
                expected_voxel = expected_sm.getHex(x,y,z)
                expected = expected_sm.imesh.getTagHandle('ww_n_group_001')[expected_voxel]
                written_voxel = written_sm.getHex(x,y,z)
                written = written_sm.imesh.getTagHandle('ww_n_group_001')[written_voxel]
                assert_equal(written, expected)

    #verify correct particle identifier
    assert_equal(written_sm.imesh.getTagHandle('particle')[written_sm.imesh.rootSet], 1)

    #verify correct energy upper bounds
    expected_E = 100
    written_E = written_sm.imesh.getTagHandle('E_upper_bounds')[written_sm.imesh.rootSet]

    assert_equal(written_E, expected_E)
示例#13
0
def main():
    """Method defines an option parser and handles command-line
    usage of this module.

    Notes
    -----
    Requires command line arguments to be passed - otherwise prints help
    information.
    """

    usage = "usage: %prog input-h5m-file [options] arg"
    parser = OptionParser(usage)

    # Input and mesh file names
    parser.add_option("-o","--output",action="store",dest="output", \
            default="gammas",help="Option specifies the name of the 'gammas'" \
            "file. Default: %default")
    #

    (options, args) = parser.parse_args()

    # Create ScdMesh object, which also loads 'meshfile' into mesh.
    sm = ScdMesh.fromFile(args[0])

    gen_gammas_file_from_h5m(sm, options.output)

    return 1
示例#14
0
def test_wwinp_to_h5m_1D_p():
    thisdir = os.path.dirname(__file__)
    wwinp = os.path.join(thisdir, 'files_test_wwinp_to_h5m/1D_p.e')
    expected_file = os.path.join(
        thisdir, 'files_test_wwinp_to_h5m/expected_ww_mesh_1D_p.h5m')

    written_sm = wwinp_to_h5m.cartesian(wwinp)
    expected_sm = ScdMesh.fromFile(expected_file)

    #verify weight window lower bounds are the same
    for x in range(0, 1):
        for y in range(0, 1):
            for z in range(0, 9):
                expected_voxel = expected_sm.getHex(x, y, z)
                expected = expected_sm.imesh.getTagHandle(
                    'ww_n_group_001')[expected_voxel]
                written_voxel = written_sm.getHex(x, y, z)
                written = written_sm.imesh.getTagHandle(
                    'ww_n_group_001')[written_voxel]
                assert_equal(written, expected)

    #verify correct particle identifier
    assert_equal(
        written_sm.imesh.getTagHandle('particle')[written_sm.imesh.rootSet], 1)

    #verify correct energy upper bounds
    expected_E = 100
    written_E = written_sm.imesh.getTagHandle('E_upper_bounds')[
        written_sm.imesh.rootSet]

    assert_equal(written_E, expected_E)
示例#15
0
def test_wwinp_to_h5m_3D_n():
    thisdir = os.path.dirname(__file__)
    wwinp = os.path.join(thisdir, 'files_test_wwinp_to_h5m/3D_n.e')
    expected_file = os.path.join(
        thisdir, 'files_test_wwinp_to_h5m/expected_ww_mesh_3D_n.h5m')

    written_sm = wwinp_to_h5m.cartesian(wwinp)
    expected_sm = ScdMesh.fromFile(expected_file)

    #verify weight window lower bounds are the same
    for x in range(0, 14):
        for y in range(0, 8):
            for z in range(0, 6):
                for e_group in range(1, 8):
                    expected_voxel = expected_sm.getHex(x, y, z)
                    expected = expected_sm.imesh.getTagHandle(
                        'ww_n_group_00{0}'.format(e_group))[expected_voxel]
                    written_voxel = written_sm.getHex(x, y, z)
                    written = written_sm.imesh.getTagHandle(
                        'ww_n_group_00{0}'.format(e_group))[written_voxel]
                    assert_equal(written, expected)

    #verify correct particle identifier
    assert_equal(
        written_sm.imesh.getTagHandle('particle')[written_sm.imesh.rootSet], 1)

    #verify correct energy upper bounds
    expected_E = [1E-9, 1E-8, 1E-7, 1E-6, 1E-5, 1E-4, 1E-3]
    written_E = written_sm.imesh.getTagHandle('E_upper_bounds')[
        written_sm.imesh.rootSet]

    for i in range(0, len(expected_E)):
        assert_equal(written_E[i], expected_E[i])
示例#16
0
def main():
    """Method defines an option parser and handles command-line
    usage of this module.

    Notes
    -----
    Requires command line arguments to be passed - otherwise prints help
    information.
    """

    usage = "usage: %prog input-h5m-file [options] arg"
    parser = OptionParser(usage)
    
    # Input and mesh file names
    parser.add_option("-o","--output",action="store",dest="output", \
            default="gammas",help="Option specifies the name of the 'gammas'" \
            "file. Default: %default")
    #
   
    (options, args) = parser.parse_args()

    # Create ScdMesh object, which also loads 'meshfile' into mesh.
    sm = ScdMesh.fromFile(args[0])

    gen_gammas_file_from_h5m(sm, options.output)

    return 1
示例#17
0
def main( arguments = None ):

    #Instatiate options parser
    parser = OptionParser\
             (usage='%prog <ww mesh> [options]')

    parser.add_option('-o', dest='output_name', default='wwinp.out',\
        help='Name of WWINP output file, default=%default')

    parser.add_option('-t', action='store_true', dest='totals_bool',\
        default=False, \
        help='If multiple energy groups exist, only use Total \
         default=%default')

    (opts, args) = parser.parse_args( arguments )

    if len(args) != 1:
        parser.error\
        ( '\nNeed exactly 1 argument: <ww mesh>' )

    # load mesh
    ww_mesh = ScdMesh.fromFile(args[0])


    write_wwinp(ww_mesh, opts.totals_bool, opts.output_name)

    print "\tWrote WWINP file '{0}'".format(opts.output_name)

    print "Complete"
示例#18
0
def main():
    """ACTION: Method defines an option parser and handles command-line
    usage of this module.
    REQUIRES: command line arguments to be passed - otherwise prints help
    information.
    """

    usage = "usage: %prog ENERGY_FILE MESH_FILE [options] \n\n" \
            "ENERGY_FILE is a list of the energy bins for each photon energy " \
            "group, with a single energy per line. MESH_FILE is the MOAB " \
            "mesh that will store the contents of ENERGY_FILE in the tag " \
            "'PHTN_ERGS'."
    parser = OptionParser(usage)

    (options, args) = parser.parse_args()

    fr = open(args[0])
    sm = ScdMesh.fromFile(args[1])

    # Call the method to read fr and tag mesh
    read_and_tag_phtn_ergs(fr, sm)

    mesh.save(args[1])
    fr.close()

    return 1
示例#19
0
def test_h5m_to_wwinp_3D_n():
    thisdir = os.path.dirname(__file__)
    ww_sm_filename = os.path.join(
        thisdir, 'files_test_wwinp_to_h5m/expected_ww_mesh_3D_n.h5m')
    ww_sm = ScdMesh.fromFile(ww_sm_filename)
    output = os.path.join(os.getcwd(), 'test.e')
    expected_output = os.path.join(thisdir, 'files_test_wwinp_to_h5m/3D_n.e')

    if output in os.listdir('.'):
        os.remove(output)

    totals_bool = False
    h5m_to_wwinp.write_wwinp(ww_sm, totals_bool, output)

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

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

    # check to make sure the first line is the same except for the date
    assert_equal(written[0].split()[:-2], expected[0].split()[:-2])

    # check to make sure files are the same length
    assert_equal(len(written), len(expected))

    # check to make sure the rest of the lines have the same values
    # since the number formats are different, float comparisons are used
    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)
示例#20
0
def main( arguments = None ) :

    # Instantiate option parser
    parser = OptionParser\
             (usage='%prog <meshtal_file> <normalization_factor> [options]')

    parser.add_option('-o', dest='mesh_output', default='flux_mesh.h5m',\
                      help = 'Name of mesh output file, default=%default.\
                             For meshtal files with multiple tallies,\
                             if the -o flag is used all tallies must be named,\
                             with file names seperated by commas and no spaces\
                             (e.g. "tally14.h5m,tally24.h5m,tally34.h5m")')
    parser.add_option('-n', dest='norm', default=None,
                      help='Normalization factor, default=%default,\
                            For meshtal files with multiple tallies, if the -n\
                            flag is used, a normalization factor must be\
                            specified for all tallies, seperated by commas but \
                            not spaces (eg. -n 1.1,2.2,3.3) ')
    parser.add_option('-m', dest='smesh_filename', default=None,
                      help='Preexisting mesh on which to tag fluxes')
                         

    (opts, args) = parser.parse_args(arguments)
    
    #if len(args) != 2 :
     #   parser.error('\nNeed 1 argument: meshtal file')
    print "\n\nRunning read_meshtal.py"
    tally_numbers, tally_lines = find_tallies(args[1])
    print "Number of tallies found: {0}\nTally number(s): {1}" \
                                     .format(len(tally_numbers), tally_numbers)

    # Parse input from options parser, generate default values
    if opts.norm :
        norm = opts.norm.split(',')
    else :
        norm = [1]*len(tally_numbers)

    if opts.mesh_output !='flux_mesh.h5m' :
        mesh_output = opts.mesh_output.split(',')
    else:
        mesh_output = []
        for n in range(0, len(tally_numbers)) :
            if len(tally_numbers) == 1 :
                mesh_output.append('flux_mesh.h5m')
            else :
                mesh_output.append('flux_mesh_tally{0}.h5m'.format(tally_numbers[n]))

    # Convert each tally to h5m and name accordingly
    for n in range(0,len(tally_numbers)) :
        print "\nNow parsing tally number {0}".format(tally_numbers[n])
        if opts.smesh_filename:
            alt_sm = ScdMesh.fromFile(opts.smesh_filename)
            sm = read_meshtal(args[1], tally_lines[n], float(norm[n]), smesh=alt_sm)
        else:
            sm = read_meshtal(args[1], tally_lines[n],float(norm[n]))
        sm.scdset.save(mesh_output[n])

        print "\tSaved tally {0} as {1}".format(tally_numbers[n], mesh_output[n])
    print "\nStructured mesh tagging complete\n\n"
示例#21
0
def create_ww_mesh(flux_mesh, e_group_names):
    """
    This function reads a flux mesh and returns a weight window mesh tagged with 
    all zeros in every energy group. This is used for the intial MAGIC weight
    window generation, for which no preexisting weight window mesh is given.

    Parameters
    ----------
    flux_mesh : ScdMesh
        A ScdMesh tagged with fluxes in the form X_group_YYY and or
        X_group_total. Addition required tags are "particle" (1 for n, 2 for p) 
        and E_group_bounds (vector of energy upper bounds).
    e_group_names : vector of energy names
        In the form X_group_YYY or X_group_total.
        
    """

    ww_mesh = ScdMesh(flux_mesh.getDivisions('x'),\
                       flux_mesh.getDivisions('y'),\
                       flux_mesh.getDivisions('z'))

    # create ww tags
    for e_group_name in e_group_names:
        ww_tag = ww_mesh.imesh.createTag('ww_{0}'.format(e_group_name), 1,
                                         float)
        for voxel in ww_mesh.iterateHex('xyz'):
            ww_tag[voxel] = 0

    # create e_upper_bound tags
    e_upper_bounds = \
        flux_mesh.imesh.getTagHandle("E_upper_bounds")[flux_mesh.imesh.rootSet]
    if isinstance(e_upper_bounds, float):
        e_upper_bounds = [e_upper_bounds]

    e_tag = ww_mesh.imesh.createTag("E_upper_bounds", len(e_upper_bounds),
                                    float)
    e_tag[ww_mesh.imesh.rootSet] = \
        flux_mesh.imesh.getTagHandle("E_upper_bounds")[flux_mesh.imesh.rootSet]

    # create  particle tag
    particle = flux_mesh.imesh.getTagHandle("particle")[
        flux_mesh.imesh.rootSet]
    particle_tag = ww_mesh.imesh.createTag("particle", 1, int)
    particle_tag[ww_mesh.imesh.rootSet] = particle

    return ww_mesh
示例#22
0
 def test_vox_cum(self):
     """Verify gammas file for voxel sampling with cumulative bins"""
     self.meshfile = meshfile_g
     self.sm = ScdMesh.fromFile(self.meshfile)
     write_gammas.gen_gammas_file_from_h5m(self.sm,
                                           outfile,
                                           cumulative=True)
     self.compare_gammas(outfile, gammas7)
示例#23
0
def cartesian(wwinp):
    """This function reads in a Cartesian WWINP file and returns a structured
        mesh tagged with weight window lower bounds.
    Parameters
    ----------
    wwinp : file name
        The weight window input file to create a mesh from.
    """

    print "Parsing Cartesian WWINP"

    particle_identifier = linecache.getline(wwinp, 1).split()[2]
    if particle_identifier == '1':
        particle = 'n'
    elif particle_identifier =='2':
        particle = 'p'


    # collect easy to parse energy group and mesh sized info
    num_e_bins = int(linecache.getline(wwinp, 2).split()[-1])
    # total number of fine mesh points
    nfx, nfy, nfz = \
        [int(float(x)) for x in linecache.getline(wwinp, 3).split()[0:3]]
    x0, y0, z0 = [float(x) for x in linecache.getline(wwinp, 3).split()[3:6]]
    # number of course points
    ncx, ncy, ncz = \
        [int(float(x)) for x in linecache.getline(wwinp, 4).split()[0:3]]

    # get the x, y, and z bounds
    x_bounds, x_last_line = block_2_bounds(wwinp, 5, ncx)
    y_bounds, y_last_line = block_2_bounds(wwinp, x_last_line + 1, ncy)
    z_bounds, z_last_line = block_2_bounds(wwinp, y_last_line + 1, ncz)

    # create structured mesh these bounds
    sm = ScdMesh(x_bounds, y_bounds, z_bounds)
    
    # Find the first line of WW values by counting through the e_bin values
    # until the expected number of e_bins is reached
    # Then create a root level tag with energy the energy bounds.
    e_upper_bounds = []
    line_num = z_last_line + 1

    while len(e_upper_bounds) < num_e_bins:
        e_upper_bounds += \
            [float(x) for x in linecache.getline(wwinp, line_num).split()]
        line_num += 1
    
    ww_first_line = line_num

    # tag structured mesh with WW values
    tag_mesh(sm, wwinp, ww_first_line, num_e_bins, nfx*nfy*nfz, particle)

    # tag root level of sm with energy bounds
    tag_e_bin = sm.imesh.createTag("E_upper_bounds", len(e_upper_bounds), float)
    tag_e_bin[sm.imesh.rootSet] = e_upper_bounds

    return sm
示例#24
0
 def test_uni_seq_bias(self):
     """Verify gammas file for uniform sampling with sequential bins and biasing"""
     self.meshfile = meshfile_g
     self.sm = ScdMesh.fromFile(self.meshfile)
     write_gammas.gen_gammas_file_from_h5m(self.sm,
                                           outfile,
                                           sampling='u',
                                           do_bias=True)
     self.compare_gammas(outfile, gammas2)
示例#25
0
def create_ww_mesh(flux_mesh, e_group_names):
    """
    This function reads a flux mesh and returns a weight window mesh tagged with 
    all zeros in every energy group. This is used for the intial MAGIC weight
    window generation, for which no preexisting weight window mesh is given.

    Parameters
    ----------
    flux_mesh : ScdMesh
        A ScdMesh tagged with fluxes in the form X_group_YYY and or
        X_group_total. Addition required tags are "particle" (1 for n, 2 for p) 
        and E_group_bounds (vector of energy upper bounds).
    e_group_names : vector of energy names
        In the form X_group_YYY or X_group_total.
        
    """

    ww_mesh = ScdMesh(flux_mesh.getDivisions('x'),\
                       flux_mesh.getDivisions('y'),\
                       flux_mesh.getDivisions('z'))

    # create ww tags
    for e_group_name in e_group_names:
            ww_tag = ww_mesh.imesh.createTag('ww_{0}'.format(e_group_name), 1, float)
            for voxel in ww_mesh.iterateHex('xyz'):
                ww_tag[voxel] = 0

    # create e_upper_bound tags
    e_upper_bounds = \
        flux_mesh.imesh.getTagHandle("E_upper_bounds")[flux_mesh.imesh.rootSet]
    if isinstance(e_upper_bounds, float):
        e_upper_bounds = [e_upper_bounds]

    e_tag = ww_mesh.imesh.createTag("E_upper_bounds", len(e_upper_bounds), float)
    e_tag[ww_mesh.imesh.rootSet] = \
        flux_mesh.imesh.getTagHandle("E_upper_bounds")[flux_mesh.imesh.rootSet]

    # create  particle tag
    particle = flux_mesh.imesh.getTagHandle("particle")[flux_mesh.imesh.rootSet]
    particle_tag = ww_mesh.imesh.createTag("particle", 1, int)
    particle_tag[ww_mesh.imesh.rootSet] = particle

    return ww_mesh
示例#26
0
def write_magic(flux_mesh_filename, ww_inp_mesh_filename, totals_bool, \
                null_value, output_mesh, tolerance):
    """
    This function takes the filename of the flux mesh and optional wieght window
    mesh, as well necessary parameter, sends them to the magic funtion and
    writes the resulting wieght window mesh.

    Parameters
    ----------
    flux_mesh_filename: ScdMesh file name.
        A ScdMesh tagged with fluxes in the form X_group_YYY and or
        X_group_total. Addition required tags are "particle" (1 for n, 2 for p) 
        and E_group_bounds (vector of energy upper bounds).
    totals_bool : True or False
        Determines whether magic will be applied to individual energy group
        (False), or the total group (True)
    null_value : float
        The weight window lower bound value that is assigned to voxels where the
        relative error on flux exceeds the tolerance. This is only done for 
        initial weight window lower bound generation, not subsequent iterations.
    output_mesh : string
        Filename of output mesh
    tolerance: float
        The maximum relative error allowable for the MAGIC algorithm to create
        a weight window lower bound for for a given voxel for the intial weight
        window lower bound generation, or overwrite preexisting weight window
        lower bounds for subsequent iterations.  
    ww_inp_mesh_filename : ScdMesh file name
        A preexisting weight window mesh to apply MAGIC to.      
    """

    flux_mesh = ScdMesh.fromFile(flux_mesh_filename)

    if ww_inp_mesh_filename != None:
        ww_inp_mesh = ScdMesh.fromFile(ww_inp_mesh_filename)

    else:
        ww_inp_mesh = None
   

    ww_mesh = magic(flux_mesh, totals_bool, null_value, tolerance, ww_inp_mesh)
    ww_mesh.scdset.save(output_mesh)
    print "\tWrote WW mesh file '{0}'".format(output_mesh)
示例#27
0
def write_magic(flux_mesh_filename, ww_inp_mesh_filename, totals_bool, \
                null_value, output_mesh, tolerance):
    """
    This function takes the filename of the flux mesh and optional wieght window
    mesh, as well necessary parameter, sends them to the magic funtion and
    writes the resulting wieght window mesh.

    Parameters
    ----------
    flux_mesh_filename: ScdMesh file name.
        A ScdMesh tagged with fluxes in the form X_group_YYY and or
        X_group_total. Addition required tags are "particle" (1 for n, 2 for p) 
        and E_group_bounds (vector of energy upper bounds).
    totals_bool : True or False
        Determines whether magic will be applied to individual energy group
        (False), or the total group (True)
    null_value : float
        The weight window lower bound value that is assigned to voxels where the
        relative error on flux exceeds the tolerance. This is only done for 
        initial weight window lower bound generation, not subsequent iterations.
    output_mesh : string
        Filename of output mesh
    tolerance: float
        The maximum relative error allowable for the MAGIC algorithm to create
        a weight window lower bound for for a given voxel for the intial weight
        window lower bound generation, or overwrite preexisting weight window
        lower bounds for subsequent iterations.  
    ww_inp_mesh_filename : ScdMesh file name
        A preexisting weight window mesh to apply MAGIC to.      
    """

    flux_mesh = ScdMesh.fromFile(flux_mesh_filename)

    if ww_inp_mesh_filename != None:
        ww_inp_mesh = ScdMesh.fromFile(ww_inp_mesh_filename)

    else:
        ww_inp_mesh = None

    ww_mesh = magic(flux_mesh, totals_bool, null_value, tolerance, ww_inp_mesh)
    ww_mesh.scdset.save(output_mesh)
    print "\tWrote WW mesh file '{0}'".format(output_mesh)
示例#28
0
def main():
    """Method defines an option parser and handles command-line
    usage of this module.
    
    Notes
    -----
    Requires command line arguments to be passed - otherwise prints help
    information.
    """

    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    
    # Input and mesh file names
    parser.add_option("-p","--phtn",action="store",dest="phtnsrcfile", \
            default=False,help="The photon source strengths are read from" \
            "FILENAME.")
    parser.add_option("-m","--mesh",action="store",dest="meshfile", \
            default="",help="file to write source information to, or" \
            " file name for saving a modified mesh.")
    # Other options
    parser.add_option("-i","--isotope",action="store",dest="isotope", \
            default="TOTAL",help="The isotope string identifier or 'TOTAL'. "\
            "Default: %default")
    parser.add_option("-c","--coolingstep",action="store",dest="coolingstep", \
            default=0,help="The cooling step number or string identifier. " \
            "(0 is first cooling step)  Default: %default")
    parser.add_option("-r","--retag",action="store_true",dest="retag", \
            default=False,help="Option enables retagging of .h5m meshes. " \
            "Default: %default")
    parser.add_option("-t","--totals",action="store_true",dest="totals", \
            default=False,help="Option enables adding the total photon " \
            "source strength for all energy groups as a tag for each voxel. " \
            "Default: %default")

    (options, args) = parser.parse_args()

    # Open an ScdMesh and then call read_to_h5m
    try:
        mesh = ScdMesh.fromFile(options.meshfile)
    except ScdMeshError:
        mesh = iMesh.Mesh()
        mesh.load(options.meshfile)

    read_to_h5m( \
                options.phtnsrcfile, mesh, options.isotope, \
                options.coolingstep, options.retag, options.totals)

    if isinstance(mesh, ScdMesh):
        mesh.imesh.save(options.meshfile)
    else:
        mesh.save(options.meshfile)

    return 1
示例#29
0
文件: magic.py 项目: erelson/r2s-act
def magic(flux_h5m, ww_mesh, total_bool, null_value, output, output_mesh, tolerance):
    """Runs magic.py from as a module
    """
    flux_mesh = ScdMesh.fromFile(flux_h5m)

    ww_mesh, e_groups = magic_wwinp(flux_mesh, ww_mesh, total_bool, null_value, tolerance)

    if output_mesh != 'None':
        ww_mesh.scdset.save(output_mesh)

    write_wwinp(ww_mesh, e_groups, output)
示例#30
0
def main( arguments = None ) :

   #Instantiate option parser
    parser = OptionParser\
             (usage='%prog <meshtal_file> <normalization_factor> [options]')

    parser.add_option('-o', dest='mesh_output', default=None,\
                      help = 'Name of mesh output file, default=%default')
    parser.add_option('-n', dest='norm', default=None,
                      help = 'Normalization factor, default=%default')
    parser.add_option('-m', dest='smesh_filename', default=None,
                      help='Preexisting mesh on which to tag fluxes')
                         

    (opts, args) = parser.parse_args(arguments)
    
    #if len(args) != 2 :
     #   parser.error('\nNeed 1 argument: meshtal file')
    print "\n\nRunning read_meshtal.py"
    tally_numbers, tally_lines = find_tallies(args[1])
    print 'Number of tallies found: {0}\nTally number(s): {1}'\
                                     .format(len(tally_numbers), tally_numbers)

    # Parse input from options parser, generate default values
    if opts.norm :
        norm = opts.norm.split(',')
    else :
        norm=[1]*len(tally_numbers)

    if opts.mesh_output :
        mesh_output = opts.mesh_output.split(',')
    else:
        mesh_output=[]
        for n in range(0, len(tally_numbers)) :
            if len(tally_numbers) == 1 :
                mesh_output.append('flux_mesh.h5m')
            else :
                mesh_output.append('flux_mesh_tally{0}.h5m'.format(tally_numbers[n]))
    

    # Convert each tally to h5m and name accordingly
    for n in range(0,len(tally_numbers)) :
        print "\nNow parsing tally number {0}".format(tally_numbers[n])
        if opts.smesh_filename:
            alt_sm = ScdMesh.fromFile(opts.smesh_filename)
            sm = read_meshtal(args[1], tally_lines[n], float(norm[n]), smesh=alt_sm)
        else:
            sm = read_meshtal(args[1], tally_lines[n],float(norm[n]))

        sm.scdset.save(mesh_output[n])

        print "\tSaved tally {0} as {1}".format(tally_numbers[n], mesh_output[n])
    print '\nStructured mesh tagging complete\n\n'
示例#31
0
    def test_unequal_grid_size(self):
        """Test creating an mmgrid on a mesh with uneven grid spacing"""
        grid_side = [-3, 0, .1, .2, 3]
        sm = ScdMesh(*([grid_side] * 3))
        grid = mmgrid.mmGrid(sm)
        grid.generate(5)  #, True)

        for ijk, x in numpy.ndenumerate(grid.grid):
            self.assertAlmostEqual(sum(x['mats']),
                                   1.0,
                                   msg='Normality at ijk={0}:\n'
                                   '    sum({1}) = {2} != 1.0'.format(
                                       ijk, x['mats'], sum(x['mats'])))
示例#32
0
def test_magic_it_0_1_group():
    thisdir = os.path.dirname(__file__)
    flux_sm_filename = os.path.join(thisdir, "files_test_magic/iteration_0_flux_1_group.h5m")
    flux_sm = ScdMesh.fromFile(flux_sm_filename)
    expected_sm_filename = os.path.join(thisdir, "files_test_magic/iteration_0_magic_1_group.h5m")
    expected_sm = ScdMesh.fromFile(expected_sm_filename)

    totals_bool = False
    null_value = 1e-3
    tolerance = 0.2

    written_sm = magic.magic(flux_sm, totals_bool, null_value, tolerance)

    # verify weight window lower bounds are the same
    for x in range(0, 3):
        for y in range(0, 3):
            for z in range(0, 3):
                expected_voxel = expected_sm.getHex(x, y, z)
                expected = expected_sm.imesh.getTagHandle("ww_n_group_001")[expected_voxel]
                written_voxel = written_sm.getHex(x, y, z)
                written = written_sm.imesh.getTagHandle("ww_n_group_001")[written_voxel]
                assert_equal(written, expected)
示例#33
0
def test_magic_it_0_1_group():
    thisdir = os.path.dirname(__file__)
    flux_sm_filename = os.path.join(thisdir, 'files_test_magic/iteration_0_flux_1_group.h5m')
    flux_sm = ScdMesh.fromFile(flux_sm_filename)
    expected_sm_filename = os.path.join(thisdir, 'files_test_magic/iteration_0_magic_1_group.h5m')   
    expected_sm = ScdMesh.fromFile(expected_sm_filename)    

    totals_bool = False
    null_value = 1E-3
    tolerance = 0.2

    written_sm = magic.magic(flux_sm, totals_bool, null_value, tolerance)
    
    #verify weight window lower bounds are the same
    for x in range(0,3):
        for y in range(0,3):
            for z in range(0,3):
                expected_voxel = expected_sm.getHex(x,y,z)
                expected = expected_sm.imesh.getTagHandle('ww_n_group_001')[expected_voxel]
                written_voxel = written_sm.getHex(x,y,z)
                written = written_sm.imesh.getTagHandle('ww_n_group_001')[written_voxel]
                assert_equal(written, expected)
示例#34
0
    def test_mmgrid_generate(self):
        grid_side = [-5, -3.75, -2.5, -1.25, 0, 1.25, 2.5, 3.75, 5]
        sm = ScdMesh(*([grid_side] * 3))
        grid = mmgrid.mmGrid(sm)
        grid.generate(2, True)

        for ijk, x in numpy.ndenumerate(grid.grid):
            self.assertAlmostEqual(sum(x['mats']),
                                   1.0,
                                   msg='Normality at ijk={0}:\n'
                                   '    sum({1}) = {2} != 1.0'.format(
                                       ijk, x['mats'], sum(x['mats'])))

        grid.create_tags()
示例#35
0
    def test_rayframes(self):

        # a mesh with divisions at -1, 0, and 1 for all three dimensions
        sm = ScdMesh(*([(-1, 0, 1)] * 3))
        mg = mmgrid.mmGrid(sm)

        squares = [(-1, 0, -1, 0), (-1, 0, 0, 1), (0, 1, -1, 0), (0, 1, 0, 1)]

        ijks = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1]]

        for (ijk, ab), ab_test, ijk_test in itertools.izip_longest(
                mg._rayframe('x'), squares, ijks):
            self.assertEqual(ab, ab_test)
            self.assertEqual(ijk, ijk_test)
示例#36
0
    def test_hex_volume(self):

        sm = ScdMesh( [0,1,3], [-3,-2,0], [12,13,15] )
        self.assertEqual( sm.getHexVolume(0,0,0), 1 )
        self.assertEqual( sm.getHexVolume(1,0,0), 2 )
        self.assertEqual( sm.getHexVolume(0,1,0), 2 )
        self.assertEqual( sm.getHexVolume(1,1,0), 4 )
        self.assertEqual( sm.getHexVolume(1,1,1), 8 )

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

        for V, ijk in itertools.izip_longest(sm.iterateHexVolumes(), ijk_all):
            self.assertEqual( V, sm.getHexVolume(*ijk) )
示例#37
0
    def test_create_by_file(self):
        filename = os.path.join(os.path.dirname(__file__), 'h5m_files/grid543.h5m')
        sm = ScdMesh.fromFile(filename)
        self.assertEqual( 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

        self.assertEqual( sm.getDivisions('x'), range(1,6) )
        self.assertEqual( sm.getDivisions('y'), [1.0, 5.0, 10.0, 15.0] )
        self.assertEqual( sm.getDivisions('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_scdmesh_test/test_matFracs.h5m')
        self.assertRaises( ScdMeshError, ScdMesh.fromFile, filename2 )
示例#38
0
def handle_meshtal(meshtal_file, gen_mmgrid, datafile, isscd=True):
    """Read MCNP meshtal file and tag mesh

    Parameters
    ----------
    mesh : ScdMesh or iMesh.Mesh()
        Mesh object to be tagged.
    gen_mmgrid : boolean
        Whether to generate a new macromaterials grid
    datafile : string
        File/path to mesh file to be created/loaded/tagged.
    isscd : boolean
        If True, handle geometry as a structured mesh. Otherwise mesh is
        assumed to be unstructured and unstructured mesh tally results are
        assumed to exist on the mesh (Error raised if tag TALLY_TAG is missing).
    """
    if not isscd:  # is unstructured
        mesh = iMesh.Mesh()
        mesh.load(datafile)
        try:
            mesh.getTagHandle("TALLY_TAG")
        except iBase.TagNotFoundError as e:
            print "Missing tag 'TALLY_TAG' suggests that '{0}' is missing " "unstructured mesh tally information.".format(
                datafile
            )
            raise e

        return mesh

    print "Loading mesh tally file `{0}'".format(meshtal_file)
    tally_numbers, tally_lines = find_tallies(meshtal_file)
    # If not regenerating the mmGrid info, attempt to load existing datafile
    if gen_mmgrid == False:
        print "Attempting to re-use existing ScdMesh file '{0}'".format(datafile)
        alt_sm = ScdMesh.fromFile(datafile)  # Note: ray tracing is done later
        try:
            mesh = read_meshtal(meshtal_file, tally_lines[0], mesh=alt_sm)
        except ScdMeshError:
            print "ERROR:"
            print "Existing mesh in '{0}' does not match mesh in '{1}'. " "Set the 'gen_mmgrid' option to True in your 'r2s.cfg' " "file.".format(
                datafile, meshtal_file
            )

    else:
        print "Creating ScdMesh file '{0}' from scratch.".format(datafile)
        mesh = read_meshtal(meshtal_file, tally_lines[0])

    return mesh
示例#39
0
def handle_meshtal(meshtal_file, gen_mmgrid, datafile, isscd=True):
    """Read MCNP meshtal file and tag mesh

    Parameters
    ----------
    mesh : ScdMesh or iMesh.Mesh()
        Mesh object to be tagged.
    gen_mmgrid : boolean
        Whether to generate a new macromaterials grid
    datafile : string
        File/path to mesh file to be created/loaded/tagged.
    isscd : boolean
        If True, handle geometry as a structured mesh. Otherwise mesh is
        assumed to be unstructured and unstructured mesh tally results are
        assumed to exist on the mesh (Error raised if tag TALLY_TAG is missing).
    """
    if not isscd:  # is unstructured
        mesh = iMesh.Mesh()
        mesh.load(datafile)
        try:
            mesh.getTagHandle("TALLY_TAG")
        except iBase.TagNotFoundError as e:
            print "Missing tag 'TALLY_TAG' suggests that '{0}' is missing " \
                    "unstructured mesh tally information.".format(datafile)
            raise e

        return mesh

    print "Loading mesh tally file `{0}'".format(meshtal_file)
    tally_numbers, tally_lines = find_tallies(meshtal_file)
    # If not regenerating the mmGrid info, attempt to load existing datafile
    if gen_mmgrid == False:
        print "Attempting to re-use existing ScdMesh file '{0}'".format(
            datafile)
        alt_sm = ScdMesh.fromFile(datafile)  # Note: ray tracing is done later
        try:
            mesh = read_meshtal(meshtal_file, tally_lines[0], mesh=alt_sm)
        except ScdMeshError:
            print "ERROR:"
            print "Existing mesh in '{0}' does not match mesh in '{1}'. " \
                    "Set the 'gen_mmgrid' option to True in your 'r2s.cfg' " \
                    "file.".format(datafile, meshtal_file)

    else:
        print "Creating ScdMesh file '{0}' from scratch.".format(datafile)
        mesh = read_meshtal(meshtal_file, tally_lines[0])

    return mesh
示例#40
0
def main(arguments=None):

    parser = OptionParser\
             (usage='%prog structured_mesh x_value y_value z_value tag_name')

    #parser.add_option('-o', dest='fluxin_name', default='ALARAflux.in',\
    #    help='Name of ALARA fluxin output file, default=%default')

    (opts, args) = parser.parse_args(arguments)

    if len(args) != 6:
        parser.error\
        ( '\nNeed exactly 5 arguments: run with -h flag for usage' )

    #Load Structured mesh from file
    sm = ScdMesh.fromFile(args[1])

    print_value(sm, int(args[2]), int(args[3]), int(args[4]), args[5])
示例#41
0
def main(arguments=None):

    parser = OptionParser\
             (usage='%prog structured_mesh x_value y_value z_value tag_name')

    #parser.add_option('-o', dest='fluxin_name', default='ALARAflux.in',\
    #    help='Name of ALARA fluxin output file, default=%default')

    (opts, args) = parser.parse_args( arguments )

    if len(args) != 6 :
        parser.error\
        ( '\nNeed exactly 5 arguments: run with -h flag for usage' )

    
    #Load Structured mesh from file
    sm=ScdMesh.fromFile(args[1])

    print_value(sm, int(args[2]), int(args[3]), int(args[4]), args[5])
示例#42
0
def main():
    """Method defines an option parser and handles command-line
    usage of this module.

    Notes
    -----
    Requires command line arguments to be passed - otherwise prints help
    information.
    """

    usage = "Usage: %prog INPUTFILE [options]\n\n" \
            "INPUTFILE is the MCNP or DAG-MCNP input deck that is to be " \
            "modified. \nUse the -d option for DAG-MCNP files."
    parser = OptionParser(usage)
    
    # Output file name, and toggle for DAG-MCNP problems
    parser.add_option("-o","--output",action="store",dest="outputfile", \
            default="", help="Filename to write modified MCNP input to." \
            " Default is to append input filename with '_p'.")
    parser.add_option("-d","--dagmc",action="store_true",dest="dagmc", \
            default=False, help="Add flag to parse file like a DAG-MCNP file " \
            "(which has only title card and block 3 cards). Default: %default")
    parser.add_option("-m","--mesh",action="store",dest="fmesh", \
            default=None, help="Add meshtally (fmesh card), with mesh taken " \
            "from a .h5m or .vtk file that is supplied with this option.")

    (options, args) = parser.parse_args()
    
    if len(args):
        x = ModMCNPforPhotons(args[0], options.dagmc)

        x.read()
        x.convert()
        if options.fmesh != None:
            smesh = ScdMesh.fromFile(options.fmesh)
            x.add_fmesh_from_scdmesh(smesh)
        x.write_deck(options.outputfile)
    
    else:
        print "An input file must be specified as the first argument to use " \
                "this script.\nSee the -h option for more information."

    return 1
示例#43
0
def main():
    """ """    
    # Instatiate options parser
    parser = OptionParser\
             (usage='%prog <structured mesh> [options]')

    parser.add_option('-b', action='store_true', dest='backward_bool',\
        default=False, \
        help='Print to ALARA fluxin in fluxes in  decreasing energy. ' \
        'Default=%default')

    parser.add_option('-o', dest='fluxin_name', default='ALARAflux.in',\
        help='Name of ALARA fluxin output file, default=%default')

    (opts, args) = parser.parse_args()

    if len(args) != 2:
        parser.error\
        ( '\nNeed exactly 1 argument: structured mesh file' )

    # Load Structured mesh from file
    sm = ScdMesh.fromFile(args[1])

    write_alara_fluxin( opts.fluxin_name, sm, opts.backward_bool )
示例#44
0
class ScdMeshIterateTest(unittest.TestCase):

    def setUp(self):
        self.mesh = iMesh.Mesh()
        self.sm = ScdMesh( range(10,15), # i = 0,1,2,3
                           range(21,25), # j = 0,1,2
                           range(31,34), # k = 0,1
                           self.mesh )

        self.I = range(0,4)
        self.J = range(0,3)
        self.K = range(0,2)

    def test_bad_iterates(self):

        self.assertRaises( ScdMeshError,  self.sm.iterateHex, 'abc' )
        self.assertRaises( TypeError,  self.sm.iterateHex, 12 )
        self.assertRaises( ScdMeshError,  self.sm.iterateHex, 'xxyz' )
        self.assertRaises( ScdMeshError,  self.sm.iterateHex, 'yyx' )
        self.assertRaises( ScdMeshError,  self.sm.iterateHex, 'xyz',z=[0,1,2] )

    def test_iterate_3d(self):
        
        # use izip_longest in the lockstep iterations below; this will catch any
        # situations where one iterator turns out to be longer than expected.
        izip = itertools.izip_longest

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

        print "testing zyx"

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

        print "testing xyz"

        all_indices_zyx = itertools.product( self.I, self.J, self.K )
        # Test the xyz order, the default from original mmGridGen
        for ijk_index, sm_x in izip( all_indices_zyx, 
                                     self.sm.iterateHex('xyz') ):
            self.assertEqual( self.sm.getHex(*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 ):
            print 'testing',order
            all_indices = itertools.product(*args)
            for ijk_index, sm_x in izip( tuple_sort(all_indices, order),
                                         self.sm.iterateHex(order,**kw) ):
                self.assertEqual(self.sm.getHex(*ijk_index), sm_x)

        test_order( 'yxz', self.I, self.J, self.K )
        test_order( 'yzx', self.I, self.J, self.K )
        test_order( 'xzy', self.I, self.J, self.K )
        test_order( 'zxy', self.I, self.J, self.K )

        # Specify z=[1] to iterator
        test_order( 'xyz', self.I, self.J, [1], z=[1] )
        # Specify y=2 to iterator
        test_order( 'zyx', self.I, [2], self.K, y=2 )
        # specify x and y both to iterator
        test_order( 'yzx', [1,2,3],self.J[:-1], self.K, y=self.J[:-1], x=[1,2,3] )

    def test_iterate_2d(self):
        def test_order( iter1, iter2 ):
            for i1, i2 in itertools.izip_longest( iter1, iter2 ):
                self.assertEqual( i1, i2 )

        test_order( self.sm.iterateHex('yx'), self.sm.iterateHex('zyx', z=[0] ) )
        test_order( self.sm.iterateHex('yx',z=1), self.sm.iterateHex('zyx',z=[1]) )
        test_order( self.sm.iterateHex('yx',z=1), self.sm.iterateHex('yzx',z=[1]) )
        test_order( self.sm.iterateHex('zy',x=[3]), self.sm.iterateHex('zxy',x=3) )

        # Cannot iterate over multiple z's without specifing z order
        self.assertRaises( ScdMeshError, self.sm.iterateHex, 'yx', z=[0,1] )

    def test_iterate_1d(self):
        
        def test_equal( ijk_list, miter ):
            for ijk, i in itertools.izip_longest( ijk_list, miter ):
                self.assertEqual( self.sm.getHex(*ijk), i )

        test_equal( [[0,0,0],[0,0,1]], 
                    self.sm.iterateHex('z') )

        test_equal( [[0,1,1],[0,2,1]],
                    self.sm.iterateHex('y', y=[1,2], z=1) )

        test_equal( [[2,0,0],[2,1,0],[2,2,0]],
                    self.sm.iterateHex('y', x=2) ) 
        test_equal( [[0,0,0],[1,0,0],[2,0,0]], 
            self.sm.iterateHex('x', x=[0,1,2]) )

    def test_vtx_iterator(self):
        
        #use vanilla izip as we'll test using non-equal-length iterators
        izip = itertools.izip

        sm = self.sm
        it = sm.scdset.iterate(iBase.Type.vertex, iMesh.Topology.point)

        # test the default order
        for (it_x, sm_x) in itertools.izip_longest( it, sm.iterateVtx('zyx') ):
            self.assertEqual(it_x,sm_x)

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

        it.reset()
        for (it_x, sm_x) in izip( it, sm.iterateVtx('yx',z=sm.dims[2])):
            self.assertEqual(it_x,sm_x)

        it.reset()
        for (it_x, sm_x) in izip( it, sm.iterateVtx('x')):
            self.assertEqual(it_x,sm_x)
示例#45
0
 def setUp(self):
     self.sm = ScdMesh.fromFile(meshfile)
示例#46
0
 def test_create_by_set(self):
     a =  self.mesh.createStructuredMesh( [0,0,0,1,1,1], 
                                          i=[1,2], j=[1,2], k=[1,2], 
                                          create_set=True )
     sm = ScdMesh.fromEntSet( self.mesh, a )
     self.assertEqual( sm.dims, (0,0,0,1,1,1) )
示例#47
0
 def test_create(self):
     sm = ScdMesh( range(1,5), range(1,4), range(1,3), self.mesh )
     self.assertEqual( sm.dims, (0,0,0,3,2,1) )
示例#48
0
 def test_mmgrid_create(self):
     sm = ScdMesh(*([(-1, 0, 1)] * 3))
     grid = mmgrid.mmGrid(sm)
     self.assertEqual(grid.grid.shape, (2, 2, 2))
     self.assertEqual(grid.grid[0, 0, 0]['mats'].shape, (3, ))
     self.assertEqual(grid.grid[0, 0, 0]['errs'].shape, (3, ))
示例#49
0
 def setUp(self):
     os.system("cp " + meshfile_orig + " " + meshfile)
     self.sm = ScdMesh.fromFile(meshfile)
     read_alara_phtn.read_to_h5m(inputfile, self.sm)
示例#50
0
 def setUp(self):
     os.system("cp " + meshfile_orig + " " + meshfile)
     self.sm = ScdMesh.fromFile(meshfile)