Ejemplo n.º 1
0
    def fromFile(cls, filename, imesh=None):
        """Load structured meshes from a file

        Returns one strutured mesh if the file contains one mesh, or a list if
        the file contains multiple meshes.
        """
        retlist = []
        if not imesh:
            imesh = iMesh.Mesh()
        imesh.rootSet.load(filename)
        for eset in imesh.rootSet.getEntSets():
            try:
                bdtag = imesh.getTagHandle('BOX_DIMS')
                bdtag[eset]
                retlist.append(
                    cls(None, None, None, imesh, _scdset=eset, bdtag=bdtag))
            except iBase.TagNotFoundError:
                pass
        if not retlist:
            raise ScdMeshError('Found no structured meshes in file ' +
                               filename)
        if len(retlist) == 1:
            return retlist[0]
        else:
            return retlist
Ejemplo n.º 2
0
def create_mesh(a, mesh_name):  #a is the name of the boundaries_array
    mesh = iMesh.Mesh()

    #creating a list of vertices from array of mesh boundaries
    #with z values changing fastest, then x,then y

    vertex_list = []
    x_div = len(a[0])
    y_div = len(a[1])
    z_div = len(a[2])
    verts = [0] * len(a[0]) * len(a[1]) * len(a[2])
    count = 0

    for x in range(0, x_div):
        for y in range(0, y_div):
            for z in range(0, z_div):
                verts[count] = mesh.createVtx([a[0][x], a[1][y], a[2][z]])
                count += 1

    #grouping together vertices in cannonical order to create cubes

    for x in range(0, x_div - 1):
        for y in range(0, y_div - 1):
            for z in range(0, z_div - 1):
                vert_set = [verts[z + y*z_div + x*z_div*y_div],\
                            verts[z + y*z_div + (x+1)*z_div*y_div],\
                            verts[z + y*z_div + (x+1)*z_div*y_div + z_div],\
                            verts[z + y*z_div + x*z_div*y_div + z_div],\
                            verts[z + y*z_div + x*z_div*y_div +1 ],\
                            verts[z + y*z_div + (x+1)*z_div*y_div + 1 ],\
                            verts[z + y*z_div + (x+1)*z_div*y_div + z_div +1],\
                            verts[z + y*z_div + x*z_div*y_div + z_div + 1]]
                cube, status = mesh.createEnt(iMesh.Topology.hexahedron,
                                              vert_set)
    mesh.save(mesh_name)
Ejemplo n.º 3
0
def main(filename, tagstring, outputname=None):
    """Load mesh
    """
    tagstring = tagstring.lower()

    if not outputname: outputname = filename

    mesh = iMesh.Mesh()
    print "Attempting to load {0}".format(filename)
    #try: #This should work fine for mesh files containing an ScdMesh.
    mesh.load(filename)
    print "Successfully loaded mesh."
    #except iBase.NotSupportedError:
    #    sm = ScdMesh.fromFile(filename)
    #    mesh = ScdMesh.imesh
    #    print "Successfully loaded mesh from an ScdMesh."

    # Grab first voxel entity on mesh, from which we get voxel-level tag handles
    for x in mesh.iterate(iBase.Type.region, iMesh.Topology.all):
        break

    handles = mesh.getAllTags(x)

    for handle in handles:
        tagname = handle.name.lower()
        if re.findall(tagstring, tagname):
            print "Deleting tag {0}".format(tagname)
            mesh.destroyTag(handle, force=True)

    print "Saving mesh."
    mesh.save(filename)
Ejemplo n.º 4
0
    def voxel_volumes_from_h5m(self, inputfile):
        """Read volumes of voxels from tags in a moab mesh.
        
        ACTION: Method reads tags with voxel volumes from an h5m
        file and stores the information in 
        To do this, we generate self.meshprobs and call gen_gammas_file().
        REQUIRES: the .h5m moab mesh must have 

        RECEIVES: The file (a .h5m moab file) containing the mesh of interest.
        TODO:
        """

        #~ NOTE: The below code is a placeholder from 'gen_gammas_from_h5m_file()'

        mesh = iMesh.Mesh()
        mesh.load(inputfile)

        try:
            group = mesh.getTagHandle("VOLUMES")
        except:
            print "ERROR: "

            return 0

        voxels = mesh.getEntities(iBase.Type.region)
        numvoxels = len(voxels)

        return 1
