Esempio n. 1
0
def cell_material_assignments():
    from pyne import dagmc
    path = os.path.join(os.path.dirname(__file__), 'files_test_dagmc',
                        'three_blocks.h5m')
    c = dagmc.cell_material_assignments(path)
    r = []
    r.append(c[1] == 'mat:m1/rho:1.0')
    r.append(c[2] == 'mat:m2')
    r.append(c[3] == 'mat:m2/rho:3.0')
    r.append(c[6] == 'mat:graveyard')
    return np.all(r)
Esempio n. 2
0
def _get_zones(mesh, hdf5, bounds, num_rays, grid, dg, mat_assigns,
               unique_names):
    """Get the minimum zone definitions for the geometry."""

    # Discretize the geometry and get cell fractions
    if dg is None:
        if not HAVE_DAGMC:
            raise RuntimeError("DAGMC is not available."
                               "Unable to discretize the geometry.")
        else:
            dagmc.load(hdf5)
            dg = dagmc.discretize_geom(mesh, num_rays=num_rays, grid=grid)

    # Reorganize dictionary of each voxel's info with the key the voxel number
    # and values of cell and volume fraction
    voxel = {}
    for i in dg:
        idx = i[0]  # voxel number
        if idx not in voxel:
            voxel[idx] = {}
            voxel[idx]["cell"] = []
            voxel[idx]["vol_frac"] = []
        voxel[idx]["cell"].append(i[1])
        voxel[idx]["vol_frac"].append(i[2])

    # get material to cell assignments
    if mat_assigns is None:
        if not HAVE_DAGMC:
            raise RuntimeError("DAGMC is not available."
                               "Unable to get cell material assignments.")
        else:
            mat_assigns = dagmc.cell_material_assignments(hdf5)

    # Replace the names in the material assignments with unique names
    temp = {}
    for i, name in mat_assigns.items():
        if "vacuum" in name.lower() or "graveyard" in name.lower():
            temp[i] = name
        else:
            temp[i] = unique_names[name]
    mat_assigns = temp

    # Replace cell numbers with materials, eliminating duplicate materials
    # within single zone definition
    zones = {}
    for z in voxel:
        zones[z] = {}
        zones[z]["vol_frac"] = []
        zones[z]["mat"] = []
        for i, cell in enumerate(voxel[z]["cell"]):
            if mat_assigns[cell] not in zones[z]["mat"]:
                # create new entry
                zones[z]["mat"].append(mat_assigns[cell])
                zones[z]["vol_frac"].append(voxel[z]["vol_frac"][i])
            else:
                # update value that already exists with new volume fraction
                for j, val in enumerate(zones[z]["mat"]):
                    if mat_assigns[cell] == val:
                        vol_frac = zones[z]["vol_frac"][j] + voxel[z][
                            "vol_frac"][i]
                        zones[z]["vol_frac"][j] = vol_frac

    # Remove vacuum or graveyard from material definition if not vol_frac of 1.0
    skip_array = [["mat:Vacuum"], ["mat:vacuum"], ["mat:Graveyard"],
                  ["mat:graveyard"]]
    skip_list = ["mat:Vacuum", "mat:vacuum", "mat:Graveyard", "mat:graveyard"]
    zones_compressed = {}
    for z, info in zones.items():
        # check first if the definition is 100% void, keep same if is
        if zones[z]["mat"] in skip_array and zones[z]["vol_frac"] == [1.0]:
            zones_compressed[z] = info
        else:
            # check for partial void
            zones_compressed[z] = {"mat": [], "vol_frac": []}
            for i, mat in enumerate(zones[z]["mat"]):
                if mat not in skip_list:
                    zones_compressed[z]["mat"].append(mat)
                    zones_compressed[z]["vol_frac"].append(
                        zones[z]["vol_frac"][i])

    # Eliminate duplicate zones and assign each voxel a zone number.
    # Assign zone = 0 if vacuum or graveyard and eliminate material definition.
    voxel_zone = {}
    zones_mats = {}
    z = 0
    match = False
    first = True
    for i, vals in zones_compressed.items():
        # Find if the zone already exists
        for zone, info in zones_mats.items():
            # Iterate through both sets to disregard order
            match_all = np.empty(len(vals["mat"]), dtype=bool)
            match_all.fill(False)
            for ii, mat in enumerate(vals["mat"]):
                for jj, mat_info in enumerate(info["mat"]):
                    if mat == mat_info and np.allclose(
                            np.array(vals["vol_frac"][ii]),
                            np.array(info["vol_frac"][jj]),
                            rtol=1e-5,
                    ):
                        match_all[ii] = True
                        break
            if match_all.all() == True:
                match = True
                y = zone
                break
            else:
                match = False
        # Create a new zone if first zone or does not match other zones
        if first or not match:
            # Check that the material is not 100% void (assign zone 0 otherwise)
            if vals["mat"] in skip_array:
                voxel_zone[i] = 0
            else:
                z += 1
                zones_mats[z] = zones_compressed[i]
                voxel_zone[i] = z
                first = False
        else:
            if vals["mat"] in skip_array:
                voxel_zone[i] = 0
            else:
                voxel_zone[i] = y

    # Remove any instances of graveyard or vacuum in zone definitions
    zones_novoid = {}
    for z in zones_mats:
        zones_novoid[z] = {"mat": [], "vol_frac": []}
        for i, mat in enumerate(zones_mats[z]["mat"]):
            if mat not in skip_list:
                zones_novoid[z]["mat"].append(mat)
                zones_novoid[z]["vol_frac"].append(
                    zones_mats[z]["vol_frac"][i])

    # Put zones into format for PARTISN input
    if "x" in bounds:
        im = len(bounds["x"]) - 1
    else:
        im = 1

    if "y" in bounds:
        jm = len(bounds["y"]) - 1
    else:
        jm = 1

    if "z" in bounds:
        km = len(bounds["z"]) - 1
    else:
        km = 1

    n = 0
    zones_formatted = np.zeros(shape=(jm * km, im), dtype=int)
    for i in range(im):
        temp = np.zeros(shape=(jm * km), dtype=int)
        for jk in range(jm * km):
            temp[jk] = voxel_zone[n]
            n += 1
        temp = np.reshape(temp, (jm, km))
        temp = np.transpose(temp)
        temp = np.reshape(temp, jm * km)
        zones_formatted[:, i] = temp

    return zones_formatted, zones_novoid
