Apply @paulromano 's suggestions from code review.

Co-Authored-By: Paul Romano <paul.k.romano@gmail.com>
This commit is contained in:
Patrick Shriwise 2020-03-25 03:14:58 -05:00 committed by GitHub
parent e7eceff2aa
commit ca7cba57df
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 74 additions and 99 deletions

View file

@ -488,7 +488,7 @@
"tally.filters = [mesh_filter]\n",
"tally.scores = ['heating', 'flux']\n",
"tally.estimator = 'tracklength'\n",
"model.tallies = (tally,)"
"model.tallies = [tally]"
]
},
{

View file

@ -99,8 +99,7 @@ public:
int n_dimension_; //!< Number of dimensions
};
class StructuredMesh : public Mesh
{
class StructuredMesh : public Mesh {
public:
StructuredMesh() = default;
StructuredMesh(pugi::xml_node node) : Mesh {node} {};
@ -252,7 +251,7 @@ private:
class UnstructuredMesh : public Mesh {
typedef std::vector<std::pair<double, moab::EntityHandle>> UnstructuredMeshHits;
using UnstructuredMeshHits = std::vector<std::pair<double, moab::EntityHandle>>;
public:
UnstructuredMesh() = default;
@ -273,7 +272,7 @@ public:
private:
//! Finds all intersections with faces of the mesh.
//! Find all intersections with faces of the mesh.
//
//! \param[in] start Staring location
//! \param[in] dir Normalized particle direction
@ -285,7 +284,7 @@ private:
double track_len,
UnstructuredMeshHits& hits) const;
//! Calculates the volume for a given tetrahedron handle.
//! Calculate the volume for a given tetrahedron handle.
//
// \param[in] tet MOAB EntityHandle of the tetrahedron
double tet_volume(moab::EntityHandle tet) const;
@ -297,12 +296,12 @@ private:
//! \return MOAB EntityHandle of tet
moab::EntityHandle get_tet(const Position& r) const;
//! Returns the containing tet given a position
inline moab::EntityHandle get_tet(const moab::CartVect& r) const {
//! Return the containing tet given a position
moab::EntityHandle get_tet(const moab::CartVect& r) const {
return get_tet(Position(r[0], r[1], r[2]));
};
//! Check for point containment within a tet, uses
//! Check for point containment within a tet; uses
//! pre-computed barycentric data.
//
//! \param[in] r Position to check
@ -317,13 +316,13 @@ private:
//! \param[in] tets MOAB Range of tetrahedral elements
void compute_barycentric_data(const moab::Range& tets);
//! Translates a MOAB EntityHandle its corresponding bin.
//! Translate a MOAB EntityHandle to its corresponding bin.
//
//! \param[in] eh MOAB EntityHandle to translate
//! \return Mesh bin
int get_bin_from_ent_handle(moab::EntityHandle eh) const;
//! Translates a bin to its corresponding MOAB EntityHandle
//! Translate a bin to its corresponding MOAB EntityHandle
//! for the tetrahedron representing that bin.
//
//! \param[in] bin Bin value to translate
@ -348,7 +347,7 @@ private:
//! \return Index of the bin
int get_index_from_bin(int bin) const;
//! Builds a KDTree for all tetrahedra in the mesh. All
//! Build a KDTree for all tetrahedra in the mesh. All
//! triangles representing 2D faces of the mesh are
//! added to the tree as well.
//
@ -359,7 +358,7 @@ private:
//! or create them if they are not there
//
//! \param[in] score Name of the score
//! \returns The MOAB value and error tag handles, respectively
//! \return The MOAB value and error tag handles, respectively
std::pair<moab::Tag, moab::Tag>
get_score_tags(std::string score) const;
@ -392,7 +391,7 @@ public:
//! Retrieve a centroid for the mesh cell
//
// \param[in] tet MOAB EntityHandle of the tetrahedron
// \returns The centroid of the element
// \return The centroid of the element
Position centroid(moab::EntityHandle tet) const;
//! Return a string represntation of the mesh bin

View file

@ -632,8 +632,7 @@ class UnstructuredMesh(MeshBase):
@filename.setter
def filename(self, filename):
if filename is not None:
cv.check_type('Unstructured Mesh filename: {}'.format(filename),
filename, str)
cv.check_type('Unstructured Mesh filename', filename, str)
self._filename = filename
else:
self.filename = ''
@ -663,8 +662,7 @@ class UnstructuredMesh(MeshBase):
def __repr__(self):
string = super().__repr__()
string += '{0: <16}{1}{2}\n'.format('\tFilename', '=\t', self.filename)
return string
return string + '{: <16}=\t{}\n'.format('\tFilename', self.filename)
@classmethod
def from_hdf5(cls, group):
@ -674,7 +672,7 @@ class UnstructuredMesh(MeshBase):
mesh.filename = group['filename'][()].decode()
vol_data = group['volumes'][()]
centroids = group['centroids'][()]
mesh.volumes = np.reshape(vol_data, (vol_data.shape[0], 1))
mesh.volumes = np.reshape(vol_data, (vol_data.shape[0],))
mesh.centroids = np.reshape(centroids, (vol_data.shape[0], 3))
return mesh

View file

@ -818,7 +818,7 @@ RegularMesh::count_sites(const Particle::Bank* bank,
bool* outside) const
{
// Determine shape of array for counts
std::size_t m = n_bins();
std::size_t m = this->n_bins();
std::vector<std::size_t> shape = {m};
// Create array of zeros
@ -1413,7 +1413,7 @@ openmc_extend_meshes(int32_t n, int32_t* index_start, int32_t* index_end)
{
if (index_start) *index_start = model::meshes.size();
for (int i = 0; i < n; ++i) {
model::meshes.push_back(std::move(std::make_unique<RegularMesh>()));
model::meshes.push_back(std::make_unique<RegularMesh>());
}
if (index_end) *index_end = model::meshes.size() - 1;
@ -1552,14 +1552,13 @@ UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
// get the filename of the unstructured mesh to load
if (check_for_node(node, "mesh_file")) {
filename_ = get_node_value(node, "mesh_file");
}
else {
} else {
fatal_error("No filename supplied for unstructured mesh with ID: " +
std::to_string(id_));
}
// create MOAB instance
mbi_ = std::unique_ptr<moab::Interface>(new moab::Core());
mbi_ = std::make_unique<moab::Core>();
// create meshset to load mesh into
moab::ErrorCode rval = mbi_->create_meshset(moab::MESHSET_SET, meshset_);
if (rval != moab::MB_SUCCESS) {
@ -1624,7 +1623,7 @@ UnstructuredMesh::build_kdtree(const moab::Range& all_tets)
all_tets_and_tris.merge(all_tris);
// create a kd-tree instance
kdtree_ = std::unique_ptr<moab::AdaptiveKDTree>(new moab::AdaptiveKDTree(mbi_.get()));
kdtree_ = std::make_unique<moab::AdaptiveKDTree>(mbi_.get());
// build the tree
rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_);
@ -1789,8 +1788,8 @@ UnstructuredMesh::get_tet(const Position& r) const
// loop over the tets in this leaf, returning the containing tet if found
for (const auto& tet : tets) {
if (point_in_tet(pos, tet)) {
return tet;
if (point_in_tet(pos, tet)) {
return tet;
}
}
@ -1862,7 +1861,7 @@ UnstructuredMesh::compute_barycentric_data(const moab::Range& tets) {
void
UnstructuredMesh::to_hdf5(hid_t group) const
{
hid_t mesh_group = create_group(group, "mesh " + std::to_string(id_));
hid_t mesh_group = create_group(group, fmt::format("mesh {}", id_));
write_dataset(mesh_group, "type", "unstructured");
write_dataset(mesh_group, "filename", filename_);
@ -1872,8 +1871,8 @@ UnstructuredMesh::to_hdf5(hid_t group) const
xt::xtensor<double, 2> centroids({ehs_.size(), 3});
for (int i = 0; i < ehs_.size(); i++) {
const auto& eh = ehs_[i];
tet_vols.emplace_back(tet_volume(eh));
Position c = centroid(eh);
tet_vols.emplace_back(this->tet_volume(eh));
Position c = this->centroid(eh);
xt::view(centroids, i, xt::all()) = xt::xarray<double>({c.x, c.y, c.z});
}
@ -1922,9 +1921,7 @@ UnstructuredMesh::point_in_tet(const moab::CartVect& r, moab::EntityHandle tet)
int
UnstructuredMesh::get_bin_from_index(int idx) const {
if (idx >= n_bins()) {
std::stringstream s;
s << "Invalid bin index: " << idx;
fatal_error(s);
fatal_error(fmt::format("Invalid bin index: {}", idx));
}
return ehs_[idx] - ehs_[0];
}
@ -1951,9 +1948,7 @@ int
UnstructuredMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const {
int bin = eh - ehs_[0];
if (bin >= n_bins()) {
std::stringstream s;
s << "Invalid bin: " << bin;
fatal_error(s);
fatal_error(fmt::format("Invalid bin: {}", bin));
}
return bin;
}
@ -1961,9 +1956,7 @@ UnstructuredMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const {
moab::EntityHandle
UnstructuredMesh::get_ent_handle_from_bin(int bin) const {
if (bin >= n_bins()) {
std::stringstream s;
s << "Invalid bin index: " << bin;
fatal_error(s);
fatal_error(fmt::format("Invalid bin index: ", bin));
}
return ehs_[bin];
}
@ -1998,7 +1991,7 @@ UnstructuredMesh::centroid(moab::EntityHandle tet) const {
// get the coordinates
std::vector<moab::CartVect> coords(conn.size());
rval = mbi_->get_coords(&conn.front(), conn.size(), coords[0].array());
rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
if (rval != moab::MB_SUCCESS) {
warning("Failed to get the coordinates of a mesh element.");
return {};
@ -2016,9 +2009,7 @@ UnstructuredMesh::centroid(moab::EntityHandle tet) const {
std::string
UnstructuredMesh::bin_label(int bin) const {
std::stringstream out;
out << "Mesh Index (" << bin << ")";
return out.str();
return fmt::format("Mesh Index ({})", bin);
};
std::pair<moab::Tag, moab::Tag>
@ -2031,7 +2022,7 @@ UnstructuredMesh::get_score_tags(std::string score) const {
// create the value tag if not present and get handle
double default_val = 0.0;
auto val_string = score + "_value";
auto val_string = score + "_mean";
rval = mbi_->tag_get_handle(val_string.c_str(),
1,
moab::MB_TYPE_DOUBLE,
@ -2039,9 +2030,8 @@ UnstructuredMesh::get_score_tags(std::string score) const {
moab::MB_TAG_DENSE|moab::MB_TAG_CREAT,
&default_val);
if (rval != moab::MB_SUCCESS) {
std::stringstream msg;
msg << "Could not create or retrieve the value tag for the score " << score
<< " on unstructured mesh " << id_;
auto msg = fmt::format("Could not create or retrieve the value tag for the score {}"
" on unstructured mesh {}", score, id_);
fatal_error(msg);
}
@ -2067,26 +2057,26 @@ UnstructuredMesh::get_score_tags(std::string score) const {
void
UnstructuredMesh::add_score(std::string score) const {
auto score_tags = get_score_tags(score);
auto score_tags = this->get_score_tags(score);
}
void
UnstructuredMesh::set_score_data(const std::string& score,
std::vector<double> values,
std::vector<double> std_dev) const {
auto score_tags = get_score_tags(score);
auto score_tags = this->get_score_tags(score);
// normalize tally values by element volume
for (int i = 0; i < ehs_.size(); i++) {
auto eh = get_ent_handle_from_bin(i);
double volume = tet_volume(eh);
auto eh = this->get_ent_handle_from_bin(i);
double volume = this->tet_volume(eh);
values[i] /= volume;
std_dev[i] /= volume;
}
moab::ErrorCode rval;
// set the score value
rval = mbi_->tag_set_data(score_tags.first, ehs_, &values.front());
rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
if (rval != moab::MB_SUCCESS) {
std::stringstream msg;
msg << "Failed to set the tally value for score '" << score << "' "
@ -2095,7 +2085,7 @@ UnstructuredMesh::set_score_data(const std::string& score,
}
// set the error value
rval = mbi_->tag_set_data(score_tags.second, ehs_, &std_dev.front());
rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
if (rval != moab::MB_SUCCESS) {
std::stringstream msg;
msg << "Failed to set the tally value for score '" << score << "' "
@ -2144,12 +2134,11 @@ void read_meshes(pugi::xml_node root)
model::meshes.push_back(std::make_unique<RegularMesh>(node));
} else if (mesh_type == "rectilinear") {
model::meshes.push_back(std::make_unique<RectilinearMesh>(node));
}
#ifdef DAGMC
else if (mesh_type == "unstructured") {
} else if (mesh_type == "unstructured") {
model::meshes.push_back(std::make_unique<UnstructuredMesh>(node));
#else
else if (mesh_type == "unstructured") {
} else if (mesh_type == "unstructured") {
fatal_error("Unstructured mesh support is disabled.");
#endif
} else {

View file

@ -699,7 +699,7 @@ void write_unstructured_mesh_results() {
// warning and skip writing the mesh
if (tally->filters().size() > 1) {
warning(fmt::format("Skipping unstructured mesh writing for tally "
"{0}. More than one filter is present on the tally.",
"{}. More than one filter is present on the tally.",
tally->id_));
break;
}
@ -711,7 +711,7 @@ void write_unstructured_mesh_results() {
for (int i_nuc = 0; i_nuc < tally->nuclides_.size(); i_nuc++) {
// index for this nuclide and score
int nuc_score_idx = i_score + i_nuc * tally->scores_.size();
int nuc_score_idx = i_score + i_nuc*tally->scores_.size();
// construct result vectors
std::vector<double> mean_vec, std_dev_vec;
@ -731,12 +731,8 @@ void write_unstructured_mesh_results() {
std::string score_name = tally->score_name(i_score);
auto score_str = fmt::format("{0}_{1}",
score_name,
nuclide_name);
umesh->set_score_data(score_str,
mean_vec,
std_dev_vec);
auto score_str = fmt::format("{}_{}", score_name, nuclide_name);
umesh->set_score_data(score_str, mean_vec, std_dev_vec);
}
}

View file

@ -1,4 +1,3 @@
from collections import defaultdict
import glob
from itertools import product
import os
@ -18,8 +17,6 @@ TETS_PER_VOXEL = 12
class UnstructuredMeshTest(PyAPITestHarness):
def __init__(self, statepoint_name, **kwargs):
super().__init__(statepoint_name)
@ -47,11 +44,7 @@ class UnstructuredMeshTest(PyAPITestHarness):
materials.append(fuel_mat)
zirc_mat = openmc.Material(name="zircaloy")
zirc_mat.add_nuclide("Zr90", 0.5145)
zirc_mat.add_nuclide("Zr91", 0.1122)
zirc_mat.add_nuclide("Zr92", 0.1715)
zirc_mat.add_nuclide("Zr94", 0.1738)
zirc_mat.add_nuclide("Zr96", 0.028)
zirc_mat.add_element("Zr", 1.0)
zirc_mat.set_density("g/cc", 5.77)
materials.append(zirc_mat)
@ -64,14 +57,14 @@ class UnstructuredMeshTest(PyAPITestHarness):
materials.export_to_xml()
### Geometry ###
fuel_min_x = openmc.XPlane(x0=-5.0, name="minimum x")
fuel_max_x = openmc.XPlane(x0=5.0, name="maximum x")
fuel_min_x = openmc.XPlane(-5.0, name="minimum x")
fuel_max_x = openmc.XPlane(5.0, name="maximum x")
fuel_min_y = openmc.YPlane(y0=-5.0, name="minimum y")
fuel_max_y = openmc.YPlane(y0=5.0, name="maximum y")
fuel_min_y = openmc.YPlane(-5.0, name="minimum y")
fuel_max_y = openmc.YPlane(5.0, name="maximum y")
fuel_min_z = openmc.ZPlane(z0=-5.0, name="minimum z")
fuel_max_z = openmc.ZPlane(z0=5.0, name="maximum z")
fuel_min_z = openmc.ZPlane(-5.0, name="minimum z")
fuel_max_z = openmc.ZPlane(5.0, name="maximum z")
fuel_cell = openmc.Cell(name="fuel")
fuel_cell.region = +fuel_min_x & -fuel_max_x & \
@ -79,21 +72,21 @@ class UnstructuredMeshTest(PyAPITestHarness):
+fuel_min_z & -fuel_max_z
fuel_cell.fill = fuel_mat
clad_min_x = openmc.XPlane(x0=-6.0, name="minimum x")
clad_max_x = openmc.XPlane(x0=6.0, name="maximum x")
clad_min_x = openmc.XPlane(-6.0, name="minimum x")
clad_max_x = openmc.XPlane(6.0, name="maximum x")
clad_min_y = openmc.YPlane(y0=-6.0, name="minimum y")
clad_max_y = openmc.YPlane(y0=6.0, name="maximum y")
clad_min_y = openmc.YPlane(-6.0, name="minimum y")
clad_max_y = openmc.YPlane(6.0, name="maximum y")
clad_min_z = openmc.ZPlane(z0=-6.0, name="minimum z")
clad_max_z = openmc.ZPlane(z0=6.0, name="maximum z")
clad_min_z = openmc.ZPlane(-6.0, name="minimum z")
clad_max_z = openmc.ZPlane(6.0, name="maximum z")
clad_cell = openmc.Cell(name="clad")
clad_cell.region = (-fuel_min_x | +fuel_max_x | \
-fuel_min_y | +fuel_max_y | \
clad_cell.region = (-fuel_min_x | +fuel_max_x |
-fuel_min_y | +fuel_max_y |
-fuel_min_z | +fuel_max_z) & \
(+clad_min_x & -clad_max_x & \
+clad_min_y & -clad_max_y & \
(+clad_min_x & -clad_max_x &
+clad_min_y & -clad_max_y &
+clad_min_z & -clad_max_z)
clad_cell.fill = zirc_mat
@ -124,19 +117,16 @@ class UnstructuredMeshTest(PyAPITestHarness):
boundary_type='vacuum')
water_cell = openmc.Cell(name="water")
water_cell.region = (-clad_min_x | +clad_max_x | \
-clad_min_y | +clad_max_y | \
water_cell.region = (-clad_min_x | +clad_max_x |
-clad_min_y | +clad_max_y |
-clad_min_z | +clad_max_z) & \
(+water_min_x & -water_max_x & \
+water_min_y & -water_max_y & \
(+water_min_x & -water_max_x &
+water_min_y & -water_max_y &
+water_min_z & -water_max_z)
water_cell.fill = water_mat
# create a containing universe
root_univ = openmc.Universe()
root_univ.add_cells([fuel_cell, clad_cell, water_cell])
geom = openmc.Geometry(root=root_univ)
geom = openmc.Geometry([fuel_cell, clad_cell, water_cell])
geom.export_to_xml()
@ -256,14 +246,17 @@ class UnstructuredMeshTest(PyAPITestHarness):
if os.path.exists(f):
os.remove(f)
param_values = ( ('collision', 'tracklength'), # estimators
(True, False), # geometry outside of the mesh
( (333, 90, 77), tuple() ) ) # location of holes in the mesh
param_values = (['collision', 'tracklength'], # estimators
[True, False], # geometry outside of the mesh
[(333, 90, 77), (,)]) # location of holes in the mesh
test_cases = []
for estimator, holes, ext_geom in product(*param_values):
test_cases.append({'estimator' : estimator,
'external_geom' : ext_geom,
'holes' : holes})
@pytest.mark.parametrize("opts", test_cases)
def test_unstructured_mesh(opts):
harness = UnstructuredMeshTest('statepoint.10.h5', kwargs=opts)