Ejemplo n.º 5
0
def get_tag_values(filename):
    mesh = iMesh.Mesh()
    mesh.load(filename)
    # get all entities
    ents = mesh.getEntities(iBase.Type.all, iMesh.Topology.triangle)
    # get mesh set
    mesh_sets = mesh.getEntSets()
    # tag_values = []  # list of tag values
    tag_values = []
    found_all_tags = 0
    for s in mesh_sets:
        if found_all_tags == 1:
            break
        # get all the tags
        tags = mesh.getAllTags(s)
        # loop over the tags checking for name
        for t in tags:
            # look for NAME tag
            if t.name == 'NAME':
                # the handle is the tag name
                t_handle = mesh.getTagHandle(t.name)
                # get the data for the tag, with taghandle in element i
                tag = t_handle[s]
                tag_to_script(tag, tag_values)
                # last tag we are done
                if any('impl_complement' in s for s in tag_values):
                    found_all_tags = 1
    print('The groups found in the h5m file are: ')
    print tag_values
    return tag_values
Ejemplo n.º 6
0
def tag_fluxes_preexisting(array, j, k, norm, meshtal_type, mesh_input,
                           mesh_output):
    if meshtal_type == 'n':
        print 'Tagging user supplied mesh with neutron fluxes'
    if meshtal_type == 'p':
        print 'Tagging user supplied mesh with photon fluxes'
    mesh = iMesh.Mesh()
    mesh.load(mesh_input)
    voxels = mesh.getEntities(iBase.Type.region)
    column_flux = []
    column_error = []
    count = 0
    for group_ID in range(1, k + 1):  #need to add one for total fluxes
        if group_ID != k:
            tag_flux=mesh.createTag\
            ('{0}_group_{1:03d}'.format(meshtal_type, group_ID),1,float)
            tag_error=mesh.createTag\
            ('{0}_group_{1:03d}_error'.format(meshtal_type, group_ID),1,float)
        if group_ID == k:
            tag_flux = mesh.createTag(meshtal_type + '_group_total', 1, float)
            tag_error = mesh.createTag(meshtal_type + '_group_total_error', 1,
                                       float)
        for x in range(0, j):
            array_index = x + j * count
            column_flux.append(array[array_index][4] * norm)
            column_error.append(array[array_index][5])
        count = count + 1
        tag_flux[voxels] = column_flux
        tag_error[voxels] = column_error
        column_flux = []
        column_error = []
    mesh.save(mesh_output)
    print 'User supplied mesh successfully tagged'
Ejemplo n.º 7
0
def test_create_by_set():
    mesh = iMesh.Mesh()
    a = mesh.createStructuredMesh([0, 0, 0, 1, 1, 1],
                                  i=[1, 2],
                                  j=[1, 2],
                                  k=[1, 2],
                                  create_set=True)
    sm = Mesh(mesh=mesh, structured_set=a, structured=True)
    assert_true(all(sm.dims == [0, 0, 0, 1, 1, 1]))
Ejemplo n.º 8
0
def main():
    (options, args) = parser()
    alara_input = open(options.output, 'w')
    mesh = iMesh.Mesh()
    print "Read " + args[0]
    mesh.load(args[0])
    moab2alara(mesh, alara_input, options.round, options.volume)
    print "Wrote " + options.output
    return
Ejemplo n.º 9
0
    def test_convert(self):
        m = iMesh.Mesh()
        sm = sc_convert.convert_mesh(self.mesh, self.mesh.rootSet, m)
        self.assertEqual(sm.dims, (0, 0, 0, 8, 8, 8))
        for L in 'xyz':
            self.assertEqual(sm.getDivisions(L), self.reference)

        # also test that converting into the same iMesh instance doesn't fault
        sm2 = sc_convert.convert_mesh(self.mesh, self.mesh.rootSet, self.mesh)