Esempio n. 3
0
def _get_zones(mesh, hdf5, bounds, num_rays, grid):
    """Get the minimum zone definitions for the geometry.
    """

    # load the geometry
    from pyne import dagmc
    dagmc.load(hdf5)

    # Descretize the geometry and get cell fractions
    dg = dagmc.discretize_geom(mesh, num_rays=num_rays, grid=grid)

    # Reorganize dictionary of each voxel's info with the key the voxel number
    # and values of cell and volume fraction
    voxel = {}
    for i in dg:
        idx = i[0]  # voxel number
        if idx not in voxel:
            voxel[idx] = {}
            voxel[idx]['cell'] = []
            voxel[idx]['vol_frac'] = []
        voxel[idx]['cell'].append(i[1])
        voxel[idx]['vol_frac'].append(i[2])

    # get material to cell assignments
    mat_assigns = dagmc.cell_material_assignments(hdf5)

    # Replace cell numbers with materials, eliminating duplicate materials
    # within single zone definition
    zones = {}
    for z in voxel:
        zones[z] = {}
        zones[z]['vol_frac'] = []
        zones[z]['mat'] = []
        for i, cell in enumerate(voxel[z]['cell']):
            if mat_assigns[cell] not in zones[z]['mat']:
                # create new entry
                zones[z]['mat'].append(mat_assigns[cell])
                zones[z]['vol_frac'].append(voxel[z]['vol_frac'][i])
            else:
                # update value that already exists with new volume fraction
                for j, val in enumerate(zones[z]['mat']):
                    if mat_assigns[cell] == val:
                        vol_frac = zones[z]['vol_frac'][j] + voxel[z][
                            'vol_frac'][i]
                        zones[z]['vol_frac'][j] = vol_frac

    # Remove vacuum or graveyard from material definition if not vol_frac of 1.0
    skip_array = [['mat:Vacuum'], ['mat:vacuum'], ['mat:Graveyard'],
                  ['mat:graveyard']]
    skip_list = ['mat:Vacuum', 'mat:vacuum', 'mat:Graveyard', 'mat:graveyard']
    zones_compressed = {}
    for z, info in zones.iteritems():
        # check first if the definition is 100% void, keep same if is
        if zones[z]['mat'] in skip_array and zones[z]['vol_frac'] == [1.0]:
            zones_compressed[z] = info
        else:
            # check for partial void
            zones_compressed[z] = {'mat': [], 'vol_frac': []}
            for i, mat in enumerate(zones[z]['mat']):
                if mat not in skip_list:
                    zones_compressed[z]['mat'].append(mat)
                    zones_compressed[z]['vol_frac'].append(
                        zones[z]['vol_frac'][i])

    # Eliminate duplicate zones and assign each voxel a zone number.
    # Assign zone = 0 if vacuum or graveyard and eliminate material definition.
    voxel_zone = {}
    zones_mats = {}
    z = 0
    match = False
    first = True
    for i, vals in zones_compressed.iteritems():
        # Find if the zone already exists
        for zone, info in zones_mats.iteritems():
            # Iterate through both sets to disregard order
            match_all = np.empty(len(vals['mat']), dtype=bool)
            match_all.fill(False)
            for ii, mat in enumerate(vals['mat']):
                for jj, mat_info in enumerate(info['mat']):
                    if mat == mat_info and np.allclose(np.array(vals['vol_frac'][ii]), \
                                np.array(info['vol_frac'][jj]), rtol=1e-5):
                        match_all[ii] = True
                        break
            if match_all.all() == True:
                match = True
                y = zone
                break
            else:
                match = False
        # Create a new zone if first zone or does not match other zones
        if first or not match:
            # Check that the material is not 100% void (assign zone 0 otherwise)
            if vals['mat'] in skip_array:
                voxel_zone[i] = 0
            else:
                z += 1
                zones_mats[z] = zones_compressed[i]
                voxel_zone[i] = z
                first = False
        else:
            if vals['mat'] in skip_array:
                voxel_zone[i] = 0
            else:
                voxel_zone[i] = y

    # Remove any instances of graveyard or vacuum in zone definitions
    zones_novoid = {}
    for z in zones_mats:
        zones_novoid[z] = {'mat': [], 'vol_frac': []}
        for i, mat in enumerate(zones_mats[z]['mat']):
            if mat not in skip_list:
                name = strip_mat_name(mat)
                zones_novoid[z]['mat'].append(name)
                zones_novoid[z]['vol_frac'].append(
                    zones_mats[z]['vol_frac'][i])

    # Put zones into format for PARTISN input
    if 'x' in bounds:
        im = len(bounds['x']) - 1
    else:
        im = 1

    if 'y' in bounds:
        jm = len(bounds['y']) - 1
    else:
        jm = 1

    if 'z' in bounds:
        km = len(bounds['z']) - 1
    else:
        km = 1

    n = 0
    zones_formatted = np.zeros(shape=(jm * km, im), dtype=int)
    for i in range(im):
        for jk in range(jm * km):
            zones_formatted[jk, i] = voxel_zone[n]
            n += 1

    return zones_formatted, zones_novoid