Ejemplo n.º 10
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)
Ejemplo n.º 11
0
def main():
    op = optparse.OptionParser( 
            usage='%prog [options] filename', 
            description='A tool to convert old structured meshes to ScdMeshes.'
                        '  Eligible inputs include meshes created by mmGridGen'
                        ' and FluxParse.py') 
    op.add_option( '-o', default='converted_scdmesh.h5m',
                   help='Output file name, default: %default',
                   dest='outputfile' )

    opts, args = op.parse_args()
    if len(args) != 1:
        op.error( 'Need exactly one argument: filename to load' )

    mesh = iMesh.Mesh()
    mesh.rootSet.load( args[0] )

    mesh2 = iMesh.Mesh()
    sm = convert_mesh( mesh, mesh.rootSet, mesh2 )
    sm.scdset.save( opts.outputfile )
Ejemplo n.º 12
0
 def test_tags(self):
     m = iMesh.Mesh()
     sm = sc_convert.convert_mesh(self.mesh, self.mesh.rootSet, m)
     for tname in ["FRACTIONS", "ERRORS"]:
         t1 = self.mesh.getTagHandle(tname)
         t2 = sm.imesh.getTagHandle(tname)
         for (e1, e2) in itertools.izip_longest(
                 self.mesh.iterate(iBase.Type.region,
                                   iMesh.Topology.hexahedron),
                 sm.iterateHex('xyz')):
             self.assertTrue(all(t1[e1] == t2[e2]))
     for tname in ["GRID_DIMS", "MATS"]:  # tags on root set
         t1 = self.mesh.getTagHandle(tname)
         t2 = sm.imesh.getTagHandle(tname)
         self.assertTrue(all(t1[self.mesh.rootSet] == t2[sm.scdset]))
Ejemplo n.º 13
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
Ejemplo n.º 14
0
def get_centers_and_vals(filename, outfile, valtagname, errtagname, plotnum, \
        header):
    """
    """
    imesh = iMesh.Mesh()

    imesh.load(filename)

    cnt = 0

    taltag = imesh.getTagHandle(valtagname)
    errtag = imesh.getTagHandle(errtagname)

    with open(outfile, 'w') as fw:

        # write metadata/comment line
        if header:
            fw.write("# File created: {0}  From: {1}\n".format( \
                    datetime.now().strftime("%D %H:%M"), filename))
            fw.write("# {0:<12}\t{1:<12}\t{2:<12}\t{3:<12}\t{4:<12}\n".format( \
                    "x", "y", "z", "tally", "error"))

        #
        for tet in imesh.iterate(iBase.Type.region,
                                 iMesh.Topology.tetrahedron):
            vtxs = imesh.getVtxCoords(imesh.getEntAdj(tet, iBase.Type.vertex))
            # calculate centroid
            centroid = list()
            for idx in xrange(3):
                centroid.append(sum([vtx[idx] for vtx in vtxs]) / 4.0)

            # Write output
            fw.write("{0:<12}\t{1:<12}\t{2:<12}\t{3:<12}\t{4:<12}\n".format( \
                    centroid[0], centroid[1], centroid[2], \
                    taltag[tet], errtag[tet]))

            cnt += 1

            # Optionally plot points of a tet for verification
            if cnt == plotnum:
                print "Example centroid...\n"
                print "For tet with coords\n{0}\n".format(vtxs)
                print "We find the centroid to be:\n{0}\n".format(centroid)
                plot(vtxs, centroid)

    print "{0} tetrahedrons found\nTet center coordinates and tally value/" \
            "errors written to: {1}".format(cnt, outfile)