Esempio n. 4
0
def step5(cfg, cfg2, cfg5):
    """
    This function creates the adjoint neutron source and writes the
    PARTISN input file for adjoint neutron transport.
 
    Parameters
    ----------
    cfg : dictionary
        User input from 'general' section of config.yml file 
    cfg2 : dictionary
        User input for step 2 from the config.yml file
    cfg5 : dictionary 
        User input for step 3 from the config.yml file 
    """
    # Get user-input from config file
    num_n_groups = cfg['n_groups']
    num_p_groups = cfg['p_groups']
    n_geom = cfg2['n_geom_file']
    decay_times = str(cfg2['decay_times']).split(' ')
    meshflux = cfg5['meshflux']

    # Base of geometry file name
    basename = n_geom.split("/")[-1].split(".")[0]

    # The total number of photon and neutron energy groups
    total_num_groups = num_n_groups + num_p_groups

    # Read given flux file and tag to a mesh
    if meshflux:
        # Adjoint flux file is an hdf5 mesh file
        fw_n_err = meshflux
        m = Mesh(structured=True, mesh=fw_n_err, mats=None)
    else:
        raise RuntimeError("No neutron flux file given")

    # Size of flux tag is equal to the total number of energy groups
    m.ERROR_TAG = NativeMeshTag(num_n_groups, name="ERROR_TAG")
    fw_n_err = m.ERROR_TAG[:]

    # Load geometry and get material assignments
    load(n_geom)
    ml = MaterialLibrary(n_geom)
    mat_names = list(ml.keys())
    cell_mats = cell_material_assignments(n_geom)

    # Load T matrix
    if not os.path.exists('step2_T.npy'):
        raise RuntimeError("T matrix from step 2 (step2_T.npy) not found")
    T = np.load('step2_T.npy')

    # Loop over mesh voxels and calculate the error in the photon source by multiplying neutron flux and T matrix
    dg = discretize_geom(m)
    for t, dt in enumerate(decay_times):
        temp = np.zeros(shape=(len(m), num_p_groups))
        for i in range(len(m)):
            for row in np.atleast_1d(dg[dg["idx"] == i]):
                cell = row[1]
                if not cell_mats[cell] in mat_names:
                    continue
                vol_frac = row[2]
                mat = mat_names.index(cell_mats[cell])
                for h in range(num_p_groups):
                    for g in range(num_n_groups):
                        temp[i, h] += (fw_n_err[i, g]**2) * T[mat, t, g,
                                                              h] * vol_frac
                    print("err ", temp[i, h])
        # Tag the mesh with the squared error in the photon source values
        tag_name = "sq_err_q_src_{0}".format(dt)
        m.err_q_src = NativeMeshTag(num_p_groups, name=tag_name)
        m.err_q_src[:] = temp

    # Save adjoint neutron source mesh file tagged with values for all decay times
    m.save("sq_err_q_src.h5m")