Ejemplo n.º 15
0
    def __init__(self, x_points, y_points, z_points, imesh=None, **kw):
        """Construct a ScdMesh from given x, y, and z coordinates.

        Parameters
        ----------
        x_points, y_points, z_points : list of floats
            List of points.
            The i,j,k extents of the structured mesh will be numbered from 0.
        imesh : iMesh.Mesh object
            Parameter can be used to designate an iMesh instance
            in which to place the mesh; if None, a new instance will be 
            created.
        keyword arguments:
            bdtag : iMesh.Tag handle
                if the BOX_DIMS tag has already been looked up, it may
                be passed thus
            _scdset : iMesh.EntitySet handle (?)
                an existing scdset to use; clients should use 
                fromEntSet() instead of using this parameter.
        """
        if imesh:
            self.imesh = imesh
        else:
            self.imesh = iMesh.Mesh()
        if x_points is None and y_points is None and z_points is None:
            self.scdset = kw['_scdset']
        else:
            extents = [0, 0, 0]
            extents.extend(
                [len(x) - 1 for x in [x_points, y_points, z_points]])
            self.scdset = self.imesh.createStructuredMesh(extents,
                                                          i=x_points,
                                                          j=y_points,
                                                          k=z_points,
                                                          create_set=True)
        bdtag = kw.get('bdtag', self.imesh.getTagHandle('BOX_DIMS'))
        self.dims = ScdMesh.extents_tuple(*bdtag[self.scdset])
        vdims_incr = list(self.dims[0:3]) + [x + 1 for x in self.dims[3:6]]
        self.vdims = ScdMesh.extents_tuple(*vdims_incr)
        # access iterators for hexes and vertices; used by getHex()/getVtx()
        self.hexit = self.scdset.iterate(iBase.Type.region,
                                         iMesh.Topology.hexahedron)
        self.vtxit = self.scdset.iterate(iBase.Type.vertex,
                                         iMesh.Topology.point)
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
def load_mesh(filename):
    mesh = iMesh.Mesh()  # imesh instance
    mesh.load(filename)
    num_el = mesh.getNumOfType(iBase.Type.all)
    return num_el, mesh
Ejemplo n.º 18
0
 def setUp(self):
     self.mesh = iMesh.Mesh()
Ejemplo n.º 19
0
def loadmesh(filename):
    mesh = iMesh.Mesh()
    mesh.load(filename)
    cells = list()
    surfs = dict()
    surfcount = 0
    cellcount = 0

    # iterate over cells, creating surface numbers for each triangle
    for i in mesh.iterate(iBase.Type.region, iMesh.Topology.tetrahedron):

        cellcount += 1

        vertices = mesh.getEntAdj(i, iBase.Type.vertex)
        cell = list()

        # for each triangle in this tet
        for verts in [vertices.take(i) for i in tet_connect]:

            ent_idx = [(e, i) for i, e in enumerate(verts)]
            ent_idx = sorted(ent_idx, key=repr)

            # vkey: a tuple of the triangle's 3 vertices in sorted order by EntityHandle.
            #       This is used as a unique ID for the surface associated with these vertices.
            vkey = tuple([e for e, i in ent_idx])

            # idxs: an index map of the vkey such that vkey.take(idxs) produces the list of
            #       vertices in the same order as they appear in this triangle.
            #       This is used to determine the triangle's outward-facing normal relative to
            #       a cell that contains it.
            idxs = tuple([i for e, i in ent_idx])

            if vkey not in surfs:
                surfcount += 1
                surfs[vkey] = [surfcount, 1]
            else:
                surfs[vkey][1] += 1
            cell.append((vkey, idxs))

        cells.append((cellcount, cell))

    # iterate over surfaces, pulling out vertex data and setting up surfs_out
    surfs_out = list()
    for (vkey, (surf_idx, count)) in surfs.iteritems():
        coords = mesh.getVtxCoords(vkey)
        surfs_out.append([surf_idx, coords])

    # sort surfaces according to surface ID; this allows surfs_out to be indexed by (surf_idx-1)
    # in the loop below
    surfs_out.sort(key=operator.itemgetter(0))

    cells_out = list()
    complement_slist = list()

    epsilon = 1e-12

    # iterate over cells again, determining surface sense for each triangle
    for (cellid, cell) in cells:

        slist = list()

        for (vkey, idxs) in cell:

            surf_idx, scount = surfs[vkey]
            _, coords = surfs_out[surf_idx - 1]
            p1, p2, p3 = coords.take(idxs, axis=0)

            # unit normal of triangle facing out of cell
            normal = numpy.cross(p2 - p1, p3 - p1)
            normal = normal / la.norm(normal)

            # vertex furthest from origin
            furthest = max((p1, p2, p3), key=la.norm)
            # distance from origin to triangle's plane
            D = furthest.dot(normal)

            sense = 0

            if (D < -epsilon):
                sense = 1
            elif (D > epsilon):
                sense = -1
            else:
                # MCNP sense rules for planes that intercept the origin:
                # if D=0, the point (0,0,infinity) has positive sense
                # if the plane intercepts that point, then (0,infinity,0) has positive sense
                # if the plane intercepts both points, then (infinity,0,0) has positive sense
                idx = 2
                while sense == 0 and idx >= 0:
                    # Use this dimension if normal[idx] is not zero.
                    # Note that -0 is not uncommon for axis-aligned planes
                    if abs(normal[idx]) > epsilon:
                        sense = -int(math.copysign(1, normal[idx]))
                    idx -= 1

            if sense == 0:
                print "Error: could not determine the sense of surface", surf_idx
                # The value 0 will be appended to the slist (mcnp5 will choke)

            slist.append(surf_idx * sense)

            # check if surface has only one reference; if so, add it to the complement cell
            if scount == 1:
                complement_slist.append(str(surf_idx * -sense))
                complement_slist.append(':')

        slist.append('imp:n=1')
        cells_out.append((cellid, slist))

    complement_slist.pop()  # remove the last ':'
    complement_slist.append('imp:n=0 $ complement vol ')
    cells_out.append((cellid + 1, complement_slist))

    return (cells_out, surfs_out)
Ejemplo n.º 20
0
def test_unstructured_mesh_from_instance():
    filename = os.path.join(os.path.dirname(__file__),
                            "files_mesh_test/unstr.h5m")
    mesh = iMesh.Mesh()
    mesh.load(filename)
    sm = Mesh(mesh=mesh)
Ejemplo n.º 21
0
    print 'Tagging mesh with material volume fractions'
    count = 0
    mats = mesh.getTagHandle("MATS")
    dims = mesh.getTagHandle("GRID_DIMS")
    fracs = mesh.getTagHandle("FRACTIONS")
    matID = list(mats[mesh.rootSet])
    print '\tMaterials order: ' + str(matID)
    dimID = list(dims[mesh.rootSet])
    print '\tNumber of xyz intervals: ' + str(dimID) + '\n'
    voxels = mesh.getEntities(iBase.Type.region)

    for num in matID:
        column = []
        tag = mesh.createTag('mat_' + str(num), 1, float)

        for i in fracs[voxels]:
            column.append(i[count])
        tag[voxels] = column
        count = count + 1
    return


if __name__ == '__main__':
    (options, args) = parser()
    mesh = iMesh.Mesh()
    print "Read " + args[0]
    mesh.load(args[0])
    TagMats(mesh)
    mesh.save(options.output)
    print "Wrote " + options.output
Ejemplo n.º 22
0
    def gen_phtn_src_h5m_tags(self, inputfile, outfile="", retag=False):
        """Tag an h5m mesh with the phtn_src information (deprecated)
        
        ACTION: Method adds tag with photon source strengths from ALARA to a
        moab mesh.
        If there are photon energy group tags with numbers higher than those
        added and retagging is enabled, these tags are removed.
        REQUIRES:

        RECEIVES: The file (a .h5m moab file) containing the mesh of interest.
        An output file which is fun
        TODO:
        Check to make sure the correct number of energy groups were added as tags.
        """

        try:
            nmesh = len(self.meshstrengths)
        except:
            print "ERROR: isotope_source_strengths needs to be called before " \
                    "gen_phtn_src_h5m_tags"
            return 0

        if outfile == "": outfile = inputfile

        # pyTaps stuff starts here
        mesh = iMesh.Mesh()
        mesh.load(inputfile)

        num_erg_groups = 42  # must be an integer

        # We grab the list of mesh entity objects
        voxels = mesh.getEntities(iBase.Type.region)

        # We need to create the list of photon probabilities for each mesh cell.
        # Because this list can be quite large, we will do this element-by-element.

        # for grp, prob in enumerate(self.meshprobs[0]):
        for grp in xrange(len(self.meshprobs[0])):
            try:
                tag = mesh.createTag( \
                        "phtn_src_group_{0:03d}".format(grp+1), 1, float)
            except:
                if retag:
                    tag = mesh.getTagHandle(
                        "phtn_src_group_{0:03d}".format(grp + 1))
                else:
                    print "ERROR: The tag phtn_src_group_{0:03d}".format(grp+1), \
                            "already exists in the file", inputfile, \
                            "\nNow exiting this method."
                    return 0

            # we give each voxel to the tag dictionary, and assign the tag the value
            # stored in self.meshprobs
            for cnt, vox in enumerate(voxels):
                # we create tag, which is a dictionary, and give the dictionary
                tag[vox] = float(self.meshprobs[cnt][grp])

        #~ some caution needed with making sure 'grp' remains as is at end of
        #~  above for loop
        grp += 1

        # We get of tags corresponding with higher energy groups here.
        if retag:
            while grp:
                try:
                    tag = mesh.getTagHandle(
                        "phtn_src_group_{0:03d}".format(grp + 1))
                    mesh.destroyTag(tag, force=True)
                    grp += 1
                except:
                    grp = 0

        mesh.save(outfile)

        print "The file '{0}' was created successfully".format(outfile)

        return 1