Esempio n. 5
0
def _get_zones(mesh, hdf5, bounds, num_rays, grid):
    """Get the minimum zone definitions for the geometry.
    """
    
    # load the geometry
    from pyne import dagmc
    dagmc.load(hdf5)
    
    # Descretize the geometry and get cell fractions
    dg = dagmc.discretize_geom(mesh, num_rays=num_rays, grid=grid)

    # Reorganize dictionary of each voxel's info with the key the voxel number 
    # and values of cell and volume fraction   
    voxel = {}
    for i in dg:
        idx = i[0]  # voxel number
        if idx not in voxel:
            voxel[idx] = {}
            voxel[idx]['cell'] = []
            voxel[idx]['vol_frac'] = []
        voxel[idx]['cell'].append(i[1])
        voxel[idx]['vol_frac'].append(i[2])

    # get material to cell assignments
    mat_assigns = dagmc.cell_material_assignments(hdf5)

    # Replace cell numbers with materials, eliminating duplicate materials
    # within single zone definition
    zones = {}
    for z in voxel:
        zones[z] = {}
        zones[z]['vol_frac'] = []
        zones[z]['mat'] = []
        for i, cell in enumerate(voxel[z]['cell']):
            if mat_assigns[cell] not in zones[z]['mat']:
                # create new entry
                zones[z]['mat'].append(mat_assigns[cell])
                zones[z]['vol_frac'].append(voxel[z]['vol_frac'][i])
            else:
                # update value that already exists with new volume fraction
                for j, val in enumerate(zones[z]['mat']):
                    if mat_assigns[cell] == val:
                        vol_frac = zones[z]['vol_frac'][j] + voxel[z]['vol_frac'][i]
                        zones[z]['vol_frac'][j] = vol_frac
    
    # Remove vacuum or graveyard from material definition if not vol_frac of 1.0
    skip_array = [['mat:Vacuum'], ['mat:vacuum'], ['mat:Graveyard'], ['mat:graveyard']]
    skip_list = ['mat:Vacuum', 'mat:vacuum', 'mat:Graveyard', 'mat:graveyard']
    zones_compressed = {}
    for z, info in zones.iteritems():
        # check first if the definition is 100% void, keep same if is
        if zones[z]['mat'] in skip_array and zones[z]['vol_frac'] == [1.0]:
            zones_compressed[z] = info
        else:
            # check for partial void
            zones_compressed[z] = {'mat':[], 'vol_frac':[]}
            for i, mat in enumerate(zones[z]['mat']):
                if mat not in skip_list:
                    zones_compressed[z]['mat'].append(mat)
                    zones_compressed[z]['vol_frac'].append(zones[z]['vol_frac'][i])
    
    # Eliminate duplicate zones and assign each voxel a zone number.
    # Assign zone = 0 if vacuum or graveyard and eliminate material definition.
    voxel_zone = {}
    zones_mats = {}
    z = 0
    match = False
    first = True    
    for i, vals in zones_compressed.iteritems():
        # Find if the zone already exists
        for zone, info in zones_mats.iteritems():
            # Iterate through both sets to disregard order
            match_all = np.empty(len(vals['mat']), dtype=bool)
            match_all.fill(False)
            for ii, mat in enumerate(vals['mat']):
                for jj, mat_info in enumerate(info['mat']):
                    if mat == mat_info and np.allclose(np.array(vals['vol_frac'][ii]), \
                                np.array(info['vol_frac'][jj]), rtol=1e-5):
                        match_all[ii] = True
                        break
            if match_all.all() == True:
                match = True
                y = zone
                break
            else:
                match = False
        # Create a new zone if first zone or does not match other zones
        if first or not match:
            # Check that the material is not 100% void (assign zone 0 otherwise)
            if vals['mat'] in skip_array:
                voxel_zone[i] = 0
            else:
                z += 1
                zones_mats[z] = zones_compressed[i]
                voxel_zone[i] = z
                first = False
        else:
            if vals['mat'] in skip_array:
                voxel_zone[i] = 0
            else:
                voxel_zone[i] = y
    
    # Remove any instances of graveyard or vacuum in zone definitions
    zones_novoid = {}
    for z in zones_mats:
        zones_novoid[z] = {'mat':[], 'vol_frac':[]}
        for i, mat in enumerate(zones_mats[z]['mat']):
            if mat not in skip_list:
                name = strip_mat_name(mat)
                zones_novoid[z]['mat'].append(name)
                zones_novoid[z]['vol_frac'].append(zones_mats[z]['vol_frac'][i])
    
    # Put zones into format for PARTISN input
    if 'x' in bounds:
        im = len(bounds['x']) - 1
    else:
        im = 1
    
    if 'y' in bounds:
        jm = len(bounds['y']) - 1
    else:
        jm = 1
    
    if 'z' in bounds:
        km = len(bounds['z']) - 1
    else:
        km = 1

    n = 0
    zones_formatted = np.zeros(shape=(jm*km, im), dtype=int)
    for i in range(im):
        for jk in range(jm*km):
            zones_formatted[jk, i] = voxel_zone[n]
            n += 1
    
    return zones_formatted, zones_novoid