Ejemplo n.º 23
0
    def gen_gammas_file_from_h5m(self, meshform, inputfile, outfile="gammas"):
        """Generate gammas file using information from tags on a moab mesh.
        
        ACTION: Method reads tags with photon source strengths from an h5m
        file and generates the gammas file for the modified KIT source.f90 routine
        To do this, we generate self.meshprobs and call gen_gammas_file().
        REQUIRES: the .h5m moab mesh must have photon source strength tags of the
        form "phtn_src_group_###"
        Will read photon energy bin boundary values if the root set has the tag 
        PHOT_ERG (a list of floats)

        RECEIVES: The file (a moab mesh file) containing the mesh of interest.
        An output file name for the 'gammas' file.
        TODO:
        """

        mesh = iMesh.Mesh()
        mesh.load(inputfile)

        try:
            group = mesh.getTagHandle("phtn_src_group_001")
        except:
            print "ERROR: The file", inputfile, "does not contain tags of the " \
                    "form 'phtn_src_group_#'"
            return 0

        voxels = mesh.getEntities(iBase.Type.region)
        numvoxels = len(voxels)

        #Need to create: self.meshstrengths, self.meshprobs
        self.meshprobs = list(
        )  # of lists of strings; each string is a source strength
        self.meshstrengths = list(
        )  # of floats; each float is the total source
        #  strength of a voxel at the chosen cooling step

        # Initialize list to first erg bin source strength value for each voxel
        self.meshstrengths = [float(x) for x in group[voxels]]

        numergbins = 0

        # We now go through all photon energy groups and add the individual bins
        #  to get the total source strength in each voxel
        for i in xrange(2, 1000):  #~ Arbitrary: we look for up to 1000 groups
            try:
                group = mesh.getTagHandle("phtn_src_group_{0:03d}".format(i))
                for cnt, vox in enumerate(voxels):
                    self.meshstrengths[cnt] += float(group[vox])
            except iBase.TagNotFoundError:
                numergbins = i - 1
                break

        print "Found tags for for {0} photon energy bins.".format(numergbins)

        # We calcualte the normalization factor as the average total source
        #  strength in each mesh cell divided by the number of mesh cells
        #  with non-zero source strength.
        # This applies ONLY for uniform voxel size meshing.
        numactivatedcells = 0
        for val in self.meshstrengths:
            if val > 0:
                numactivatedcells += 1
                # volsourcetot += volcell #~
        print "The number of activated voxels and total number of voxels is " \
                "{0}/{1}".format(numactivatedcells, len(self.meshstrengths))
        norm = sum(self.meshstrengths) / numactivatedcells

        # We now look for the tags with the energy bin boundary values
        try:
            phtn_ergs = mesh.getTagHandle("PHTN_BINS")
            myergbins = phtn_ergs[
                mesh.rootSet]  #UNTESTED... does this need list() around it?
            print "NOTE: photon energy bins were found in the .h5m mesh and added to " \
                    "'{0}'. The modified mcnp5/source.f90 looks for a file caled " \
                    "'gammas_ener'".format(outfile)
        except:  # if there is no PHTN_BINS tag, then we send an empty string in its place
            myergbins = ""


#        self.gen_gammas_file(meshform, outfile, myergbins)

        fw = self._gen_gammas_header(meshform, outfile, myergbins)

        for voxel in voxels:
            writestring = ""
            binval = 0.0
            for i in xrange(1, numergbins + 1):
                binval += float(mesh.getTagHandle( \
                        "phtn_src_group_{0:03d}".format(i))[voxel])
                writestring += "{0:<12.5E}".format(binval / norm)
            fw.write(writestring + "\n")

        fw.close()

        return 1
Ejemplo n.º 24
0
def handle_phtn_data(datafile, phtn_src, opt_isotope, opt_cooling,  \
        opt_sampling, opt_bias, opt_cumulative, cust_ergbins, 
        resample, uni_resamp_all, gammas="gammas"):
    """Loads phtn_src data, tags this to mesh, and generates 'gammas' file.

    Parameters
    ----------
    datafile : string
        Path to structured mesh file (e.g. .h5m file)
    phtn_src : string
        Path to phtn_src file
    opt_isotope : string
        The isotope identifier as listed in phtn_src file
    opt_cooling : int or string
        The cooling step, either as a numeric index (from 0) or a string
        identifier as listed in phtn_src file
    opt_sampling : ['v', 'u']
        Type of sampling to generate the 'gammas' file for; v=voxel; u=uniform
    opt_bias : boolean
        If true, look for bias values on the mesh and include them in 'gammas'
    opt_cumulative : boolean
        If true, write energy bins' relative probabilities cumulatively
    cust_ergbins : boolean
        If true, look for custom energy bins on the mesh and include them in
        'gammas'
    resample : boolean
        If true, 'r' flag is added to gammas, and resampling of particles 
        starting in void regions of voxels is enabled.
    uni_resamp_all : boolean
        If true, 'a' flag is added to gammas, and particles starting in void
        regions of voxels, during uniform sampling, are resampled over the
        entire problem, rather than resampling just the voxel.  This has the
        potential to result in an unfair game.
    gammas : string (optional)
        File name for 'gammas' file. Defaults to 'gammas'.

    Returns
    -------
    mesh : ScdMesh object or iMesh.Mesh object
        MOAB mesh object

    Notes
    -----
    Only creates gammas file if mesh is an ScdMesh.
    """
    print "Loading step one data file '{0}'".format(datafile)
    try:
        mesh = ScdMesh.fromFile(datafile)
    except ScdMeshError:
        mesh = iMesh.Mesh()
        mesh.load(datafile)

    # Tagging mesh
    print "Reading ALARA photon source '{0}'".format(phtn_src)
    read_alara_phtn.read_to_h5m(phtn_src, mesh, isotope=opt_isotope, \
            coolingstep=opt_cooling, retag=True, totals=True)

    print "Saving photon source information to '{0}'".format(datafile)
    if isinstance(mesh, ScdMesh):
        mesh.imesh.save(datafile)

        with open(phtn_src, 'r') as fr:
            try:
                coolingstepstring = read_alara_phtn.get_cooling_step_name( \
                    opt_cooling, fr)[0]
            except ValueError:
                coolingstepstring = opt_cooling

        print "Writing gammas file"
        write_gammas.gen_gammas_file_from_h5m(mesh, outfile=gammas, \
                sampling=opt_sampling, do_bias=opt_bias, \
                cumulative=opt_cumulative, cust_ergbins=cust_ergbins, \
                resample=resample, uni_resamp_all=uni_resamp_all, \
                coolingstep=coolingstepstring, isotope=opt_isotope)
    else:
        voxels = list(mesh.iterate(iBase.Type.region, iMesh.Topology.all))
        write_gammas.calc_total_source_strength(mesh, voxels)
        mesh.save(datafile)

    print "\n"

    return mesh
Ejemplo n.º 25
0
 def setUp(self):
     self.mesh = iMesh.Mesh()
     self.mesh.rootSet.load(
         os.path.join(os.path.dirname(__file__), 'test_matFracs.h5m'))
     # each dimension is equal in this test file and has the following divisions
     self.reference = [-5, -3.75, -2.5, -1.25, 0, 1.25, 2.5, 3.75, 5]