From a6b3eaec9fb311917b7606096e9d5513f69102bb Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Fri, 15 Jan 2016 18:02:44 -0500 Subject: [PATCH 01/34] Added Tally average aggregation operation to Python API --- openmc/aggregate.py | 14 ++-- openmc/tallies.py | 155 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 160 insertions(+), 9 deletions(-) diff --git a/openmc/aggregate.py b/openmc/aggregate.py index 67995a41f2..0e15c193c9 100644 --- a/openmc/aggregate.py +++ b/openmc/aggregate.py @@ -13,7 +13,7 @@ if sys.version_info[0] >= 3: basestring = str # Acceptable tally aggregation operations -_TALLY_AGGREGATE_OPS = ['sum', 'mean'] +_TALLY_AGGREGATE_OPS = ['sum', 'avg'] class AggregateScore(object): @@ -25,7 +25,7 @@ class AggregateScore(object): scores : Iterable of str or CrossScore The scores included in the aggregation aggregate_op : str - The tally aggregation operator (e.g., 'sum', 'mean', etc.) used + The tally aggregation operator (e.g., 'sum', 'avg', etc.) used to aggregate across a tally's scores with this AggregateScore Attributes @@ -33,7 +33,7 @@ class AggregateScore(object): scores : Iterable of str or CrossScore The scores included in the aggregation aggregate_op : str - The tally aggregation operator (e.g., 'sum', 'mean', etc.) used + The tally aggregation operator (e.g., 'sum', 'avg', etc.) used to aggregate across a tally's scores with this AggregateScore """ @@ -108,7 +108,7 @@ class AggregateNuclide(object): nuclides : Iterable of str or Nuclide or CrossNuclide The nuclides included in the aggregation aggregate_op : str - The tally aggregation operator (e.g., 'sum', 'mean', etc.) used + The tally aggregation operator (e.g., 'sum', 'avg', etc.) used to aggregate across a tally's nuclides with this AggregateNuclide Attributes @@ -116,7 +116,7 @@ class AggregateNuclide(object): nuclides : Iterable of str or Nuclide or CrossNuclide The nuclides included in the aggregation aggregate_op : str - The tally aggregation operator (e.g., 'sum', 'mean', etc.) used + The tally aggregation operator (e.g., 'sum', 'avg', etc.) used to aggregate across a tally's nuclides with this AggregateNuclide """ @@ -198,7 +198,7 @@ class AggregateFilter(object): bins : Iterable of tuple The filter bins included in the aggregation aggregate_op : str - The tally aggregation operator (e.g., 'sum', 'mean', etc.) used + The tally aggregation operator (e.g., 'sum', 'avg', etc.) used to aggregate across a tally filter's bins with this AggregateFilter Attributes @@ -208,7 +208,7 @@ class AggregateFilter(object): aggregate_filter : filter The filter included in the aggregation aggregate_op : str - The tally aggregation operator (e.g., 'sum', 'mean', etc.) used + The tally aggregation operator (e.g., 'sum', 'avg', etc.) used to aggregate across a tally filter's bins with this AggregateFilter bins : Iterable of tuple The filter bins included in the aggregation diff --git a/openmc/tallies.py b/openmc/tallies.py index 980c5fa2b5..30495398ac 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -2758,7 +2758,7 @@ class Tally(object): def summation(self, scores=[], filter_type=None, filter_bins=[], nuclides=[], remove_filter=False): """Vectorized sum of tally data across scores, filter bins and/or - nuclides using tally addition. + nuclides using tally aggregation. This method constructs a new tally to encapsulate the sum of the data represented by the summation of the data in this tally. The tally data @@ -2800,7 +2800,7 @@ class Tally(object): tally_sum._derived = True tally_sum._estimator = self.estimator tally_sum._num_realizations = self.num_realizations - tally_sum.with_batch_statistics = self.with_batch_statistics + tally_sum._with_batch_statistics = self.with_batch_statistics tally_sum._with_summary = self.with_summary tally_sum._sp_filename = self._sp_filename tally_sum._results_read = self._results_read @@ -2903,6 +2903,157 @@ class Tally(object): tally_sum.sparse = self.sparse return tally_sum + def average(self, scores=[], filter_type=None, + filter_bins=[], nuclides=[], remove_filter=False): + """Vectorized average of tally data across scores, filter bins and/or + nuclides using tally aggregation. + + This method constructs a new tally to encapsulate the average of the + data represented by the average of the data in this tally. The tally + data average is determined by the scores, filter bins and nuclides + specified in the input parameters. + + Parameters + ---------- + scores : list of str + A list of one or more score strings to average across + (e.g., ['absorption', 'nu-fission']; default is []) + filter_type : str + A filter type string (e.g., 'cell', 'energy') corresponding to the + filter bins to average across + filter_bins : Iterable of Integral or tuple + A list of the filter bins corresponding to the filter_type parameter + Each bin in the list is the integer ID for 'material', 'surface', + 'cell', 'cellborn', and 'universe' Filters. Each bin is an integer + for the cell instance ID for 'distribcell' Filters. Each bin is a + 2-tuple of floats for 'energy' and 'energyout' filters corresponding + to the energy boundaries of the bin of interest. Each bin is an + (x,y,z) 3-tuple for 'mesh' filters corresponding to the mesh cell of + interest. + nuclides : list of str + A list of nuclide name strings to average across + (e.g., ['U-235', 'U-238']; default is []) + remove_filter : bool + If a filter is being averaged over, this bool indicates whether to + remove that filter in the returned tally. Default is False. + + Returns + ------- + Tally + A new tally which encapsulates the average of data requested. + """ + + # Create new derived Tally for average + tally_avg = Tally() + tally_avg._derived = True + tally_avg._estimator = self.estimator + tally_avg._num_realizations = self.num_realizations + tally_avg._with_batch_statistics = self.with_batch_statistics + tally_avg._with_summary = self.with_summary + tally_avg._sp_filename = self._sp_filename + tally_avg._results_read = self._results_read + + # Get tally data arrays reshaped with one dimension per filter + mean = self.get_reshaped_data(value='mean') + std_dev = self.get_reshaped_data(value='std_dev') + + # Average across any filter bins specified by the user + if filter_type in _FILTER_TYPES: + find_filter = self.find_filter(filter_type) + + # If user did not specify filter bins, average across all bins + if len(filter_bins) == 0: + bin_indices = np.arange(find_filter.num_bins) + + if filter_type == 'distribcell': + filter_bins = np.arange(find_filter.num_bins) + else: + num_bins = find_filter.num_bins + filter_bins = \ + [(find_filter.get_bin(i)) for i in range(num_bins)] + + # Only average across bins specified by the user + else: + bin_indices = \ + [find_filter.get_bin_index(bin) for bin in filter_bins] + + # Average across the bins in the user-specified filter + for i, self_filter in enumerate(self.filters): + if self_filter.type == filter_type: + mean = np.take(mean, indices=bin_indices, axis=i) + std_dev = np.take(std_dev, indices=bin_indices, axis=i) + mean = np.mean(mean, axis=i, keepdims=True) + std_dev = np.mean(std_dev**2, axis=i, keepdims=True) + std_dev /= len(bin_indices) + std_dev = np.sqrt(std_dev) + + # Add AggregateFilter to the tally avg + if not remove_filter: + filter_sum = \ + AggregateFilter(self_filter, filter_bins, 'avg') + tally_avg.add_filter(filter_sum) + + # Add a copy of each filter not averaged across to the tally avg + else: + tally_avg.add_filter(copy.deepcopy(self_filter)) + + # Add a copy of this tally's filters to the tally avg + else: + tally_avg._filters = copy.deepcopy(self.filters) + + # Sum across any nuclides specified by the user + if len(nuclides) != 0: + nuclide_bins = [self.get_nuclide_index(nuclide) for nuclide in nuclides] + axis_index = self.num_filters + mean = np.take(mean, indices=nuclide_bins, axis=axis_index) + std_dev = np.take(std_dev, indices=nuclide_bins, axis=axis_index) + mean = np.mean(mean, axis=axis_index, keepdims=True) + std_dev = np.mean(std_dev**2, axis=axis_index, keepdims=True) + std_dev /= len(nuclide_bins) + std_dev = np.sqrt(std_dev) + + # Add AggregateNuclide to the tally avg + nuclide_avg = AggregateNuclide(nuclides, 'avg') + tally_avg.add_nuclide(nuclide_avg) + + # Add a copy of this tally's nuclides to the tally avg + else: + tally_avg._nuclides = copy.deepcopy(self.nuclides) + + # Sum across any scores specified by the user + if len(scores) != 0: + score_bins = [self.get_score_index(score) for score in scores] + axis_index = self.num_filters + 1 + mean = np.take(mean, indices=score_bins, axis=axis_index) + std_dev = np.take(std_dev, indices=score_bins, axis=axis_index) + mean = np.sum(mean, axis=axis_index, keepdims=True) + std_dev = np.sum(std_dev**2, axis=axis_index, keepdims=True) + std_dev /= len(score_bins) + std_dev = np.sqrt(std_dev) + + # Add AggregateScore to the tally avg + score_sum = AggregateScore(scores, 'avg') + tally_avg.add_score(score_sum) + + # Add a copy of this tally's scores to the tally avg + else: + tally_avg._scores = copy.deepcopy(self.scores) + + # Update the tally avg's filter strides + tally_avg._update_filter_strides() + + # Reshape condensed data arrays with one dimension for all filters + mean = np.reshape(mean, tally_avg.shape) + std_dev = np.reshape(std_dev, tally_avg.shape) + + # Assign tally avg's data with the new arrays + tally_avg._mean = mean + tally_avg._std_dev = std_dev + + # If original tally was sparse, sparsify the tally average + tally_avg.sparse = self.sparse + return tally_avg + def diagonalize_filter(self, new_filter): """Diagonalize the tally data array along a new axis of filter bins. From bd195ca069a2893c605c9c4d8dda9afede2a479d Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Wed, 3 Feb 2016 14:13:41 -0500 Subject: [PATCH 02/34] Now setting the source space Box to be fissionable in asymmetric lattice test --- tests/test_asymmetric_lattice/inputs_true.dat | 2 +- tests/test_asymmetric_lattice/results_true.dat | 2 +- tests/test_asymmetric_lattice/test_asymmetric_lattice.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_asymmetric_lattice/inputs_true.dat b/tests/test_asymmetric_lattice/inputs_true.dat index 552c8d039e..e3b00b185c 100644 --- a/tests/test_asymmetric_lattice/inputs_true.dat +++ b/tests/test_asymmetric_lattice/inputs_true.dat @@ -1 +1 @@ -fe07eb28fd0dbb56edaecd510f5e8e4db7271e5c9aecf3d880cce92b69872a0aacf825b8e88cd2e9b1ff709f578b269b1835f53cf2561a390062e1e7e03b5276 \ No newline at end of file +b9b4222c4beea80fe6083590f6b785303d174972d80671fb661bac8e030db6f4a61648240cfad6162799361fc0e08a23c61d31aff844d978528d6dad5b5fbc63 \ No newline at end of file diff --git a/tests/test_asymmetric_lattice/results_true.dat b/tests/test_asymmetric_lattice/results_true.dat index 0cf2315ea4..ec4b883886 100644 --- a/tests/test_asymmetric_lattice/results_true.dat +++ b/tests/test_asymmetric_lattice/results_true.dat @@ -1 +1 @@ -cea61172ecad5554ef86f52d6adad6ad5e21931cf3d67feb37b8bf9d75e618786f638685e458051d4a39afe1a924fd651cf6674a88cf1f1842fd69cd851e1f17 \ No newline at end of file +b5f96919ca474cd1c9c9d0acde3b8aac4a1cf636443c72a38b6c5a4221a8ce3e90182aaef2f664e44b9175ca257a89db2328b63e19388ee0e5006de4b3d92ce6 \ No newline at end of file diff --git a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py b/tests/test_asymmetric_lattice/test_asymmetric_lattice.py index 3b9e2029b2..0080078aa3 100644 --- a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py +++ b/tests/test_asymmetric_lattice/test_asymmetric_lattice.py @@ -74,7 +74,7 @@ class AsymmetricLatticeTestHarness(PyAPITestHarness): # Specify summary output and correct source sampling box source = Source(space=Box([-32, -32, 0], [32, 32, 32])) - source.only_fissionable = True + source.space.only_fissionable = True self._input_set.settings.source = source self._input_set.settings.output = {'summary': True} From 0b80ef0509b1baab5de9a5e5494541b472d66313 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Wed, 3 Feb 2016 16:50:09 -0500 Subject: [PATCH 03/34] Added MGXS slice class method --- openmc/mgxs/mgxs.py | 87 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 3 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index f241274581..b199933863 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -66,6 +66,10 @@ class MGXS(object): The energy group structure for energy condensation by_nuclide : bool If true, computes cross sections for each nuclide in domain + nuclides : Iterable of basestring + The user-specified nuclides to compute cross sections. If by_nuclide + is True but nuclides are not specified by the user, all nuclides in the + spatial domain will be used. name : str, optional Name of the multi-group cross section. Used as a label to identify tallies in OpenMC 'tallies.xml' file. @@ -122,6 +126,7 @@ class MGXS(object): self._name = '' self._rxn_type = None self._by_nuclide = None + self._nuclides = None self._domain = None self._domain_type = None self._energy_groups = None @@ -150,6 +155,7 @@ class MGXS(object): clone._name = self.name clone._rxn_type = self.rxn_type clone._by_nuclide = self.by_nuclide + clone._nuclides = self._nuclides clone._domain = self.domain clone._domain_type = self.domain_type clone._energy_groups = copy.deepcopy(self.energy_groups, memo) @@ -259,6 +265,11 @@ class MGXS(object): cv.check_type('by_nuclide', by_nuclide, bool) self._by_nuclide = by_nuclide + @nuclides.setter + def nuclides(self, nuclides): + cv.check_iterable_type('nuclides', nuclides, basestring) + self._nuclides = nuclides + @domain.setter def domain(self, domain): cv.check_type('domain', domain, tuple(_DOMAINS)) @@ -386,8 +397,14 @@ class MGXS(object): if self.domain is None: raise ValueError('Unable to get all nuclides without a domain') - nuclides = self.domain.get_all_nuclides() - return nuclides.keys() + # If the user defined nuclides, return them + if self._nuclides: + return self._nuclides + + # Otherwise, return all nuclides in the spatial domain + else: + nuclides = self.domain.get_all_nuclides() + return nuclides.keys() def get_nuclide_density(self, nuclide): """Get the atomic number density in units of atoms/b-cm for a nuclide @@ -550,7 +567,7 @@ class MGXS(object): # If computing xs for each nuclide, replace CrossNuclides with originals if self.by_nuclide: self.xs_tally._nuclides = [] - nuclides = self.domain.get_all_nuclides() + nuclides = self.get_all_nuclides() for nuclide in nuclides: self.xs_tally.add_nuclide(openmc.Nuclide(nuclide)) @@ -865,6 +882,70 @@ class MGXS(object): avg_xs.sparse = self.sparse return avg_xs + def get_slice(self, nuclides=[], groups=[]): + """Build a sliced MGXS for the specified nuclides and energy groups. + + This method constructs a new MGXS to encapsulate a subset of the data + represented by this MGXS. The subset of data to include in the tally + slice is determined by the nuclides and energy groups specified in + the input parameters. + + Parameters + ---------- + nuclides : list of str + A list of nuclide name strings + (e.g., ['U-235', 'U-238']; default is []) + groups : list of Integral + A list of energy group indices starting at 1 for the high energies + (e.g., [1, 2, 3]; default is []) + + Returns + ------- + MGXS + A new tally which encapsulates the subset of data requested for the + nuclide(s) and/or energy group(s) requested in the parameters. + + """ + + cv.check_iterable_type('nuclides', nuclides, basestring) + cv.check_iterable_type('energy_groups', groups, Integral) + + # Build lists of filters and filter bins to slice + if len(groups) == 0: + filters = [] + filter_bins = [] + else: + filter_bins = [] + for group in groups: + group_bounds = self.energy_groups.get_group_bounds(group) + filter_bins.append(group_bounds) + filter_bins = [tuple(filter_bins)] + filters = ['energy'] + + # Clone this MGXS to initialize the sliced version + slice_xs = copy.deepcopy(self) + slice_xs._rxn_rate_tally = None + slice_xs._xs_tally = None + + # Slice each of the tallies across nuclides and energy groups + for tally_type, tally in slice_xs.tallies.items(): + slice_nuclides = [nuc for nuc in nuclides if nuc in tally.nuclides] + tally_slice = tally.get_slice(filters=filters, + filter_bins=filter_bins, nuclides=slice_nuclides) + slice_xs.tallies[tally_type] = tally_slice + + # Assign sliced energy group structure to sliced MGXS + if groups: + energy_filter = slice_xs.tallies.values()[0].find_filter('energy') + slice_xs.energy_groups.group_edges = energy_filter.bins + + # Assign sliced nuclides to sliced MGXS + if nuclides: + slice_xs.nuclides = nuclides + + slice_xs.sparse = self.sparse + return slice_xs + def print_xs(self, subdomains='all', nuclides='all', xs_type='macro'): """Print a string representation for the multi-group cross section. From a5c51aa71532297afca8c0f9577bac2bf8153664 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Wed, 3 Feb 2016 17:20:12 -0500 Subject: [PATCH 04/34] Added slice method to ScatterMatrixXS along with new Tally.contains_filter(...) --- openmc/mgxs/mgxs.py | 54 +++++++++++++++++++++++++++++++++++++++++++-- openmc/tallies.py | 26 ++++++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index b199933863..d4d949d1b2 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -930,8 +930,11 @@ class MGXS(object): # Slice each of the tallies across nuclides and energy groups for tally_type, tally in slice_xs.tallies.items(): slice_nuclides = [nuc for nuc in nuclides if nuc in tally.nuclides] - tally_slice = tally.get_slice(filters=filters, - filter_bins=filter_bins, nuclides=slice_nuclides) + if len(groups) != 0 and tally.contains_filter('energy'): + tally_slice = tally.get_slice(filters=filters, + filter_bins=filter_bins, nuclides=slice_nuclides) + else: + tally_slice = tally.get_slice(nuclides=slice_nuclides) slice_xs.tallies[tally_type] = tally_slice # Assign sliced energy group structure to sliced MGXS @@ -1822,6 +1825,53 @@ class ScatterMatrixXS(MGXS): cv.check_value('correction', correction, ('P0', None)) self._correction = correction + def get_slice(self, nuclides=[], groups=[]): + """Build a sliced MGXS for the specified nuclides and energy groups. + + This method constructs a new MGXS to encapsulate a subset of the data + represented by this MGXS. The subset of data to include in the tally + slice is determined by the nuclides and energy groups specified in + the input parameters. + + Parameters + ---------- + nuclides : list of str + A list of nuclide name strings + (e.g., ['U-235', 'U-238']; default is []) + groups : list of Integral + A list of energy group indices starting at 1 for the high energies + (e.g., [1, 2, 3]; default is []) + + Returns + ------- + MGXS + A new tally which encapsulates the subset of data requested for the + nuclide(s) and/or energy group(s) requested in the parameters. + + """ + + slice_xs = super(ScatterMatrixXS, self).get_slice(nuclides, groups) + slice_xs._rxn_rate_tally = None + slice_xs._xs_tally = None + + # Build lists of filters and filter bins to slice + if len(groups) != 0: + filter_bins = [] + for group in groups: + group_bounds = self.energy_groups.get_group_bounds(group) + filter_bins.append(group_bounds) + filter_bins = [tuple(filter_bins)] + + # Slice each of the tallies across nuclides and energy groups + for tally_type, tally in slice_xs.tallies.items(): + if tally.contains_filter('energyout'): + tally_slice = tally.get_slice(filters=['energyout'], + filter_bins=filter_bins) + slice_xs.tallies[tally_type] = tally_slice + + slice_xs.sparse = self.sparse + return slice_xs + def get_xs(self, in_groups='all', out_groups='all', subdomains='all', nuclides='all', xs_type='macro', order_groups='increasing', value='mean'): diff --git a/openmc/tallies.py b/openmc/tallies.py index 1ad62e33ab..66b99cb00c 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -846,6 +846,32 @@ class Tally(object): return element + def contains_filter(self, filter_type): + """Looks for a filter in the tally that matches a specified type + + Parameters + ---------- + filter_type : str + Type of the filter, e.g. 'mesh' + + Returns + ------- + filter_found : bool + True if the tally contains a filter of the requested type; + otherwise false + + """ + + filter_found = False + + # Look through all of this Tally's Filters for the type requested + for test_filter in self.filters: + if test_filter.type == filter_type: + filter_found = True + break + + return filter_found + def find_filter(self, filter_type): """Return a filter in the tally that matches a specified type From d66f2b108aaa23b0c69fc192f372a7b009c1c256 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Wed, 3 Feb 2016 18:10:33 -0500 Subject: [PATCH 05/34] Added Chi.get_slice(...) method --- openmc/mgxs/mgxs.py | 70 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index d4d949d1b2..272d5e0402 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -939,8 +939,12 @@ class MGXS(object): # Assign sliced energy group structure to sliced MGXS if groups: - energy_filter = slice_xs.tallies.values()[0].find_filter('energy') - slice_xs.energy_groups.group_edges = energy_filter.bins + new_group_edges = [] + for group in groups: + group_edges = self.energy_groups.get_group_bounds(group) + new_group_edges.extend(group_edges) + new_group_edges = np.unique(new_group_edges) + slice_xs.energy_groups.group_edges = sorted(new_group_edges) # Assign sliced nuclides to sliced MGXS if nuclides: @@ -1850,11 +1854,12 @@ class ScatterMatrixXS(MGXS): """ + # Call super class method and null out derived tallies slice_xs = super(ScatterMatrixXS, self).get_slice(nuclides, groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None - # Build lists of filters and filter bins to slice + # Slice energy groups if needed if len(groups) != 0: filter_bins = [] for group in groups: @@ -1862,7 +1867,7 @@ class ScatterMatrixXS(MGXS): filter_bins.append(group_bounds) filter_bins = [tuple(filter_bins)] - # Slice each of the tallies across nuclides and energy groups + # Slice each of the tallies across energyout groups for tally_type, tally in slice_xs.tallies.items(): if tally.contains_filter('energyout'): tally_slice = tally.get_slice(filters=['energyout'], @@ -2215,6 +2220,63 @@ class Chi(MGXS): return self._xs_tally + def get_slice(self, nuclides=[], groups=[]): + """Build a sliced MGXS for the specified nuclides and energy groups. + + This method constructs a new MGXS to encapsulate a subset of the data + represented by this MGXS. The subset of data to include in the tally + slice is determined by the nuclides and energy groups specified in + the input parameters. + + Parameters + ---------- + nuclides : list of str + A list of nuclide name strings + (e.g., ['U-235', 'U-238']; default is []) + groups : list of Integral + A list of energy group indices starting at 1 for the high energies + (e.g., [1, 2, 3]; default is []) + + Returns + ------- + MGXS + A new tally which encapsulates the subset of data requested for the + nuclide(s) and/or energy group(s) requested in the parameters. + + """ + + # Temporarily remove energy filter from nu-fission-in since its + # group structure will work in super MGXS.get_slice(...) method + nu_fission_in = self.tallies['nu-fission-in'] + energy_filter = nu_fission_in.find_filter('energy') + nu_fission_in.remove_filter(energy_filter) + + # Call super class method and null out derived tallies + slice_xs = super(Chi, self).get_slice(nuclides, groups) + slice_xs._rxn_rate_tally = None + slice_xs._xs_tally = None + + # Slice energy groups if needed + if len(groups) != 0: + filter_bins = [] + for group in groups: + group_bounds = self.energy_groups.get_group_bounds(group) + filter_bins.append(group_bounds) + filter_bins = [tuple(filter_bins)] + + # Slice nu-fission-out tally along energyout filter + nu_fission_out = slice_xs.tallies['nu-fission-out'] + tally_slice = nu_fission_out.get_slice(filters=['energyout'], + filter_bins=filter_bins) + slice_xs._tallies['nu-fission-out'] = tally_slice + + # Add energy filter back to nu-fission-in tallies + self.tallies['nu-fission-in'].add_filter(energy_filter) + slice_xs._tallies['nu-fission-in'].add_filter(energy_filter) + + slice_xs.sparse = self.sparse + return slice_xs + def get_xs(self, groups='all', subdomains='all', nuclides='all', xs_type='macro', order_groups='increasing', value='mean'): """Returns an array of the fission spectrum. From 628daeb48a2bafc7f40dbddc8642d7e9c1d3199f Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Thu, 4 Feb 2016 09:11:47 -0500 Subject: [PATCH 06/34] Now require numpy >=1.9 in install_requires per request by @paulromano --- setup.py | 2 +- tests/test_asymmetric_lattice/test_asymmetric_lattice.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 0bf4549c03..87fdff68cf 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,7 @@ kwargs = {'name': 'openmc', if have_setuptools: kwargs.update({ # Required dependencies - 'install_requires': ['numpy', 'h5py', 'matplotlib'], + 'install_requires': ['numpy>=1.9', 'h5py', 'matplotlib'], # Optional dependencies 'extras_require': { diff --git a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py b/tests/test_asymmetric_lattice/test_asymmetric_lattice.py index 0080078aa3..5a1d47ef85 100644 --- a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py +++ b/tests/test_asymmetric_lattice/test_asymmetric_lattice.py @@ -69,7 +69,7 @@ class AsymmetricLatticeTestHarness(PyAPITestHarness): # Assign the tallies file to the input set self._input_set.tallies = tallies_file - + # Build default settings self._input_set.build_default_settings() # Specify summary output and correct source sampling box From 076117c3aa1d1d73d0fde21ca9c230725848d0e0 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Thu, 4 Feb 2016 19:30:11 -0500 Subject: [PATCH 07/34] MGXS Library now properly deep copies domains dictionary --- openmc/mgxs/library.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmc/mgxs/library.py b/openmc/mgxs/library.py index e87b4bdaef..a38e42d245 100644 --- a/openmc/mgxs/library.py +++ b/openmc/mgxs/library.py @@ -116,11 +116,11 @@ class Library(object): clone._by_nuclide = self.by_nuclide clone._mgxs_types = self.mgxs_types clone._domain_type = self.domain_type - clone._domains = self.domains + clone._domains = copy.deepcopy(self.domains) clone._correction = self.correction clone._energy_groups = copy.deepcopy(self.energy_groups, memo) clone._tally_trigger = copy.deepcopy(self.tally_trigger, memo) - clone._all_mgxs = self.all_mgxs + clone._all_mgxs = copy.deepcopy(self.all_mgxs) clone._sp_filename = self._sp_filename clone._keff = self._keff clone._sparse = self.sparse From 7fa2be860af63d2118fb9a7451e5ad56f05f6129 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Sat, 6 Feb 2016 15:04:56 -0500 Subject: [PATCH 08/34] Improved modular functionalization of tally merging --- openmc/filter.py | 23 +++- openmc/tallies.py | 287 ++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 267 insertions(+), 43 deletions(-) diff --git a/openmc/filter.py b/openmc/filter.py index 54814a6b6f..430b2415f0 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -257,9 +257,17 @@ class Filter(object): elif self.type == 'mesh': return False - # Different energy bins are not mergeable + # Different energy bins structures must be mutually exclusive and + # share only one shared bin edge at the minimum or maximum energy elif 'energy' in self.type: - return False + # This low energy edge coincides with other's high energy edge + if self.bins[0] == other.bins[-1]: + return True + # This high energy edge coincides with other's low energy edge + elif self.bins[-1] == other.bins[0]: + return True + else: + return False else: return True @@ -288,9 +296,14 @@ class Filter(object): merged_filter = copy.deepcopy(self) # Merge unique filter bins - merged_bins = list(set(np.concatenate((self.bins, other.bins)))) - merged_filter.bins = merged_bins - merged_filter.num_bins = len(merged_bins) + merged_bins = set(np.concatenate((self.bins, other.bins))) + merged_filter.bins = list(sorted(merged_bins)) + + # Count bins in the merged filter + if 'energy' in merged_filter.type: + merged_filter.num_bins = len(merged_bins) -1 + else: + merged_filter.num_bins = len(merged_bins) return merged_filter diff --git a/openmc/tallies.py b/openmc/tallies.py index 66b99cb00c..dabbeb04ae 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -673,66 +673,162 @@ class Tally(object): self._nuclides.remove(nuclide) - def can_merge(self, tally): - """Determine if another tally can be merged with this one + def _can_merge_filters(self, other): + """Determine if another tally's filters can be merged with this one's + + The types of filters between the two tallies must match identically. + The bins in all of the filters must match identically, or be mergeable + in only one filter. This is a helper method for the can_merge(...) + and merge(...) methods. Parameters ---------- - tally : Tally - Tally to check for merging + other : Tally + Tally to check for mergeable scores """ - if not isinstance(tally, Tally): + # Two tallys must have the same number of filters + if len(self.filters) != len(other.filters): return False - # Must have same estimator - if self.estimator != tally.estimator: - return False - - # Must have same nuclides - if len(self.nuclides) != len(tally.nuclides): - return False - - for nuclide in self.nuclides: - if nuclide not in tally.nuclides: - return False - - # Must have same or mergeable filters - if len(self.filters) != len(tally.filters): - return False - - # Check if only one tally contains a delayed group filter - tally1_dg = False - for filter1 in self.filters: - if filter1.type == 'delayedgroup': - tally1_dg = True - - tally2_dg = False - for filter2 in tally.filters: - if filter2.type == 'delayedgroup': - tally2_dg = True - # Return False if only one tally has a delayed group filter - if (tally1_dg or tally2_dg) and not (tally1_dg and tally2_dg): + tally1_dg = self.contains_filter('delayedgroup') + tally2_dg = other.contains_filter('delayedgroup') + if sum(tally1_dg, tally2_dg) == 1: return False # Look to see if all filters are the same, or one or more can be merged for filter1 in self.filters: mergeable_filter = False - for filter2 in tally.filters: - if filter1 == filter2 or filter1.can_merge(filter2): + for filter2 in other.filters: + + # If filters match, they are mergeable + if filter1 == filter2: mergeable_filter = True break + # If filters are first mergeable filters encountered + elif filter1.can_merge(filter2) and not merge_filters: + merge_filters = True + mergeable_filter = True + break + + # If filters are the second mergeable filters encountered + elif filter1.can_merge(filter2) and merge_filters: + return False + # If no mergeable filter was found, the tallies are not mergeable if not mergeable_filter: return False - # Tallies are mergeable if all conditional checks passed + # Tally filters are mergeable if all conditional checks passed return True + def _can_merge_nuclides(self, other): + """Determine if another tally's nuclides can be merged with this one's + + The nuclides between the two tallies must be mutually exclusive or + identically matching. This is a helper method for the can_merge(...) + and merge(...) methods. + + Parameters + ---------- + other : Tally + Tally to check for mergeable nuclides + + """ + + no_nuclides_match = True + all_nuclides_match = True + + # Search for each of this tally's nuclides in the other tally + for nuclide in self.nuclides: + if nuclide not in other.nuclides: + all_nuclides_match = False + else: + no_nuclides_match = False + + # Search for each of the other tally's nuclides in this tally + for nuclide in other.nuclides: + if nuclide not in self.nuclides: + all_nuclides_match = False + else: + no_nuclides_match = False + + # Either all nuclides should match, or none should + if no_nuclides_match: + return True + if not no_nuclides_match and not all_nuclides_match: + return False + + def _can_merge_scores(self, other): + """Determine if another tally's scores can be merged with this one's + + The scores between the two tallies must be mutually exclusive or + identically matching. This is a helper method for the can_merge(...) + and merge(...) methods. + + Parameters + ---------- + other : Tally + Tally to check for mergeable scores + + """ + + no_scores_match = True + all_scores_match = True + + # Search for each of this tally's scores in the other tally + for score in self.scores: + if score not in other.scores: + all_scores_match = False + else: + no_scores_match = False + + # Search for each of the other tally's scores in this tally + for score in other.scores: + if score not in self.scores: + all_scores_match = False + else: + no_scores_match = False + + # Either all scores should match, or none should + if no_scores_match: + return True + elif not no_scores_match and not all_scores_match: + return False + + def can_merge(self, other): + """Determine if another tally can be merged with this one + + Parameters + ---------- + other : Tally + Tally to check for merging + + """ + + if not isinstance(other, Tally): + return False + + # Must have same estimator + if self.estimator != other.estimator: + return False + + # Variables to indicate matching filter bins, nuclides and scores + merge_filters = self._can_merge_filters(other) + merge_nuclides = self._can_merge_nuclides(other) + merge_scores = self._can_merge_scores(other) + + # Tallies are mergeable if only one of filters, nuclides and + # scores is mergeable + if sum(merge_filters, merge_nuclides, merge_scores) == 1: + return True + else: + return False + def merge(self, tally): """Merge another tally with this one @@ -778,6 +874,116 @@ class Tally(object): return merged_tally + def join(self, other): + """Join another tally with this one + + Parameters + ---------- + tally : Tally + Tally to join with this one + + Returns + ------- + joined_tally : Tally + Joined tallies + + """ + + if not self.can_merge(other): + msg = 'Unable to join tally ID="{0}" with ' + \ + '"{1}"'.format(other.id, self.id) + raise ValueError(msg) + + # Create deep copy of tally to return as merged tally + joined_tally = copy.deepcopy(self) + + # Differentiate Tally with a new auto-generated Tally ID + joined_tally.id = None + + # Create deep copy of other tally to use for array concatenation + other_copy = copy.deepcopy(other) + + # If two tallies can be merged along a filter's bins + if self._can_merge_filters(other): + + # Search for mergeable filters + for i, filter1 in enumerate(self.filters): + for j, filter2 in enumerate(other.filters): + if filter1 != filter2 and filter1.can_merge(filter2): + other_copy._swap_filters(other_copy.filters[i], filter1) + joined_tally.filters[i] = filter1.merge(filter2) + join_axis = i + break + + # If two tallies can be merged along nuclide bins + elif self._can_merge_nuclides(other): + join_axis = self.num_filters + + # Add unique nuclides from other tally to merged tally + for nuclide in other.nuclides: + if nuclide not in joined_tally.nuclides: + joined_tally.add_score(nuclide) + + # If two tallies can be merged along score bins + elif self._can_merge_scores(other): + join_axis = self.num_filters + 1 + + # Add unique scores from other tally to merged tally + for score in other.scores: + if score not in joined_tally.scores: + joined_tally.add_score(score) + + else: + raise ValueError('Unable to merge tallies') + + # Update filter strides in joined tally + joined_tally._update_filter_strides() + + # Concatenate sum arrays if present in both tallies + if self.sum is not None and other_copy.sum is not None: + self_sum = self.get_reshaped_data(value='sum') + other_sum = other_copy.get_reshaped_data(value='sum') + joined_tally._sum = \ + np.concatenate((self_sum, other_sum), axis=join_axis) + joined_tally._sum = \ + np.reshape(joined_tally._sum, joined_tally.shape) + + # Concatenate sum_sq arrays if present in both tallies + if self.sum_sq is not None and other.sum_sq is not None: + self_sum_sq = self.get_reshaped_data(value='sum_sq') + other_sum_sq = other_copy.get_reshaped_data(value='sum_sq') + joined_tally._sum_sq = \ + np.concatenate((self_sum_sq, other_sum_sq), axis=join_axis) + joined_tally._sum_sq = \ + np.reshape(joined_tally._sum_sq, joined_tally.shape) + + # Concatenate mean arrays if present in both tallies + if self.mean is not None and other.mean is not None: + self_mean = self.get_reshaped_data(value='mean') + other_mean = other_copy.get_reshaped_data(value='mean') + joined_tally._mean = \ + np.concatenate((self_mean, other_mean), axis=join_axis) + joined_tally._mean = \ + np.reshape(joined_tally._mean, joined_tally.shape) + + # Concatenate std. dev. arrays if present in both tallies + if self.std_dev is not None and other.std_dev is not None: + self_std_dev = self.get_reshaped_data(value='std_dev') + other_std_dev = other_copy.get_reshaped_data(value='std_dev') + joined_tally._std_dev = \ + np.concatenate((self_std_dev, other_std_dev), axis=join_axis) + joined_tally._std_dev = \ + np.reshape(joined_tally._std_dev, joined_tally.shape) + + # Sparsify joined tally if both tallies are sparse + joined_tally.sparse = self.sparse and other.sparse + + # Add triggers from other tally to merged tally + for trigger in other.triggers: + joined_tally.add_trigger(trigger) + + return joined_tally + def get_tally_xml(self): """Return XML representation of the tally @@ -1980,8 +2186,7 @@ class Tally(object): # Check that the filters exist in the tally and are not the same if filter1 == filter2: - msg = 'Unable to swap a filter with itself' - raise ValueError(msg) + return elif filter1 not in self.filters: msg = 'Unable to swap "{0}" filter1 in Tally ID="{1}" since it ' \ 'does not contain such a filter'.format(filter1.type, self.id) @@ -2012,6 +2217,8 @@ class Tally(object): else: filter2_bins = [filter2.get_bin(i) for i in range(filter2.num_bins)] + # FIXME: Why doesn't this swap data for sum and sum_sq??? + # Adjust the mean data array to relect the new filter order if self.mean is not None: for bin1, bin2 in itertools.product(filter1_bins, filter2_bins): @@ -2083,6 +2290,8 @@ class Tally(object): self.nuclides[nuclide1_index] = nuclide2 self.nuclides[nuclide2_index] = nuclide1 + # FIXME: Why doesn't this swap data for sum and sum_sq??? + # Adjust the mean data array to relect the new nuclide order if self.mean is not None: nuclide1_mean = self.mean[:, nuclide1_index, :].copy() @@ -2155,6 +2364,8 @@ class Tally(object): self.scores[score1_index] = score2 self.scores[score2_index] = score1 + # FIXME: Why doesn't this swap data for sum and sum_sq??? + # Adjust the mean data array to relect the new nuclide order if self.mean is not None: score1_mean = self.mean[:, :, score1_index].copy() From 76f9c462b583b0567c8fbeca89066527996d8740 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Sat, 6 Feb 2016 15:09:02 -0500 Subject: [PATCH 09/34] Removed old tally merge method --- openmc/tallies.py | 49 ++--------------------------------------------- 1 file changed, 2 insertions(+), 47 deletions(-) diff --git a/openmc/tallies.py b/openmc/tallies.py index dabbeb04ae..51633186e7 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -684,7 +684,7 @@ class Tally(object): Parameters ---------- other : Tally - Tally to check for mergeable scores + Tally to check for mergeable filters """ @@ -829,52 +829,7 @@ class Tally(object): else: return False - def merge(self, tally): - """Merge another tally with this one - - Parameters - ---------- - tally : Tally - Tally to merge with this one - - Returns - ------- - merged_tally : Tally - Merged tallies - - """ - - if not self.can_merge(tally): - msg = 'Unable to merge tally ID="{0}" with ' + \ - '"{1}"'.format(tally.id, self.id) - raise ValueError(msg) - - # Create deep copy of tally to return as merged tally - merged_tally = copy.deepcopy(self) - - # Differentiate Tally with a new auto-generated Tally ID - merged_tally.id = None - - # Merge filters - for i, filter1 in enumerate(merged_tally.filters): - for filter2 in tally.filters: - if filter1 != filter2 and filter1.can_merge(filter2): - merged_filter = filter1.merge(filter2) - merged_tally.filters[i] = merged_filter - break - - # Add unique scores from second tally to merged tally - for score in tally.scores: - if score not in merged_tally.scores: - merged_tally.add_score(score) - - # Add triggers from second tally to merged tally - for trigger in tally.triggers: - merged_tally.add_trigger(trigger) - - return merged_tally - - def join(self, other): + def merge(self, other): """Join another tally with this one Parameters From a2ac93a84389d400b39ad6eccf9bfc3ee4c788a6 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Sat, 6 Feb 2016 20:53:52 -0500 Subject: [PATCH 10/34] Fixed bugs in tally merge method --- openmc/mgxs/mgxs.py | 4 ++ openmc/tallies.py | 124 ++++++++++++++++++++++++-------------------- 2 files changed, 71 insertions(+), 57 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 272d5e0402..a382c629b1 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -953,6 +953,10 @@ class MGXS(object): slice_xs.sparse = self.sparse return slice_xs + # FIXME + def merge(self, other): + raise NotImplementedError('not yet implemented') + def print_xs(self, subdomains='all', nuclides='all', xs_type='macro'): """Print a string representation for the multi-group cross section. diff --git a/openmc/tallies.py b/openmc/tallies.py index 51633186e7..c966fbcf88 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -695,10 +695,11 @@ class Tally(object): # Return False if only one tally has a delayed group filter tally1_dg = self.contains_filter('delayedgroup') tally2_dg = other.contains_filter('delayedgroup') - if sum(tally1_dg, tally2_dg) == 1: + if sum([tally1_dg, tally2_dg]) == 1: return False # Look to see if all filters are the same, or one or more can be merged + merge_filters = False for filter1 in self.filters: mergeable_filter = False @@ -758,9 +759,9 @@ class Tally(object): no_nuclides_match = False # Either all nuclides should match, or none should - if no_nuclides_match: + if no_nuclides_match or all_nuclides_match: return True - if not no_nuclides_match and not all_nuclides_match: + else: return False def _can_merge_scores(self, other): @@ -794,15 +795,23 @@ class Tally(object): else: no_scores_match = False + # Nuclides cannot be specified on 'flux' scores + if 'flux' in self.scores or 'flux' in other.scores: + if self.nuclides != other.nuclides: + return False + # Either all scores should match, or none should - if no_scores_match: + if no_scores_match or all_scores_match: return True - elif not no_scores_match and not all_scores_match: + else: return False def can_merge(self, other): """Determine if another tally can be merged with this one + If results have been loaded from a statepoint, then tallies are only + mergeable along one and only one of filter bins, nuclides or scores. + Parameters ---------- other : Tally @@ -821,39 +830,43 @@ class Tally(object): merge_filters = self._can_merge_filters(other) merge_nuclides = self._can_merge_nuclides(other) merge_scores = self._can_merge_scores(other) + mergeability = [merge_filters, merge_nuclides, merge_scores] - # Tallies are mergeable if only one of filters, nuclides and - # scores is mergeable - if sum(merge_filters, merge_nuclides, merge_scores) == 1: - return True - else: + # If the tally results have been read from the statepoint, we can only + # merge along one of filter bins, scores or nuclides + if self._results_read and sum(mergeability) > 1: return False + else: + return all([merge_filters, merge_nuclides, merge_scores]) def merge(self, other): - """Join another tally with this one + """Merge another tally with this one + + If results have been loaded from a statepoint, then tallies are only + mergeable along one and only one of filter bins, nuclides or scores. Parameters ---------- tally : Tally - Tally to join with this one + Tally to merge with this one Returns ------- - joined_tally : Tally - Joined tallies + merged_tally : Tally + Merged tallies """ if not self.can_merge(other): - msg = 'Unable to join tally ID="{0}" with ' + \ + msg = 'Unable to merge tally ID="{0}" with ' \ '"{1}"'.format(other.id, self.id) raise ValueError(msg) # Create deep copy of tally to return as merged tally - joined_tally = copy.deepcopy(self) + merged_tally = copy.deepcopy(self) # Differentiate Tally with a new auto-generated Tally ID - joined_tally.id = None + merged_tally.id = None # Create deep copy of other tally to use for array concatenation other_copy = copy.deepcopy(other) @@ -865,79 +878,76 @@ class Tally(object): for i, filter1 in enumerate(self.filters): for j, filter2 in enumerate(other.filters): if filter1 != filter2 and filter1.can_merge(filter2): - other_copy._swap_filters(other_copy.filters[i], filter1) - joined_tally.filters[i] = filter1.merge(filter2) - join_axis = i + other_copy._swap_filters(other_copy.filters[i], filter2) + merged_tally.filters[i] = filter1.merge(filter2) + merge_axis = i break # If two tallies can be merged along nuclide bins - elif self._can_merge_nuclides(other): - join_axis = self.num_filters + if self._can_merge_nuclides(other): + merge_axis = self.num_filters # Add unique nuclides from other tally to merged tally for nuclide in other.nuclides: - if nuclide not in joined_tally.nuclides: - joined_tally.add_score(nuclide) + if nuclide not in merged_tally.nuclides: + merged_tally.add_nuclide(nuclide) # If two tallies can be merged along score bins - elif self._can_merge_scores(other): - join_axis = self.num_filters + 1 + if self._can_merge_scores(other): + merge_axis = self.num_filters + 1 # Add unique scores from other tally to merged tally for score in other.scores: - if score not in joined_tally.scores: - joined_tally.add_score(score) + if score not in merged_tally.scores: + merged_tally.add_score(score) - else: - raise ValueError('Unable to merge tallies') - - # Update filter strides in joined tally - joined_tally._update_filter_strides() + # Update filter strides in merged tally + merged_tally._update_filter_strides() # Concatenate sum arrays if present in both tallies if self.sum is not None and other_copy.sum is not None: self_sum = self.get_reshaped_data(value='sum') other_sum = other_copy.get_reshaped_data(value='sum') - joined_tally._sum = \ - np.concatenate((self_sum, other_sum), axis=join_axis) - joined_tally._sum = \ - np.reshape(joined_tally._sum, joined_tally.shape) + merged_tally._sum = \ + np.concatenate((self_sum, other_sum), axis=merge_axis) + merged_tally._sum = \ + np.reshape(merged_tally._sum, merged_tally.shape) # Concatenate sum_sq arrays if present in both tallies if self.sum_sq is not None and other.sum_sq is not None: self_sum_sq = self.get_reshaped_data(value='sum_sq') other_sum_sq = other_copy.get_reshaped_data(value='sum_sq') - joined_tally._sum_sq = \ - np.concatenate((self_sum_sq, other_sum_sq), axis=join_axis) - joined_tally._sum_sq = \ - np.reshape(joined_tally._sum_sq, joined_tally.shape) + merged_tally._sum_sq = \ + np.concatenate((self_sum_sq, other_sum_sq), axis=merge_axis) + merged_tally._sum_sq = \ + np.reshape(merged_tally._sum_sq, merged_tally.shape) # Concatenate mean arrays if present in both tallies if self.mean is not None and other.mean is not None: self_mean = self.get_reshaped_data(value='mean') other_mean = other_copy.get_reshaped_data(value='mean') - joined_tally._mean = \ - np.concatenate((self_mean, other_mean), axis=join_axis) - joined_tally._mean = \ - np.reshape(joined_tally._mean, joined_tally.shape) + merged_tally._mean = \ + np.concatenate((self_mean, other_mean), axis=merge_axis) + merged_tally._mean = \ + np.reshape(merged_tally._mean, merged_tally.shape) # Concatenate std. dev. arrays if present in both tallies if self.std_dev is not None and other.std_dev is not None: self_std_dev = self.get_reshaped_data(value='std_dev') other_std_dev = other_copy.get_reshaped_data(value='std_dev') - joined_tally._std_dev = \ - np.concatenate((self_std_dev, other_std_dev), axis=join_axis) - joined_tally._std_dev = \ - np.reshape(joined_tally._std_dev, joined_tally.shape) + merged_tally._std_dev = \ + np.concatenate((self_std_dev, other_std_dev), axis=merge_axis) + merged_tally._std_dev = \ + np.reshape(merged_tally._std_dev, merged_tally.shape) - # Sparsify joined tally if both tallies are sparse - joined_tally.sparse = self.sparse and other.sparse + # Sparsify merged tally if both tallies are sparse + merged_tally.sparse = self.sparse and other.sparse # Add triggers from other tally to merged tally for trigger in other.triggers: - joined_tally.add_trigger(trigger) + merged_tally.add_trigger(trigger) - return joined_tally + return merged_tally def get_tally_xml(self): """Return XML representation of the tally @@ -2131,10 +2141,10 @@ class Tally(object): """ # Check that results have been read - if not self.derived and self.sum is None: - msg = 'Unable to use tally arithmetic with Tally ID="{0}" ' \ - 'since it does not contain any results.'.format(self.id) - raise ValueError(msg) +# if not self.derived and self.sum is None: +# msg = 'Unable to use tally arithmetic with Tally ID="{0}" ' \ +# 'since it does not contain any results.'.format(self.id) +# raise ValueError(msg) cv.check_type('filter1', filter1, Filter) cv.check_type('filter2', filter2, Filter) From 077eff7f19bbab9a411d5c3356a93b9b7c9279b2 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Sun, 7 Feb 2016 13:24:14 -0500 Subject: [PATCH 11/34] Fixed some bugs in tally merging with introduction of comparison operators for filers and nuclides --- openmc/element.py | 6 ++++ openmc/filter.py | 25 ++++++++++++- openmc/nuclide.py | 6 ++++ openmc/tallies.py | 92 +++++++++++++++++++++++++++++++++++------------ 4 files changed, 106 insertions(+), 23 deletions(-) diff --git a/openmc/element.py b/openmc/element.py index 9f04abfdab..4880dfaf23 100644 --- a/openmc/element.py +++ b/openmc/element.py @@ -57,6 +57,12 @@ class Element(object): def __ne__(self, other): return not self == other + def __lt__(self, other): + return not self > other + + def __hash__(self): + return hash(repr(self)) + def __hash__(self): return hash(repr(self)) diff --git a/openmc/filter.py b/openmc/filter.py index 430b2415f0..21797264b3 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -77,6 +77,23 @@ class Filter(object): def __ne__(self, other): return not self == other + def __gt__(self, other): + if self.type != other.type: + if self.type in _FILTER_TYPES and other.type in _FILTER_TYPES: + delta = _FILTER_TYPES.index(self.type) - \ + _FILTER_TYPES.index(other.type) + return True if delta > 0 else False + else: + return False + else: + if 'energy' in self.type and 'energy' in other.type: + return self.bins[0] >= other.bins[-1] + else: + return max(self.bins) > max(other.bins) + + def __lt__(self, other): + return not self > other + def __hash__(self): return hash(repr(self)) @@ -297,7 +314,13 @@ class Filter(object): # Merge unique filter bins merged_bins = set(np.concatenate((self.bins, other.bins))) - merged_filter.bins = list(sorted(merged_bins)) + + # Sort energy bin edges + if 'energy' in self.type: + merged_bins = sorted(merged_bins) + + # Assign merged bins to merged filter + merged_filter.bins = list(merged_bins) # Count bins in the merged filter if 'energy' in merged_filter.type: diff --git a/openmc/nuclide.py b/openmc/nuclide.py index 01fb2aa459..8e97f1a1c6 100644 --- a/openmc/nuclide.py +++ b/openmc/nuclide.py @@ -60,6 +60,12 @@ class Nuclide(object): def __ne__(self, other): return not self == other + def __gt__(self, other): + return repr(self) > repr(other) + + def __lt__(self, other): + return not self > other + def __hash__(self): return hash(repr(self)) diff --git a/openmc/tallies.py b/openmc/tallies.py index c966fbcf88..d88519ba3b 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -826,18 +826,30 @@ class Tally(object): if self.estimator != other.estimator: return False + equal_filters = sorted(self.filters) == sorted(other.filters) + equal_nuclides = sorted(self.nuclides) == sorted(other.nuclides) + equal_scores = sorted(self.scores) == sorted(other.scores) + equality = [equal_filters, equal_nuclides, equal_scores] + + # If all filters, nuclides and scores match then tallies are mergeable + if equal_filters and equal_nuclides and equal_scores: + return True + # Variables to indicate matching filter bins, nuclides and scores merge_filters = self._can_merge_filters(other) merge_nuclides = self._can_merge_nuclides(other) merge_scores = self._can_merge_scores(other) mergeability = [merge_filters, merge_nuclides, merge_scores] + if not all(mergeability): + return False + # If the tally results have been read from the statepoint, we can only - # merge along one of filter bins, scores or nuclides - if self._results_read and sum(mergeability) > 1: + # at least two of filters, nuclides and scores must match + elif self._results_read and sum(equality) < 2: return False else: - return all([merge_filters, merge_nuclides, merge_scores]) + return True def merge(self, other): """Merge another tally with this one @@ -871,8 +883,16 @@ class Tally(object): # Create deep copy of other tally to use for array concatenation other_copy = copy.deepcopy(other) + # FIXME: document and create vars for merge_filters, etc. + merge_filters = self._can_merge_filters(other) + merge_nuclides = self._can_merge_nuclides(other) + merge_scores = self._can_merge_scores(other) + equal_filters = sorted(self.filters) == sorted(other.filters) + equal_nuclides = sorted(self.nuclides) == sorted(other.nuclides) + equal_scores = sorted(self.scores) == sorted(other.scores) + # If two tallies can be merged along a filter's bins - if self._can_merge_filters(other): + if merge_filters and not equal_filters: # Search for mergeable filters for i, filter1 in enumerate(self.filters): @@ -880,12 +900,14 @@ class Tally(object): if filter1 != filter2 and filter1.can_merge(filter2): other_copy._swap_filters(other_copy.filters[i], filter2) merged_tally.filters[i] = filter1.merge(filter2) + join_right = filter1 < filter2 merge_axis = i break # If two tallies can be merged along nuclide bins - if self._can_merge_nuclides(other): + if merge_nuclides and not equal_nuclides: merge_axis = self.num_filters + join_right = True # Add unique nuclides from other tally to merged tally for nuclide in other.nuclides: @@ -893,8 +915,9 @@ class Tally(object): merged_tally.add_nuclide(nuclide) # If two tallies can be merged along score bins - if self._can_merge_scores(other): + if merge_scores and not equal_scores: merge_axis = self.num_filters + 1 + join_right = True # Add unique scores from other tally to merged tally for score in other.scores: @@ -908,37 +931,57 @@ class Tally(object): if self.sum is not None and other_copy.sum is not None: self_sum = self.get_reshaped_data(value='sum') other_sum = other_copy.get_reshaped_data(value='sum') - merged_tally._sum = \ - np.concatenate((self_sum, other_sum), axis=merge_axis) - merged_tally._sum = \ - np.reshape(merged_tally._sum, merged_tally.shape) + + if join_right: + merged_sum = \ + np.concatenate((self_sum, other_sum), axis=merge_axis) + else: + merged_sum = \ + np.concatenate((other_sum, self_sum), axis=merge_axis) + + merged_tally._sum = np.reshape(merged_sum, merged_tally.shape) # Concatenate sum_sq arrays if present in both tallies if self.sum_sq is not None and other.sum_sq is not None: self_sum_sq = self.get_reshaped_data(value='sum_sq') other_sum_sq = other_copy.get_reshaped_data(value='sum_sq') - merged_tally._sum_sq = \ - np.concatenate((self_sum_sq, other_sum_sq), axis=merge_axis) - merged_tally._sum_sq = \ - np.reshape(merged_tally._sum_sq, merged_tally.shape) + + if join_right: + merged_sum_sq = \ + np.concatenate((self_sum_sq, other_sum_sq), axis=merge_axis) + else: + merged_sum_sq = \ + np.concatenate((other_sum_sq, self_sum_sq), axis=merge_axis) + + merged_tally._sum_sq = np.reshape(merged_sum_sq, merged_tally.shape) # Concatenate mean arrays if present in both tallies if self.mean is not None and other.mean is not None: self_mean = self.get_reshaped_data(value='mean') other_mean = other_copy.get_reshaped_data(value='mean') - merged_tally._mean = \ - np.concatenate((self_mean, other_mean), axis=merge_axis) - merged_tally._mean = \ - np.reshape(merged_tally._mean, merged_tally.shape) + + if join_right: + merged_mean = \ + np.concatenate((self_mean, other_mean), axis=merge_axis) + else: + merged_mean = \ + np.concatenate((other_mean, self_mean), axis=merge_axis) + + merged_tally._mean = np.reshape(merged_mean, merged_tally.shape) # Concatenate std. dev. arrays if present in both tallies if self.std_dev is not None and other.std_dev is not None: self_std_dev = self.get_reshaped_data(value='std_dev') other_std_dev = other_copy.get_reshaped_data(value='std_dev') - merged_tally._std_dev = \ - np.concatenate((self_std_dev, other_std_dev), axis=merge_axis) - merged_tally._std_dev = \ - np.reshape(merged_tally._std_dev, merged_tally.shape) + + if join_right: + merged_std_dev = \ + np.concatenate((self_std_dev, other_std_dev), axis=merge_axis) + else: + merged_std_dev = \ + np.concatenate((other_std_dev, self_std_dev), axis=merge_axis) + + merged_tally._std_dev = np.reshape(merged_std_dev, merged_tally.shape) # Sparsify merged tally if both tallies are sparse merged_tally.sparse = self.sparse and other.sparse @@ -2878,7 +2921,12 @@ class Tally(object): 'since it does not contain any results.'.format(self.id) raise ValueError(msg) + # Create deep copy of tally to return as sliced tally new_tally = copy.deepcopy(self) + + # Differentiate Tally with a new auto-generated Tally ID + new_tally.id = None + new_tally.sparse = False if not self.derived and self.sum is not None: From 184ed3733b2e81463b1f83aaa98b81ce0229f3a3 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Mon, 8 Feb 2016 00:36:49 -0500 Subject: [PATCH 12/34] Fixed bugs in pandas dataframe construction for AggregateFilter --- openmc/arithmetic.py | 120 +++++++++++++++--- openmc/filter.py | 34 +++-- openmc/mgxs/mgxs.py | 1 - openmc/tallies.py | 34 ++--- .../results_true.dat | 8 +- 5 files changed, 146 insertions(+), 51 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index f6f701d095..13f300968a 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -1,5 +1,7 @@ import sys +import copy from numbers import Integral +from collections import Iterable import numpy as np @@ -430,7 +432,7 @@ class CrossFilter(object): filter_index = left_index * self.right_filter.num_bins + right_index return filter_index - def get_pandas_dataframe(self, datasize, summary=None): + def get_pandas_dataframe(self, data_size, summary=None): """Builds a Pandas DataFrame for the CrossFilter's bins. This method constructs a Pandas DataFrame object for the CrossFilter @@ -445,7 +447,7 @@ class CrossFilter(object): Parameters ---------- - datasize : Integral + data_size : Integral The total number of bins in the tally corresponding to this filter summary : None or Summary An optional Summary object to be used to construct columns for @@ -472,12 +474,12 @@ class CrossFilter(object): # If left and right filters are identical, do not combine bins if self.left_filter == self.right_filter: - df = self.left_filter.get_pandas_dataframe(datasize, summary) + df = self.left_filter.get_pandas_dataframe(data_size, summary) # If left and right filters are different, combine their bins else: - left_df = self.left_filter.get_pandas_dataframe(datasize, summary) - right_df = self.right_filter.get_pandas_dataframe(datasize, summary) + left_df = self.left_filter.get_pandas_dataframe(data_size, summary) + right_df = self.right_filter.get_pandas_dataframe(data_size, summary) left_df = left_df.astype(str) right_df = right_df.astype(str) df = '(' + left_df + ' ' + self.binary_op + ' ' + right_df + ')' @@ -713,6 +715,13 @@ class AggregateFilter(object): def __ne__(self, other): return not self == other + def __gt__(self, other): + # FIXME + return False + + def __lt__(self, other): + return not self > other + def __repr__(self): string = 'AggregateFilter\n' string += '{0: <16}{1}{2}\n'.format('\tType', '=\t', self.type) @@ -757,7 +766,7 @@ class AggregateFilter(object): @property def num_bins(self): - return 1 if self.aggregate_filter else 0 + return len(self.bins) if self.aggregate_filter else 0 @property def stride(self): @@ -779,8 +788,10 @@ class AggregateFilter(object): @bins.setter def bins(self, bins): - cv.check_iterable_type('bins', bins, (Integral, tuple)) - self._bins = bins + cv.check_iterable_type('bins', bins, Iterable) + self._bins = [] + for bin in bins: + self._bins.append(tuple(bin)) @aggregate_op.setter def aggregate_op(self, aggregate_op): @@ -825,9 +836,9 @@ class AggregateFilter(object): '"{0}" is not one of the bins'.format(filter_bin) raise ValueError(msg) else: - return 0 + return self.bins.index(filter_bin) - def get_pandas_dataframe(self, datasize, summary=None): + def get_pandas_dataframe(self, data_size, summary=None): """Builds a Pandas DataFrame for the AggregateFilter's bins. This method constructs a Pandas DataFrame object for the AggregateFilter @@ -836,7 +847,7 @@ class AggregateFilter(object): Parameters ---------- - datasize : Integral + data_size : Integral The total number of bins in the tally corresponding to this filter summary : None or Summary An optional Summary object to be used to construct columns for @@ -864,14 +875,85 @@ class AggregateFilter(object): import pandas as pd - # Construct a sring representing the filter aggregation - aggregate_bin = '{0}('.format(self.aggregate_op) - aggregate_bin += ', '.join(map(str, self.bins)) + ')' + # Create NumPy array of the bin tuples for repeating / tiling + filter_bins = np.empty(self.num_bins, dtype=tuple) + for i, bin in enumerate(self.bins): + filter_bins[i] = bin - # Construct NumPy array of bin repeated for each element in dataframe - aggregate_bin_array = np.array([aggregate_bin]) - aggregate_bin_array = np.repeat(aggregate_bin_array, datasize) + # Repeat and tile bins as needed for DataFrame + filter_bins = np.repeat(filter_bins, self.stride) + tile_factor = data_size / len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) - # Construct Pandas DataFrame for the AggregateFilter - df = pd.DataFrame({self.type: aggregate_bin_array}) + # Create DataFrame with aggregated bins + df = pd.DataFrame({self.type: filter_bins}) return df + + def can_merge(self, other): + """Determine if AggregateFilter can be merged with another. + + Parameters + ---------- + other : AggregateFilter + Filter to compare with + + Returns + ------- + bool + Whether the filter can be merged + + """ + + if not isinstance(other, AggregateFilter): + return False + + # Filters must be of the same type + elif self.type != other.type: + return False + + # None of the bins in this filter should match in the other filter + for bin in self.bins: + if bin in other.bins: + return False + + # None of the bins in the other filter should match in this filter + for bin in other.bins: + if bin in self.bins: + return False + + # If all conditional checks passed then filters are mergeable + return True + + def merge(self, other): + """Merge this aggregatefilter with another. + + Parameters + ---------- + other : AggregateFilter + Filter to merge with + + Returns + ------- + merged_filter : AggregateFilter + Filter resulting from the merge + + """ + + if not self.can_merge(other): + msg = 'Unable to merge "{0}" with "{1}" ' \ + 'filters'.format(self.type, other.type) + raise ValueError(msg) + + # Create deep copy of filter to return as merged filter + merged_filter = copy.deepcopy(self) + + # Merge unique filter bins + merged_bins = self.bins + other.bins + + # Sort energy bin edges + if 'energy' in self.type: + merged_bins = sorted(merged_bins) + + # Assign merged bins to merged filter + merged_filter.bins = list(merged_bins) + return merged_filter \ No newline at end of file diff --git a/openmc/filter.py b/openmc/filter.py index 21797264b3..f8484ec767 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -263,11 +263,11 @@ class Filter(object): return False # Filters must be of the same type - elif self.type != other.type: + if self.type != other.type: return False # Distribcell filters cannot have more than one bin - elif self.type == 'distribcell': + if self.type == 'distribcell': return False # Mesh filters cannot have more than one bin @@ -289,6 +289,24 @@ class Filter(object): else: return True + ''' + # FIXME: Should all bins be completely separate??? + # FIMXE: This is necessary if merging will choose out unique bins + else: + # None of the bins in this filter should match in the other filter + for bin in self.bins: + if bin in other.bins: + return False + + # None of the bins in the other filter should match in this filter + for bin in other.bins: + if bin in self.bins: + return False + + # If all conditional checks pass then filters are mergeable + return True + ''' + def merge(self, other): """Merge this filter with another. @@ -313,7 +331,8 @@ class Filter(object): merged_filter = copy.deepcopy(self) # Merge unique filter bins - merged_bins = set(np.concatenate((self.bins, other.bins))) + merged_bins = np.concatenate((self.bins, other.bins)) + merged_bins = np.unique(merged_bins) # Sort energy bin edges if 'energy' in self.type: @@ -557,14 +576,8 @@ class Filter(object): """ - # Attempt to import Pandas - try: - import pandas as pd - except ImportError: - msg = 'The Pandas Python package must be installed on your system' - raise ImportError(msg) - # Initialize Pandas DataFrame + import pandas as pd df = pd.DataFrame() # mesh filters @@ -743,7 +756,6 @@ class Filter(object): filter_bins = np.repeat(filter_bins, self.stride) tile_factor = data_size / len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) - filter_bins = filter_bins df = pd.DataFrame({self.type : filter_bins}) # If OpenCG level info DataFrame was created, concatenate diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index a382c629b1..b82426e7df 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -1368,7 +1368,6 @@ class MGXS(object): # Sort the dataframe by domain type id (e.g., distribcell id) and # energy groups such that data is from fast to thermal df.sort([self.domain_type] + columns, inplace=True) - return df diff --git a/openmc/tallies.py b/openmc/tallies.py index d88519ba3b..c04ee001a7 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -301,7 +301,7 @@ class Tally(object): @property def sum(self): - if not self._sp_filename: + if not self._sp_filename or self.derived: return None if not self._results_read: @@ -924,6 +924,17 @@ class Tally(object): if score not in merged_tally.scores: merged_tally.add_score(score) + # Add triggers from other tally to merged tally + for trigger in other.triggers: + merged_tally.add_trigger(trigger) + + # If results have not been read, then return tally for input generation + if self._sp_filename is None: + return merged_tally + #Otherwise, this is a derived tally which needs merged results arrays + else: + self._derived = True + # Update filter strides in merged tally merged_tally._update_filter_strides() @@ -986,10 +997,6 @@ class Tally(object): # Sparsify merged tally if both tallies are sparse merged_tally.sparse = self.sparse and other.sparse - # Add triggers from other tally to merged tally - for trigger in other.triggers: - merged_tally.add_trigger(trigger) - return merged_tally def get_tally_xml(self): @@ -1538,14 +1545,8 @@ class Tally(object): 'Summary info'.format(self.id) raise KeyError(msg) - # Attempt to import Pandas - try: - import pandas as pd - except ImportError: - msg = 'The Pandas Python package must be installed on your system' - raise ImportError(msg) - # Initialize a pandas dataframe for the tally data + import pandas as pd df = pd.DataFrame() # Find the total length of the tally data array @@ -2189,8 +2190,8 @@ class Tally(object): # 'since it does not contain any results.'.format(self.id) # raise ValueError(msg) - cv.check_type('filter1', filter1, Filter) - cv.check_type('filter2', filter2, Filter) + cv.check_type('filter1', filter1, (Filter, CrossFilter, AggregateFilter)) + cv.check_type('filter2', filter2, (Filter, CrossFilter, AggregateFilter)) # Check that the filters exist in the tally and are not the same if filter1 == filter2: @@ -2923,6 +2924,7 @@ class Tally(object): # Create deep copy of tally to return as sliced tally new_tally = copy.deepcopy(self) + new_tally._derived = True # Differentiate Tally with a new auto-generated Tally ID new_tally.id = None @@ -3094,7 +3096,7 @@ class Tally(object): # Add AggregateFilter to the tally sum if not remove_filter: filter_sum = \ - AggregateFilter(self_filter, filter_bins, 'sum') + AggregateFilter(self_filter, [tuple(filter_bins)], 'sum') tally_sum.add_filter(filter_sum) # Add a copy of each filter not summed across to the tally sum @@ -3243,7 +3245,7 @@ class Tally(object): # Add AggregateFilter to the tally avg if not remove_filter: filter_sum = \ - AggregateFilter(self_filter, filter_bins, 'avg') + AggregateFilter(self_filter, [tuple(filter_bins)], 'avg') tally_avg.add_filter(filter_sum) # Add a copy of each filter not averaged across to the tally avg diff --git a/tests/test_mgxs_library_distribcell/results_true.dat b/tests/test_mgxs_library_distribcell/results_true.dat index 4936da4cec..7b4be0f468 100644 --- a/tests/test_mgxs_library_distribcell/results_true.dat +++ b/tests/test_mgxs_library_distribcell/results_true.dat @@ -1,5 +1,5 @@ sum(distribcell) group in nuclide mean std. dev. -0 sum(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ... 1 total 0.720213 1.424323 sum(distribcell) group in nuclide mean std. dev. -0 sum(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ... 1 total 0 0 sum(distribcell) group in group out nuclide mean std. dev. -0 sum(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ... 1 1 total 0.70466 1.403916 sum(distribcell) group out nuclide mean std. dev. -0 sum(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ... 1 total 0 0 \ No newline at end of file +0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 total 0.720213 1.424323 sum(distribcell) group in nuclide mean std. dev. +0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 total 0 0 sum(distribcell) group in group out nuclide mean std. dev. +0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 1 total 0.70466 1.403916 sum(distribcell) group out nuclide mean std. dev. +0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 total 0 0 \ No newline at end of file From ef60d9d2f5e22a5d23654f23906a553c52d79c81 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Mon, 8 Feb 2016 15:40:58 -0500 Subject: [PATCH 13/34] Implemented MGXS merging --- openmc/filter.py | 18 --------- openmc/mgxs/groups.py | 67 +++++++++++++++++++++++++++++++- openmc/mgxs/mgxs.py | 90 +++++++++++++++++++++++++++++++++++++++++-- openmc/tallies.py | 6 ++- 4 files changed, 157 insertions(+), 24 deletions(-) diff --git a/openmc/filter.py b/openmc/filter.py index f8484ec767..2c310bebb4 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -289,24 +289,6 @@ class Filter(object): else: return True - ''' - # FIXME: Should all bins be completely separate??? - # FIMXE: This is necessary if merging will choose out unique bins - else: - # None of the bins in this filter should match in the other filter - for bin in self.bins: - if bin in other.bins: - return False - - # None of the bins in the other filter should match in this filter - for bin in other.bins: - if bin in self.bins: - return False - - # If all conditional checks pass then filters are mergeable - return True - ''' - def merge(self, other): """Merge this filter with another. diff --git a/openmc/mgxs/groups.py b/openmc/mgxs/groups.py index 3436c0e037..16e94ee451 100644 --- a/openmc/mgxs/groups.py +++ b/openmc/mgxs/groups.py @@ -54,10 +54,12 @@ class EnergyGroups(object): def __eq__(self, other): if not isinstance(other, EnergyGroups): return False - elif self.group_edges != other.group_edges: + elif self.num_groups != other.num_groups: return False - else: + elif np.allclose(self.group_edges, other.group_edges): return True + else: + return False def __ne__(self, other): return not self == other @@ -236,3 +238,64 @@ class EnergyGroups(object): condensed_groups.group_edges = group_edges return condensed_groups + + def can_merge(self, other): + """Determine if energy groups can be merged with another. + + Parameters + ---------- + other : EnergyGroups + EnergyGroups to compare with + + Returns + ------- + bool + Whether the energy groups can be merged + + """ + + if not isinstance(other, EnergyGroups): + return False + + # If the energy group structures match then groups are mergeable + if self == other: + return True + + # This low energy edge coincides with other's high energy edge + if self.group_edges[0] == other.group_edges[-1]: + return True + # This high energy edge coincides with other's low energy edge + elif self.group_edges[-1] == other.group_edges[0]: + return True + else: + return False + + def merge(self, other): + """Merge this energy groups with another. + + Parameters + ---------- + other : EnergyGroups + EnergyGroups to merge with + + Returns + ------- + merged_groups : EnergyGroups + EnergyGroups resulting from the merge + + """ + + if not self.can_merge(other): + raise ValueError('Unable to merge energy groups') + + # Create deep copy to return as merged energy groups + merged_groups = copy.deepcopy(self) + + # Merge unique filter bins + merged_edges = np.concatenate((self.group_edges, other.group_edges)) + merged_edges = np.unique(merged_edges) + merged_edges = sorted(merged_edges) + + # Assign merged edges to merged groups + merged_groups.group_edges = list(merged_edges) + return merged_groups \ No newline at end of file diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index b82426e7df..b4c107139d 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -155,7 +155,7 @@ class MGXS(object): clone._name = self.name clone._rxn_type = self.rxn_type clone._by_nuclide = self.by_nuclide - clone._nuclides = self._nuclides + clone._nuclides = copy.deepcopy(self._nuclides) clone._domain = self.domain clone._domain_type = self.domain_type clone._energy_groups = copy.deepcopy(self.energy_groups, memo) @@ -953,9 +953,93 @@ class MGXS(object): slice_xs.sparse = self.sparse return slice_xs - # FIXME + def can_merge(self, other): + """Determine if another MGXS can be merged with this one + + If results have been loaded from a statepoint, then MGXS are only + mergeable along one and only one of enegy groups or nuclides. + + Parameters + ---------- + other : MGXS + MGXS to check for merging + + """ + + if not isinstance(other, type(self)): + return False + + # Compare reaction type, energy groups, nuclides, domain type + if self.rxn_type != other.rxn_type: + return False + elif not self.energy_groups.can_merge(other.energy_groups): + return False + elif self.by_nuclide != other.by_nuclide: + return False + elif self.domain_type != other.domain_type: + return False + elif 'distribcell' not in self.domain_type and self.domain != other.domain: + return False + elif len(self.tallies) != len(other.tallies): + return False + + # See if each individual tally is mergeable + for tally_key in self.tallies: + if not self.tallies[tally_key].can_merge(other.tallies[tally_key]): + return False + + # If all conditionals pass then MGXS are mergeable + return True + def merge(self, other): - raise NotImplementedError('not yet implemented') + """Merge another MGXS with this one + + If results have been loaded from a statepoint, then MGXS are only + mergeable along one and only one of energy groups or nuclides. + + Parameters + ---------- + other : MGXS + MGXS to merge with this one + + Returns + ------- + merged_mgxs : MGXS + Merged MGXS + + """ + + if not self.can_merge(other): + raise ValueError('Unable to merge MGXS') + + # Create deep copy of tally to return as merged tally + merged_mgxs = copy.deepcopy(self) + merged_mgxs._rxn_rate_tally = None + merged_mgxs._xs_tally = None + + # Merge energy groups + if self.energy_groups != other.energy_groups: + merged_groups = self.energy_groups.merge(other.energy_groups) + merged_mgxs.energy_groups = merged_groups + + # Merge nuclides + if self.nuclides != other.nuclides: + + # The nuclides must be mutually exclusive + for nuclide in self.nuclides: + if nuclide in other.nuclides: + msg = 'Unable to merge MGXS with shared nuclides' + raise ValueError(msg) + + # Concatenate lists of nuclides for the merged MGXS + merged_mgxs.nuclides = self.nuclides + other.nuclides + + # Merge tallies + for tally_key in self.tallies: + merged_tally = self.tallies[tally_key].merge(other.tallies[tally_key]) + merged_mgxs.tallies[tally_key] = merged_tally + + return merged_mgxs def print_xs(self, subdomains='all', nuclides='all', xs_type='macro'): """Print a string representation for the multi-group cross section. diff --git a/openmc/tallies.py b/openmc/tallies.py index c04ee001a7..6b04403329 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -859,7 +859,7 @@ class Tally(object): Parameters ---------- - tally : Tally + other : Tally Tally to merge with this one Returns @@ -880,6 +880,10 @@ class Tally(object): # Differentiate Tally with a new auto-generated Tally ID merged_tally.id = None + # If the two tallies are equal, simpy return copy + if self == other: + return merged_tally + # Create deep copy of other tally to use for array concatenation other_copy = copy.deepcopy(other) From bbbb115196b479a117d6dc48021c1a2bdb62bbe8 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Thu, 11 Feb 2016 12:07:23 -0500 Subject: [PATCH 14/34] Implemented __gt__ method for AggregateFilter --- openmc/arithmetic.py | 20 +++++++++++++------- openmc/element.py | 3 +++ openmc/mgxs/mgxs.py | 5 +++-- openmc/tallies.py | 6 ------ 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index 13f300968a..bbb303b140 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -647,7 +647,7 @@ class AggregateNuclide(object): @nuclides.setter def nuclides(self, nuclides): cv.check_iterable_type('nuclides', nuclides, - (basestring, Nuclide, CrossNuclide)) + (basestring, Nuclide, CrossNuclide)) self._nuclides = nuclides @aggregate_op.setter @@ -716,8 +716,16 @@ class AggregateFilter(object): return not self == other def __gt__(self, other): - # FIXME - return False + if self.type != other.type: + if self.aggregate_filter.type in _FILTER_TYPES and \ + other.aggregate_filter.type in _FILTER_TYPES: + delta = _FILTER_TYPES.index(self.aggregate_filter.type) - \ + _FILTER_TYPES.index(other.aggregate_filter.type) + return True if delta > 0 else False + else: + return False + else: + return False def __lt__(self, other): return not self > other @@ -789,9 +797,7 @@ class AggregateFilter(object): @bins.setter def bins(self, bins): cv.check_iterable_type('bins', bins, Iterable) - self._bins = [] - for bin in bins: - self._bins.append(tuple(bin)) + self._bins = map(tuple, bins) @aggregate_op.setter def aggregate_op(self, aggregate_op): @@ -956,4 +962,4 @@ class AggregateFilter(object): # Assign merged bins to merged filter merged_filter.bins = list(merged_bins) - return merged_filter \ No newline at end of file + return merged_filter diff --git a/openmc/element.py b/openmc/element.py index 4880dfaf23..dda110ea7a 100644 --- a/openmc/element.py +++ b/openmc/element.py @@ -57,6 +57,9 @@ class Element(object): def __ne__(self, other): return not self == other + def __gt__(self, other): + return repr(self) > repr(other) + def __lt__(self, other): return not self > other diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index b4c107139d..fb70b1bc8d 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -1917,7 +1917,8 @@ class ScatterMatrixXS(MGXS): self._correction = correction def get_slice(self, nuclides=[], groups=[]): - """Build a sliced MGXS for the specified nuclides and energy groups. + """Build a sliced ScatterMatrix for the specified nuclides and + energy groups. This method constructs a new MGXS to encapsulate a subset of the data represented by this MGXS. The subset of data to include in the tally @@ -2308,7 +2309,7 @@ class Chi(MGXS): return self._xs_tally def get_slice(self, nuclides=[], groups=[]): - """Build a sliced MGXS for the specified nuclides and energy groups. + """Build a sliced Chi for the specified nuclides and energy groups. This method constructs a new MGXS to encapsulate a subset of the data represented by this MGXS. The subset of data to include in the tally diff --git a/openmc/tallies.py b/openmc/tallies.py index 6b04403329..b15e730386 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -2188,12 +2188,6 @@ class Tally(object): """ - # Check that results have been read -# if not self.derived and self.sum is None: -# msg = 'Unable to use tally arithmetic with Tally ID="{0}" ' \ -# 'since it does not contain any results.'.format(self.id) -# raise ValueError(msg) - cv.check_type('filter1', filter1, (Filter, CrossFilter, AggregateFilter)) cv.check_type('filter2', filter2, (Filter, CrossFilter, AggregateFilter)) From 23353fa097ec736a813386ceecd1b89cd26173dc Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Thu, 11 Feb 2016 12:59:14 -0500 Subject: [PATCH 15/34] Added new tally slice and merge test --- openmc/arithmetic.py | 2 +- tests/test_tally_slice_merge/inputs_true.dat | 1 + tests/test_tally_slice_merge/results_true.dat | 49 ++++++ .../test_tally_slice_merge.py | 165 ++++++++++++++++++ 4 files changed, 216 insertions(+), 1 deletion(-) create mode 100644 tests/test_tally_slice_merge/inputs_true.dat create mode 100644 tests/test_tally_slice_merge/results_true.dat create mode 100644 tests/test_tally_slice_merge/test_tally_slice_merge.py diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index bbb303b140..4ddf3b1f91 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -797,7 +797,7 @@ class AggregateFilter(object): @bins.setter def bins(self, bins): cv.check_iterable_type('bins', bins, Iterable) - self._bins = map(tuple, bins) + self._bins = list(map(tuple, bins)) @aggregate_op.setter def aggregate_op(self, aggregate_op): diff --git a/tests/test_tally_slice_merge/inputs_true.dat b/tests/test_tally_slice_merge/inputs_true.dat new file mode 100644 index 0000000000..29f0f1d827 --- /dev/null +++ b/tests/test_tally_slice_merge/inputs_true.dat @@ -0,0 +1 @@ +8d1ab9e4add51b99045e990ac9c3dad9447e9720d811bc430d4bfdd7c2c035424bcb7750e4a4d0ec0460ea1ef4be46ac58372ed01d55f5d8cfeebbce75559066 \ No newline at end of file diff --git a/tests/test_tally_slice_merge/results_true.dat b/tests/test_tally_slice_merge/results_true.dat new file mode 100644 index 0000000000..6aeb5735a8 --- /dev/null +++ b/tests/test_tally_slice_merge/results_true.dat @@ -0,0 +1,49 @@ + energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 21 U-235 fission 0.098638 0.009195 energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 21 U-235 nu-fission 0.240351 0.022405 energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 21 U-238 fission 1.371663e-07 1.284884e-08 energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 21 U-238 nu-fission 3.418304e-07 3.202044e-08 energy [MeV] cell nuclide score mean std. dev. +0 (6.3e-07 - 2.0e+01) 21 U-235 fission 0.027879 0.000602 energy [MeV] cell nuclide score mean std. dev. +0 (6.3e-07 - 2.0e+01) 21 U-235 nu-fission 0.068241 0.001458 energy [MeV] cell nuclide score mean std. dev. +0 (6.3e-07 - 2.0e+01) 21 U-238 fission 0.016638 0.001146 energy [MeV] cell nuclide score mean std. dev. +0 (6.3e-07 - 2.0e+01) 21 U-238 nu-fission 0.045776 0.003342 energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 27 U-235 fission 0.057752 0.004818 energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 27 U-235 nu-fission 0.140724 0.011739 energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 27 U-238 fission 8.177167e-08 7.061683e-09 energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 27 U-238 nu-fission 2.037822e-07 1.759834e-08 energy [MeV] cell nuclide score mean std. dev. +0 (6.3e-07 - 2.0e+01) 27 U-235 fission 0.01763 0.001937 energy [MeV] cell nuclide score mean std. dev. +0 (6.3e-07 - 2.0e+01) 27 U-235 nu-fission 0.04314 0.004737 energy [MeV] cell nuclide score mean std. dev. +0 (6.3e-07 - 2.0e+01) 27 U-238 fission 0.009883 0.001934 energy [MeV] cell nuclide score mean std. dev. +0 (6.3e-07 - 2.0e+01) 27 U-238 nu-fission 0.027068 0.005207 energy [MeV] cell nuclide score mean std. dev. +0 (0.0e+00 - 6.3e-07) 21 U-235 fission 9.863775e-02 9.194846e-03 +1 (0.0e+00 - 6.3e-07) 21 U-235 nu-fission 2.403506e-01 2.240508e-02 +2 (0.0e+00 - 6.3e-07) 21 U-238 fission 1.371663e-07 1.284884e-08 +3 (0.0e+00 - 6.3e-07) 21 U-238 nu-fission 3.418304e-07 3.202044e-08 +4 (0.0e+00 - 6.3e-07) 27 U-235 fission 5.775195e-02 4.817512e-03 +5 (0.0e+00 - 6.3e-07) 27 U-235 nu-fission 1.407242e-01 1.173883e-02 +6 (0.0e+00 - 6.3e-07) 27 U-238 fission 8.177167e-08 7.061683e-09 +7 (0.0e+00 - 6.3e-07) 27 U-238 nu-fission 2.037822e-07 1.759834e-08 +8 (6.3e-07 - 2.0e+01) 21 U-235 fission 2.787911e-02 6.020399e-04 +9 (6.3e-07 - 2.0e+01) 21 U-235 nu-fission 6.824140e-02 1.457590e-03 +10 (6.3e-07 - 2.0e+01) 21 U-238 fission 1.663756e-02 1.145703e-03 +11 (6.3e-07 - 2.0e+01) 21 U-238 nu-fission 4.577562e-02 3.342394e-03 +12 (6.3e-07 - 2.0e+01) 27 U-235 fission 1.763014e-02 1.937151e-03 +13 (6.3e-07 - 2.0e+01) 27 U-235 nu-fission 4.313951e-02 4.737423e-03 +14 (6.3e-07 - 2.0e+01) 27 U-238 fission 9.883451e-03 1.933519e-03 +15 (6.3e-07 - 2.0e+01) 27 U-238 nu-fission 2.706776e-02 5.206818e-03 sum(distribcell) energy [MeV] nuclide score mean std. dev. +0 (0, 100, 2000, 30000) (0.0e+00 - 6.3e-07) U-235 fission 0 0 +1 (0, 100, 2000, 30000) (0.0e+00 - 6.3e-07) U-235 nu-fission 0 0 +2 (0, 100, 2000, 30000) (0.0e+00 - 6.3e-07) U-238 fission 0 0 +3 (0, 100, 2000, 30000) (0.0e+00 - 6.3e-07) U-238 nu-fission 0 0 +4 (0, 100, 2000, 30000) (6.3e-07 - 2.0e+01) U-235 fission 0 0 +5 (0, 100, 2000, 30000) (6.3e-07 - 2.0e+01) U-235 nu-fission 0 0 +6 (0, 100, 2000, 30000) (6.3e-07 - 2.0e+01) U-238 fission 0 0 +7 (0, 100, 2000, 30000) (6.3e-07 - 2.0e+01) U-238 nu-fission 0 0 +8 (500, 5000, 50000) (0.0e+00 - 6.3e-07) U-235 fission 0 0 +9 (500, 5000, 50000) (0.0e+00 - 6.3e-07) U-235 nu-fission 0 0 +10 (500, 5000, 50000) (0.0e+00 - 6.3e-07) U-238 fission 0 0 +11 (500, 5000, 50000) (0.0e+00 - 6.3e-07) U-238 nu-fission 0 0 +12 (500, 5000, 50000) (6.3e-07 - 2.0e+01) U-235 fission 0 0 +13 (500, 5000, 50000) (6.3e-07 - 2.0e+01) U-235 nu-fission 0 0 +14 (500, 5000, 50000) (6.3e-07 - 2.0e+01) U-238 fission 0 0 +15 (500, 5000, 50000) (6.3e-07 - 2.0e+01) U-238 nu-fission 0 0 \ No newline at end of file diff --git a/tests/test_tally_slice_merge/test_tally_slice_merge.py b/tests/test_tally_slice_merge/test_tally_slice_merge.py new file mode 100644 index 0000000000..403f1827dd --- /dev/null +++ b/tests/test_tally_slice_merge/test_tally_slice_merge.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python + +import os +import sys +import glob +import hashlib +import itertools +sys.path.insert(0, os.pardir) +from testing_harness import PyAPITestHarness +import openmc + + +class TallySliceMergeTestHarness(PyAPITestHarness): + def _build_inputs(self): + + # The summary.h5 file needs to be created to read in the tallies + self._input_set.settings.output = {'summary': True} + + # Initialize the tallies file + tallies_file = openmc.TalliesFile() + + # Define nuclides and scores to add to both tallies + self.nuclides = ['U-235', 'U-238'] + self.scores = ['fission', 'nu-fission'] + + # Define filters for energy and spatial domain + + low_energy = openmc.Filter(type='energy', bins=[0., 0.625e-6]) + high_energy = openmc.Filter(type='energy', bins=[0.625e-6, 20.]) + merged_energies = low_energy.merge(high_energy) + + cell_21 = openmc.Filter(type='cell', bins=[21]) + cell_27 = openmc.Filter(type='cell', bins=[27]) + distribcell_filter = openmc.Filter(type='distribcell', bins=[21]) + + self.cell_filters = [cell_21, cell_27] + self.energy_filters = [low_energy, high_energy] + + # Initialize cell tallies with filters, nuclides and scores + tallies = [] + for cell_filter in self.energy_filters: + for energy_filter in self.cell_filters: + for nuclide in self.nuclides: + for score in self.scores: + tally = openmc.Tally() + tally.estimator = 'tracklength' + tally.add_score(score) + tally.add_nuclide(nuclide) + tally.add_filter(cell_filter) + tally.add_filter(energy_filter) + tallies.append(tally) + + # Merge all cell tallies together + while len(tallies) != 1: + halfway = int(len(tallies) / 2) + zip_split = zip(tallies[:halfway], tallies[halfway:]) + tallies = list(map(lambda xy: xy[0].merge(xy[1]), zip_split)) + + # Specify a name for the tally + tallies[0].name = 'cell tally' + + # Initialize a distribcell tally + distribcell_tally = openmc.Tally(name='distribcell tally') + distribcell_tally.estimator = 'tracklength' + distribcell_tally.add_filter(distribcell_filter) + distribcell_tally.add_filter(merged_energies) + for score in self.scores: + distribcell_tally.add_score(score) + for nuclide in self.nuclides: + distribcell_tally.add_nuclide(nuclide) + + # Add tallies to a TalliesFile + tallies_file = openmc.TalliesFile() + tallies_file.add_tally(tallies[0]) + tallies_file.add_tally(distribcell_tally) + + # Export tallies to file + self._input_set.tallies = tallies_file + super(TallySliceMergeTestHarness, self)._build_inputs() + + def _get_results(self, hash_output=False): + """Digest info in the statepoint and return as a string.""" + + # Read the statepoint file. + statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] + sp = openmc.StatePoint(statepoint) + + # Read the summary file. + summary = glob.glob(os.path.join(os.getcwd(), 'summary.h5'))[0] + su = openmc.Summary(summary) + sp.link_with_summary(su) + + # Extract the cell tally + tallies = [sp.get_tally(name='cell tally')] + + # Slice the tallies by cell filter bins + cell_filter_prod = itertools.product(tallies, self.cell_filters) + tallies = map(lambda tf: tf[0].get_slice(filters=[tf[1].type], + filter_bins=[tf[1].get_bin(0)]), cell_filter_prod) + + # Slice the tallies by energy filter bins + energy_filter_prod = itertools.product(tallies, self.energy_filters) + tallies = map(lambda tf: tf[0].get_slice(filters=[tf[1].type], + filter_bins=[(tf[1].get_bin(0),)]), energy_filter_prod) + + # Slice the tallies by nuclide + nuclide_prod = itertools.product(tallies, self.nuclides) + tallies = map(lambda tn: tn[0].get_slice(nuclides=[tn[1]]), nuclide_prod) + + # Slice the tallies by score + score_prod = itertools.product(tallies, self.scores) + tallies = map(lambda ts: ts[0].get_slice(scores=[ts[1]]), score_prod) + + # Initialize an output string + outstr = '' + + # Append sliced Tally Pandas DataFrames to output string + for tally in tallies: + df = tally.get_pandas_dataframe() + outstr += df.to_string() + + # Merge all tallies together + while len(list(tallies)) != 1: + tallies = list(tallies) + halfway = int(len(tallies) / 2) + zip_split = zip(tallies[:halfway], tallies[halfway:]) + tallies = map(lambda xy: xy[0].merge(xy[1]), zip_split) + + # Append merged Tally Pandas DataFrame to output string + df = tallies[0].get_pandas_dataframe() + outstr += df.to_string() + + # Extract the distribcell tally + distribcell_tally = sp.get_tally(name='distribcell tally') + + # Sum up a few subdomains from the distribcell tally + sum1 = distribcell_tally.summation(filter_type='distribcell', + filter_bins=[0,100,2000,30000]) + # Sum up a few subdomains from the distribcell tally + sum2 = distribcell_tally.summation(filter_type='distribcell', + filter_bins=[500,5000,50000]) + + # Merge the distribcell tally slices + merge_tally = sum1.merge(sum2) + + # Append merged Tally Pandas DataFrame to output string + df = merge_tally.get_pandas_dataframe() + outstr += df.to_string() + + # Hash the results if necessary + if hash_output: + sha512 = hashlib.sha512() + sha512.update(outstr.encode('utf-8')) + outstr = sha512.hexdigest() + + return outstr + + def _cleanup(self): + super(TallySliceMergeTestHarness, self)._cleanup() + f = os.path.join(os.getcwd(), 'tallies.xml') + if os.path.exists(f): os.remove(f) + +if __name__ == '__main__': + harness = TallySliceMergeTestHarness('statepoint.10.h5', True) + harness.main() From baad8a998a33173f70c239b4741437936c9ed35a Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Thu, 11 Feb 2016 16:27:03 -0500 Subject: [PATCH 16/34] Fixed Python 3 issue in tally slice-merge test --- tests/test_tally_slice_merge/test_tally_slice_merge.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_tally_slice_merge/test_tally_slice_merge.py b/tests/test_tally_slice_merge/test_tally_slice_merge.py index 403f1827dd..79acf182d6 100644 --- a/tests/test_tally_slice_merge/test_tally_slice_merge.py +++ b/tests/test_tally_slice_merge/test_tally_slice_merge.py @@ -110,6 +110,7 @@ class TallySliceMergeTestHarness(PyAPITestHarness): # Slice the tallies by score score_prod = itertools.product(tallies, self.scores) tallies = map(lambda ts: ts[0].get_slice(scores=[ts[1]]), score_prod) + tallies = list(tallies) # Initialize an output string outstr = '' @@ -120,11 +121,10 @@ class TallySliceMergeTestHarness(PyAPITestHarness): outstr += df.to_string() # Merge all tallies together - while len(list(tallies)) != 1: - tallies = list(tallies) + while len(tallies) != 1: halfway = int(len(tallies) / 2) zip_split = zip(tallies[:halfway], tallies[halfway:]) - tallies = map(lambda xy: xy[0].merge(xy[1]), zip_split) + tallies = list(map(lambda xy: xy[0].merge(xy[1]), zip_split)) # Append merged Tally Pandas DataFrame to output string df = tallies[0].get_pandas_dataframe() From e40fd13d80e228c3edc173b87cc6a170dc7baa2d Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Thu, 11 Feb 2016 17:17:36 -0500 Subject: [PATCH 17/34] Removed old FIXME comment tags from tallies.py --- openmc/tallies.py | 8 +- tests/test_tally_arithmetic/geometry.xml | 148 ++++++++++++ tests/test_tally_arithmetic/inputs_test.dat | 1 + tests/test_tally_arithmetic/materials.xml | 246 ++++++++++++++++++++ tests/test_tally_arithmetic/settings.xml | 16 ++ tests/test_tally_arithmetic/tallies.xml | 21 ++ 6 files changed, 433 insertions(+), 7 deletions(-) create mode 100644 tests/test_tally_arithmetic/geometry.xml create mode 100644 tests/test_tally_arithmetic/inputs_test.dat create mode 100644 tests/test_tally_arithmetic/materials.xml create mode 100644 tests/test_tally_arithmetic/settings.xml create mode 100644 tests/test_tally_arithmetic/tallies.xml diff --git a/openmc/tallies.py b/openmc/tallies.py index b15e730386..91a1fb0eef 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -887,7 +887,7 @@ class Tally(object): # Create deep copy of other tally to use for array concatenation other_copy = copy.deepcopy(other) - # FIXME: document and create vars for merge_filters, etc. + # Identify if filters, nuclides and scores are mergeable and/or equal merge_filters = self._can_merge_filters(other) merge_nuclides = self._can_merge_nuclides(other) merge_scores = self._can_merge_scores(other) @@ -2224,8 +2224,6 @@ class Tally(object): else: filter2_bins = [filter2.get_bin(i) for i in range(filter2.num_bins)] - # FIXME: Why doesn't this swap data for sum and sum_sq??? - # Adjust the mean data array to relect the new filter order if self.mean is not None: for bin1, bin2 in itertools.product(filter1_bins, filter2_bins): @@ -2297,8 +2295,6 @@ class Tally(object): self.nuclides[nuclide1_index] = nuclide2 self.nuclides[nuclide2_index] = nuclide1 - # FIXME: Why doesn't this swap data for sum and sum_sq??? - # Adjust the mean data array to relect the new nuclide order if self.mean is not None: nuclide1_mean = self.mean[:, nuclide1_index, :].copy() @@ -2371,8 +2367,6 @@ class Tally(object): self.scores[score1_index] = score2 self.scores[score2_index] = score1 - # FIXME: Why doesn't this swap data for sum and sum_sq??? - # Adjust the mean data array to relect the new nuclide order if self.mean is not None: score1_mean = self.mean[:, :, score1_index].copy() diff --git a/tests/test_tally_arithmetic/geometry.xml b/tests/test_tally_arithmetic/geometry.xml new file mode 100644 index 0000000000..ed66ef8e6b --- /dev/null +++ b/tests/test_tally_arithmetic/geometry.xml @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1.26 1.26 + 17 17 + -10.71 -10.71 + +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 1 1 1 2 1 1 2 1 1 2 1 1 1 1 1 +1 1 1 2 1 1 1 1 1 1 1 1 1 2 1 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 2 1 1 2 1 1 2 1 1 2 1 1 2 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 2 1 1 2 1 1 2 1 1 2 1 1 2 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 2 1 1 2 1 1 2 1 1 2 1 1 2 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 1 2 1 1 1 1 1 1 1 1 1 2 1 1 1 +1 1 1 1 1 2 1 1 2 1 1 2 1 1 1 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 + + + 1.26 1.26 + 17 17 + -10.71 -10.71 + +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 4 3 3 4 3 3 4 3 3 3 3 3 +3 3 3 4 3 3 3 3 3 3 3 3 3 4 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 4 3 3 4 3 3 4 3 3 4 3 3 4 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 4 3 3 4 3 3 4 3 3 4 3 3 4 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 4 3 3 4 3 3 4 3 3 4 3 3 4 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 4 3 3 3 3 3 3 3 3 3 4 3 3 3 +3 3 3 3 3 4 3 3 4 3 3 4 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 + + + 21.42 21.42 + 21 21 + -224.91 -224.91 + +5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 +5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 +5 5 5 5 5 5 5 6 6 6 6 6 6 6 5 5 5 5 5 5 5 +5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 5 5 5 5 5 +5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 5 +5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 +5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 +5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 +5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 +5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 +5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 +5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 +5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 +5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 +5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 +5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 +5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 5 +5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 5 5 5 5 5 +5 5 5 5 5 5 5 6 6 6 6 6 6 6 5 5 5 5 5 5 5 +5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 +5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 + + + 21.42 21.42 + 21 21 + -224.91 -224.91 + +7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 +7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 +7 7 7 7 7 7 7 8 8 8 8 8 8 8 7 7 7 7 7 7 7 +7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 +7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 +7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 +7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 +7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 +7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 +7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 +7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 +7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 +7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 +7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 +7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 +7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 +7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 +7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 +7 7 7 7 7 7 7 8 8 8 8 8 8 8 7 7 7 7 7 7 7 +7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 +7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 + + + + + + + + + + + + + + + + + + + diff --git a/tests/test_tally_arithmetic/inputs_test.dat b/tests/test_tally_arithmetic/inputs_test.dat new file mode 100644 index 0000000000..1b6046f1ae --- /dev/null +++ b/tests/test_tally_arithmetic/inputs_test.dat @@ -0,0 +1 @@ +57384883e37964076aa82c19fa542434331cdb09735d710485b5aa0ca3445d543729e40cb9c7b6a70e7101ef186923eb1ff6315c73b01ff257052838add68fc7 \ No newline at end of file diff --git a/tests/test_tally_arithmetic/materials.xml b/tests/test_tally_arithmetic/materials.xml new file mode 100644 index 0000000000..9454c0d8e6 --- /dev/null +++ b/tests/test_tally_arithmetic/materials.xml @@ -0,0 +1,246 @@ + + + 71c + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/test_tally_arithmetic/settings.xml b/tests/test_tally_arithmetic/settings.xml new file mode 100644 index 0000000000..64f95a3a46 --- /dev/null +++ b/tests/test_tally_arithmetic/settings.xml @@ -0,0 +1,16 @@ + + + + 100 + 10 + 5 + + + + -160 -160 -183 160 160 183 + + + + true + + diff --git a/tests/test_tally_arithmetic/tallies.xml b/tests/test_tally_arithmetic/tallies.xml new file mode 100644 index 0000000000..ab4d1c37d8 --- /dev/null +++ b/tests/test_tally_arithmetic/tallies.xml @@ -0,0 +1,21 @@ + + + + 2 2 2 + -160.0 -160.0 -183.0 + 160.0 160.0 183.0 + + + + + + U-235 Pu-239 + nu-fission total + + + + + U-238 U-235 + total fission + + From 1cb7ef8f1cb3bf035e00b6d005df82596e168d08 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Thu, 11 Feb 2016 17:21:37 -0500 Subject: [PATCH 18/34] Removed XML files from tally arithmetic test --- tests/test_tally_arithmetic/geometry.xml | 148 ------------ tests/test_tally_arithmetic/inputs_test.dat | 1 - tests/test_tally_arithmetic/materials.xml | 246 -------------------- tests/test_tally_arithmetic/settings.xml | 16 -- tests/test_tally_arithmetic/tallies.xml | 21 -- 5 files changed, 432 deletions(-) delete mode 100644 tests/test_tally_arithmetic/geometry.xml delete mode 100644 tests/test_tally_arithmetic/inputs_test.dat delete mode 100644 tests/test_tally_arithmetic/materials.xml delete mode 100644 tests/test_tally_arithmetic/settings.xml delete mode 100644 tests/test_tally_arithmetic/tallies.xml diff --git a/tests/test_tally_arithmetic/geometry.xml b/tests/test_tally_arithmetic/geometry.xml deleted file mode 100644 index ed66ef8e6b..0000000000 --- a/tests/test_tally_arithmetic/geometry.xml +++ /dev/null @@ -1,148 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1.26 1.26 - 17 17 - -10.71 -10.71 - -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 2 1 1 2 1 1 2 1 1 1 1 1 -1 1 1 2 1 1 1 1 1 1 1 1 1 2 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 2 1 1 2 1 1 2 1 1 2 1 1 2 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 2 1 1 2 1 1 2 1 1 2 1 1 2 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 2 1 1 2 1 1 2 1 1 2 1 1 2 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 2 1 1 1 1 1 1 1 1 1 2 1 1 1 -1 1 1 1 1 2 1 1 2 1 1 2 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 - - - 1.26 1.26 - 17 17 - -10.71 -10.71 - -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 3 3 3 4 3 3 4 3 3 4 3 3 3 3 3 -3 3 3 4 3 3 3 3 3 3 3 3 3 4 3 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 4 3 3 4 3 3 4 3 3 4 3 3 4 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 4 3 3 4 3 3 4 3 3 4 3 3 4 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 4 3 3 4 3 3 4 3 3 4 3 3 4 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 3 4 3 3 3 3 3 3 3 3 3 4 3 3 3 -3 3 3 3 3 4 3 3 4 3 3 4 3 3 3 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 - - - 21.42 21.42 - 21 21 - -224.91 -224.91 - -5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 -5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 -5 5 5 5 5 5 5 6 6 6 6 6 6 6 5 5 5 5 5 5 5 -5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 5 5 5 5 5 -5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 5 -5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 -5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 -5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 -5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 -5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 -5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 -5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 -5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 -5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 -5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 -5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 -5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 5 5 5 5 -5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 5 5 5 5 5 -5 5 5 5 5 5 5 6 6 6 6 6 6 6 5 5 5 5 5 5 5 -5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 -5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 - - - 21.42 21.42 - 21 21 - -224.91 -224.91 - -7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 -7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 -7 7 7 7 7 7 7 8 8 8 8 8 8 8 7 7 7 7 7 7 7 -7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 -7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 -7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 -7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 -7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 -7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 -7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 -7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 -7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 -7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 -7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 -7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 -7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 -7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 -7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 -7 7 7 7 7 7 7 8 8 8 8 8 8 8 7 7 7 7 7 7 7 -7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 -7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 - - - - - - - - - - - - - - - - - - - diff --git a/tests/test_tally_arithmetic/inputs_test.dat b/tests/test_tally_arithmetic/inputs_test.dat deleted file mode 100644 index 1b6046f1ae..0000000000 --- a/tests/test_tally_arithmetic/inputs_test.dat +++ /dev/null @@ -1 +0,0 @@ -57384883e37964076aa82c19fa542434331cdb09735d710485b5aa0ca3445d543729e40cb9c7b6a70e7101ef186923eb1ff6315c73b01ff257052838add68fc7 \ No newline at end of file diff --git a/tests/test_tally_arithmetic/materials.xml b/tests/test_tally_arithmetic/materials.xml deleted file mode 100644 index 9454c0d8e6..0000000000 --- a/tests/test_tally_arithmetic/materials.xml +++ /dev/null @@ -1,246 +0,0 @@ - - - 71c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/test_tally_arithmetic/settings.xml b/tests/test_tally_arithmetic/settings.xml deleted file mode 100644 index 64f95a3a46..0000000000 --- a/tests/test_tally_arithmetic/settings.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - 100 - 10 - 5 - - - - -160 -160 -183 160 160 183 - - - - true - - diff --git a/tests/test_tally_arithmetic/tallies.xml b/tests/test_tally_arithmetic/tallies.xml deleted file mode 100644 index ab4d1c37d8..0000000000 --- a/tests/test_tally_arithmetic/tallies.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - 2 2 2 - -160.0 -160.0 -183.0 - 160.0 160.0 183.0 - - - - - - U-235 Pu-239 - nu-fission total - - - - - U-238 U-235 - total fission - - From db48ed6fb744867f3f4d2413228847dc99bfb504 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Fri, 12 Feb 2016 18:20:38 -0500 Subject: [PATCH 19/34] Fixed bug when merging tallies with more than two filters --- openmc/tallies.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc/tallies.py b/openmc/tallies.py index 91a1fb0eef..79baf2b503 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -699,8 +699,8 @@ class Tally(object): return False # Look to see if all filters are the same, or one or more can be merged - merge_filters = False for filter1 in self.filters: + merge_filters = False mergeable_filter = False for filter2 in other.filters: From 3ee4325410357de315359b92e58b3c5844fe3862 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Mon, 15 Feb 2016 12:24:10 -0500 Subject: [PATCH 20/34] HDF5 stores now work with subdomain-avg MGXS --- openmc/mgxs/mgxs.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index fb70b1bc8d..39da487d0e 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -696,7 +696,7 @@ class MGXS(object): # Construct a collection of the domain filter bins if not isinstance(subdomains, basestring): - cv.check_iterable_type('subdomains', subdomains, Integral) + cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=2) for subdomain in subdomains: filters.append(self.domain_type) filter_bins.append((subdomain,)) @@ -1195,6 +1195,9 @@ class MGXS(object): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) + elif self.domain_type == 'sum(distribcell)': + domain_filter = self.xs_tally.find_filter('sum(distribcell)') + subdomains = domain_filter.bins else: subdomains = [self.domain.id] @@ -2019,7 +2022,7 @@ class ScatterMatrixXS(MGXS): # Construct a collection of the domain filter bins if not isinstance(subdomains, basestring): - cv.check_iterable_type('subdomains', subdomains, Integral) + cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=2) for subdomain in subdomains: filters.append(self.domain_type) filter_bins.append((subdomain,)) @@ -2416,7 +2419,7 @@ class Chi(MGXS): # Construct a collection of the domain filter bins if not isinstance(subdomains, basestring): - cv.check_iterable_type('subdomains', subdomains, Integral) + cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=2) for subdomain in subdomains: filters.append(self.domain_type) filter_bins.append((subdomain,)) From 7fdca5b9cb24eba20c433965c9e2f80ff6db1562 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Mon, 15 Feb 2016 22:42:57 -0500 Subject: [PATCH 21/34] Added name property to CrossNuclide to fix bug --- openmc/arithmetic.py | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index 4ddf3b1f91..521d33e9f0 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -188,6 +188,23 @@ class CrossNuclide(object): return existing def __repr__(self): + return self.name + + + @property + def left_nuclide(self): + return self._left_nuclide + + @property + def right_nuclide(self): + return self._right_nuclide + + @property + def binary_op(self): + return self._binary_op + + @property + def name(self): string = '' @@ -209,18 +226,6 @@ class CrossNuclide(object): return string - @property - def left_nuclide(self): - return self._left_nuclide - - @property - def right_nuclide(self): - return self._right_nuclide - - @property - def binary_op(self): - return self._binary_op - @left_nuclide.setter def left_nuclide(self, left_nuclide): cv.check_type('left_nuclide', left_nuclide, From d23149ff94209f9a2b3ecabfd27543e08665b079 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Tue, 16 Feb 2016 10:50:53 -0500 Subject: [PATCH 22/34] Fixed bug in a check for results when merging tallies --- openmc/tallies.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc/tallies.py b/openmc/tallies.py index 79baf2b503..272896d834 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -933,7 +933,7 @@ class Tally(object): merged_tally.add_trigger(trigger) # If results have not been read, then return tally for input generation - if self._sp_filename is None: + if self._results_read is None: return merged_tally #Otherwise, this is a derived tally which needs merged results arrays else: From e138fb25ea351cd17c9226b482399f011e9f9cdb Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Tue, 16 Feb 2016 16:20:22 -0500 Subject: [PATCH 23/34] Fixed bug in tiling of energies for ScatterMatrix MGXS objects --- openmc/mgxs/mgxs.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 39da487d0e..cc91e9483f 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -1414,12 +1414,11 @@ class MGXS(object): if 'energy [MeV]' in df and 'energyout [MeV]' in df: df.rename(columns={'energy [MeV]': 'group in'}, inplace=True) in_groups = np.tile(all_groups, self.num_subdomains) - in_groups = np.repeat(in_groups, self.num_groups) + in_groups = np.repeat(in_groups, df.shape[0] / in_groups.size) df['group in'] = in_groups df.rename(columns={'energyout [MeV]': 'group out'}, inplace=True) - out_groups = \ - np.tile(all_groups, self.num_subdomains * self.num_groups) + out_groups = np.tile(all_groups, df.shape[0] / all_groups.size) df['group out'] = out_groups columns = ['group in', 'group out'] @@ -1919,7 +1918,7 @@ class ScatterMatrixXS(MGXS): cv.check_value('correction', correction, ('P0', None)) self._correction = correction - def get_slice(self, nuclides=[], groups=[]): + def get_slice(self, nuclides=[], in_groups=[], out_groups=[]): """Build a sliced ScatterMatrix for the specified nuclides and energy groups. @@ -1933,9 +1932,12 @@ class ScatterMatrixXS(MGXS): nuclides : list of str A list of nuclide name strings (e.g., ['U-235', 'U-238']; default is []) - groups : list of Integral - A list of energy group indices starting at 1 for the high energies - (e.g., [1, 2, 3]; default is []) + in_groups : list of Integral + A list of incoming energy group indices starting at 1 for the high + energies (e.g., [1, 2, 3]; default is []) + out_groups : list of Integral + A list of outgoing energy group indices starting at 1 for the high + energies (e.g., [1, 2, 3]; default is []) Returns ------- @@ -1946,14 +1948,14 @@ class ScatterMatrixXS(MGXS): """ # Call super class method and null out derived tallies - slice_xs = super(ScatterMatrixXS, self).get_slice(nuclides, groups) + slice_xs = super(ScatterMatrixXS, self).get_slice(nuclides, in_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None - # Slice energy groups if needed - if len(groups) != 0: + # Slice outgoing energy groups if needed + if len(out_groups) != 0: filter_bins = [] - for group in groups: + for group in out_groups: group_bounds = self.energy_groups.get_group_bounds(group) filter_bins.append(group_bounds) filter_bins = [tuple(filter_bins)] From 128f25fe2b5bedd6b3d9cdaf537a808e2a3767c0 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Thu, 18 Feb 2016 00:45:49 -0500 Subject: [PATCH 24/34] Added methods to Python APIs Geometry class to extract objects by string name --- openmc/geometry.py | 256 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 253 insertions(+), 3 deletions(-) diff --git a/openmc/geometry.py b/openmc/geometry.py index 9788671f5c..fb43bd77f2 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -1,5 +1,6 @@ from collections import Iterable, OrderedDict from xml.etree import ElementTree as ET +import re import openmc from openmc.clean_xml import * @@ -94,7 +95,16 @@ class Geometry(object): """ - return self._root_universe.get_all_cells() + all_cells = self._root_universe.get_all_cells() + cells = set() + + for cell_id, cell in all_cells.items(): + if cell._type == 'normal': + cells.add(cell) + + cells = list(cells) + cells.sort(key=lambda x: x.id) + return cells def get_all_universes(self): """Return all universes defined @@ -106,7 +116,16 @@ class Geometry(object): """ - return self._root_universe.get_all_universes() + all_universes = self._root_universe.get_all_universes() + universes = set() + + for universe_id, universe in all_universes.items(): + if universe._type == 'normal': + universes.add(universe) + + universes = list(universes) + universes.sort(key=lambda x: x.id) + return universes def get_all_nuclides(self): """Return all nuclides assigned to a material in the geometry @@ -150,6 +169,15 @@ class Geometry(object): return materials def get_all_material_cells(self): + """Return all cells filled by a material + + Returns + ------- + list of openmc.universe.Cell + Cells filled by Materials in the geometry + + """ + all_cells = self.get_all_cells() material_cells = set() @@ -175,7 +203,7 @@ class Geometry(object): material_universes = set() for universe_id, universe in all_universes.items(): - cells = universe._cells + cells = universe.cells for cell_id, cell in cells.items(): if cell._type == 'normal': material_universes.add(universe) @@ -184,6 +212,228 @@ class Geometry(object): material_universes.sort(key=lambda x: x.id) return material_universes + def get_all_lattices(self): + """Return all lattices defined + + Returns + ------- + list of openmc.universe.Lattice + Lattices in the geometry + + """ + + cells = self.get_all_cells() + lattices = set() + + for cell in cells: + if isinstance(cell.fill, openmc.Lattice): + lattices.add(cell.fill) + + lattices = list(lattices) + lattices.sort(key=lambda x: x.id) + return lattices + + def get_materials_by_name(self, name, case_sensitive=False, matching=False): + """Return a list of materials with names matching a regular expression. + + Parameters + ---------- + name : str + The name to search for (regular expressions are acceptable) + case_sensitive : bool + Whether to distinguish upper and lower case letters in each + material's name (default is True) + matching : bool + Whether the names must match completely (default is True) + + Returns + ------- + list of openmc.material.Material + Materials matching the queried name + + """ + + regex = re.compile(b'{0}'.format(name)) + + all_materials = self.get_all_materials() + materials = set() + + for material in all_materials: + material_name = material.name + if not case_sensitive: + material_name = material_name.lower() + + match = regex.findall(material_name) + if match and matching: + materials.add(material) + elif match and match[0] == name: + materials.add(material) + + materials = list(materials) + materials.sort(key=lambda x: x.id) + return materials + + def get_cells_by_name(self, name, case_sensitive=False, matching=False): + """Return a list of cells with names matching a regular expression. + + Parameters + ---------- + name : str + The name to search for (regular expressions are acceptable) + case_sensitive : bool + Whether to distinguish upper and lower case letters in each + cell's name (default is True) + matching : bool + Whether the names must match completely (default is True) + + Returns + ------- + list of openmc.universe.Cell + Cells matching the queried name + + """ + + regex = re.compile(b'{0}'.format(name)) + + all_cells = self.get_all_cells() + cells = set() + + for cell in all_cells: + cell_name = cell.name + if not case_sensitive: + cell_name = cell_name.lower() + + match = regex.findall(cell_name) + if match and matching: + cells.add(cell) + elif match and match[0] == name: + cells.add(cell) + + cells = list(cells) + cells.sort(key=lambda x: x.id) + return cells + + def get_cells_by_fill_name(self, name, case_sensitive=False, matching=False): + """Return a list of cells with fills with names matching a + regular expression. + + Parameters + ---------- + name : str + The name to search for (regular expressions are acceptable) + case_sensitive : bool + Whether to distinguish upper and lower case letters in each + cell's name (default is True) + matching : bool + Whether the names must match completely (default is True) + + Returns + ------- + list of openmc.universe.Cell + Cells with fills matching the queried name + + """ + + regex = re.compile(b'{0}'.format(name)) + + all_cells = self.get_all_cells() + cells = set() + + for cell in all_cells: + cell_fill_name = cell.fill.name + if not case_sensitive: + cell_fill_name = cell_fill_name.lower() + + match = regex.findall(cell_fill_name) + if match and matching: + cells.add(cell) + elif match and match[0] == name: + cells.add(cell) + + cells = list(cells) + cells.sort(key=lambda x: x.id) + return cells + + def get_universes_by_name(self, name, case_sensitive=False, matching=False): + """Return a list of universes with names matching a regular expression. + + Parameters + ---------- + name : str + The name to search for (regular expressions are acceptable) + case_sensitive : bool + Whether to distinguish upper and lower case letters in each + universe's name (default is True) + matching : bool + Whether the names must match completely (default is True) + + Returns + ------- + list of openmc.universe.Universe + Universes matching the queried name + + """ + + regex = re.compile(b'{0}'.format(name)) + + all_universes = self.get_all_universes() + universes = set() + + for universe in all_universes: + universe_name = universe.name + if not case_sensitive: + universe_name = universe_name.lower() + + match = regex.findall(universe_name) + if match and matching: + universes.add(universe) + elif match and match[0] == name: + universes.add(universe) + + universes = list(universes) + universes.sort(key=lambda x: x.id) + return universes + + def get_lattices_by_name(self, name, case_sensitive=False, matching=False): + """Return a list of lattices with names matching a regular expression. + + Parameters + ---------- + name : str + The name to search for (regular expressions are acceptable) + case_sensitive : bool + Whether to distinguish upper and lower case letters in each + lattice's name (default is True) + matching : bool + Whether the names must match completely (default is True) + + Returns + ------- + list of openmc.universe.Lattice + Lattices matching the queried name + + """ + + regex = re.compile(b'{0}'.format(name)) + + all_lattices = self.get_all_lattices() + lattices = set() + + for lattice in all_lattices: + lattice_name = lattice.name + if not case_sensitive: + lattice_name = lattice_name.lower() + + match = regex.findall(lattice_name) + if match and matching: + lattices.add(lattice) + elif match and match[0] == name: + lattices.add(lattice) + + lattices = list(lattices) + lattices.sort(key=lambda x: x.id) + return lattices + class GeometryFile(object): """Geometry file used for an OpenMC simulation. Corresponds directly to the From 988105dbc3f6a95743b4cfc76dbff048770adac7 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Fri, 19 Feb 2016 13:10:20 -0500 Subject: [PATCH 25/34] Fixed Geometry object getter methods to reflect changes in last commit --- openmc/geometry.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/openmc/geometry.py b/openmc/geometry.py index fb43bd77f2..74feaef64b 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -66,8 +66,10 @@ class Geometry(object): # Find the distribcell index of the cell. cells = self.get_all_cells() - if path[-1] in cells: - distribcell_index = cells[path[-1]].distribcell_index + for cell in cells: + if cell.id == path[-1]: + distribcell_index = cell.distribcell_index + break else: raise RuntimeError('Could not find cell {} specified in a \ distribcell filter'.format(path[-1])) @@ -181,7 +183,7 @@ class Geometry(object): all_cells = self.get_all_cells() material_cells = set() - for cell_id, cell in all_cells.items(): + for cell in all_cells: if cell._type == 'normal': material_cells.add(cell) @@ -202,9 +204,9 @@ class Geometry(object): all_universes = self.get_all_universes() material_universes = set() - for universe_id, universe in all_universes.items(): + for universe in all_universes: cells = universe.cells - for cell_id, cell in cells.items(): + for cell in cells: if cell._type == 'normal': material_universes.add(universe) From a322437f0c218a5111d3cb632c29c4507f309d2e Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Fri, 19 Feb 2016 18:21:39 -0500 Subject: [PATCH 26/34] Now using tally averaging for subdomain averaging of MGXS --- openmc/mgxs/mgxs.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 8d0ecdb867..35830ff712 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -874,11 +874,11 @@ class MGXS(object): # Average each of the tallies across subdomains for tally_type, tally in avg_xs.tallies.items(): - tally_avg = tally.summation(filter_type=self.domain_type, - filter_bins=subdomains) + tally_avg = tally.average(filter_type=self.domain_type, + filter_bins=subdomains) avg_xs.tallies[tally_type] = tally_avg - avg_xs._domain_type = 'sum({0})'.format(self.domain_type) + avg_xs._domain_type = 'avg({0})'.format(self.domain_type) avg_xs.sparse = self.sparse return avg_xs @@ -1195,8 +1195,8 @@ class MGXS(object): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) - elif self.domain_type == 'sum(distribcell)': - domain_filter = self.xs_tally.find_filter('sum(distribcell)') + elif self.domain_type == 'avg(distribcell)': + domain_filter = self.xs_tally.find_filter('avg(distribcell)') subdomains = domain_filter.bins else: subdomains = [self.domain.id] From c6c3ff74dcec5cea5dbfc92edb57ad0d2e6c95bb Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Sat, 20 Feb 2016 12:28:21 -0500 Subject: [PATCH 27/34] Fixed issues with object retrieval by name from Geometry in Python API --- openmc/geometry.py | 65 +++++++++---------- .../test_asymmetric_lattice.py | 16 ++--- .../results_true.dat | 8 +-- 3 files changed, 42 insertions(+), 47 deletions(-) diff --git a/openmc/geometry.py b/openmc/geometry.py index 74feaef64b..807dcf7c66 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -1,6 +1,5 @@ from collections import Iterable, OrderedDict from xml.etree import ElementTree as ET -import re import openmc from openmc.clean_xml import * @@ -122,8 +121,7 @@ class Geometry(object): universes = set() for universe_id, universe in all_universes.items(): - if universe._type == 'normal': - universes.add(universe) + universes.add(universe) universes = list(universes) universes.sort(key=lambda x: x.id) @@ -236,12 +234,12 @@ class Geometry(object): return lattices def get_materials_by_name(self, name, case_sensitive=False, matching=False): - """Return a list of materials with names matching a regular expression. + """Return a list of materials with matching names. Parameters ---------- name : str - The name to search for (regular expressions are acceptable) + The name to match case_sensitive : bool Whether to distinguish upper and lower case letters in each material's name (default is True) @@ -255,7 +253,8 @@ class Geometry(object): """ - regex = re.compile(b'{0}'.format(name)) + if case_sensitive: + name = name.lower() all_materials = self.get_all_materials() materials = set() @@ -265,10 +264,9 @@ class Geometry(object): if not case_sensitive: material_name = material_name.lower() - match = regex.findall(material_name) - if match and matching: + if material_name == name: materials.add(material) - elif match and match[0] == name: + elif not matching and name in material_name: materials.add(material) materials = list(materials) @@ -276,12 +274,12 @@ class Geometry(object): return materials def get_cells_by_name(self, name, case_sensitive=False, matching=False): - """Return a list of cells with names matching a regular expression. + """Return a list of cells with matching names. Parameters ---------- name : str - The name to search for (regular expressions are acceptable) + The name to search match case_sensitive : bool Whether to distinguish upper and lower case letters in each cell's name (default is True) @@ -295,7 +293,8 @@ class Geometry(object): """ - regex = re.compile(b'{0}'.format(name)) + if case_sensitive: + name = name.lower() all_cells = self.get_all_cells() cells = set() @@ -305,10 +304,9 @@ class Geometry(object): if not case_sensitive: cell_name = cell_name.lower() - match = regex.findall(cell_name) - if match and matching: + if cell_name == name: cells.add(cell) - elif match and match[0] == name: + elif not matching and name in cell_name: cells.add(cell) cells = list(cells) @@ -316,13 +314,12 @@ class Geometry(object): return cells def get_cells_by_fill_name(self, name, case_sensitive=False, matching=False): - """Return a list of cells with fills with names matching a - regular expression. + """Return a list of cells with fills with matching names. Parameters ---------- name : str - The name to search for (regular expressions are acceptable) + The name to match case_sensitive : bool Whether to distinguish upper and lower case letters in each cell's name (default is True) @@ -336,7 +333,8 @@ class Geometry(object): """ - regex = re.compile(b'{0}'.format(name)) + if case_sensitive: + name = name.lower() all_cells = self.get_all_cells() cells = set() @@ -346,10 +344,9 @@ class Geometry(object): if not case_sensitive: cell_fill_name = cell_fill_name.lower() - match = regex.findall(cell_fill_name) - if match and matching: + if cell_fill_name == name: cells.add(cell) - elif match and match[0] == name: + elif not matching and name in cell_fill_name: cells.add(cell) cells = list(cells) @@ -357,12 +354,12 @@ class Geometry(object): return cells def get_universes_by_name(self, name, case_sensitive=False, matching=False): - """Return a list of universes with names matching a regular expression. + """Return a list of universes with matching names. Parameters ---------- name : str - The name to search for (regular expressions are acceptable) + The name to match case_sensitive : bool Whether to distinguish upper and lower case letters in each universe's name (default is True) @@ -376,7 +373,8 @@ class Geometry(object): """ - regex = re.compile(b'{0}'.format(name)) + if case_sensitive: + name = name.lower() all_universes = self.get_all_universes() universes = set() @@ -386,10 +384,9 @@ class Geometry(object): if not case_sensitive: universe_name = universe_name.lower() - match = regex.findall(universe_name) - if match and matching: + if universe_name == name: universes.add(universe) - elif match and match[0] == name: + elif not matching and name in universe_name: universes.add(universe) universes = list(universes) @@ -397,12 +394,12 @@ class Geometry(object): return universes def get_lattices_by_name(self, name, case_sensitive=False, matching=False): - """Return a list of lattices with names matching a regular expression. + """Return a list of lattices with matching names. Parameters ---------- name : str - The name to search for (regular expressions are acceptable) + The name to match case_sensitive : bool Whether to distinguish upper and lower case letters in each lattice's name (default is True) @@ -416,7 +413,8 @@ class Geometry(object): """ - regex = re.compile(b'{0}'.format(name)) + if case_sensitive: + name = name.lower() all_lattices = self.get_all_lattices() lattices = set() @@ -426,10 +424,9 @@ class Geometry(object): if not case_sensitive: lattice_name = lattice_name.lower() - match = regex.findall(lattice_name) - if match and matching: + if lattice_name == name: lattices.add(lattice) - elif match and match[0] == name: + elif not matching and name in lattice_name: lattices.add(lattice) lattices = list(lattices) diff --git a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py b/tests/test_asymmetric_lattice/test_asymmetric_lattice.py index 5a1d47ef85..fdb21db33c 100644 --- a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py +++ b/tests/test_asymmetric_lattice/test_asymmetric_lattice.py @@ -19,13 +19,10 @@ class AsymmetricLatticeTestHarness(PyAPITestHarness): # Build full core geometry from underlying input set self._input_set.build_default_materials_and_geometry() - # Extract all universes from the full core geometry - geometry = self._input_set.geometry.geometry - all_univs = geometry.get_all_universes() - # Extract universes encapsulating fuel and water assemblies - water = all_univs[7] - fuel = all_univs[8] + geometry = self._input_set.geometry.geometry + water = geometry.get_universes_by_name('water assembly (hot)')[0] + fuel = geometry.get_universes_by_name('fuel assembly (hot)')[0] # Construct a 3x3 lattice of fuel assemblies core_lat = openmc.RectLattice(name='3x3 Core Lattice', lattice_id=202) @@ -102,9 +99,10 @@ class AsymmetricLatticeTestHarness(PyAPITestHarness): outstr += ', '.join(map(str, tally.std_dev.flatten())) + '\n' # Extract fuel assembly lattices from the summary - all_cells = su.openmc_geometry.get_all_cells() - fuel = all_cells[80].fill - core = all_cells[1].fill + core = su.get_cell_by_id(1) + fuel = su.get_cell_by_id(80) + fuel = fuel.fill + core = core.fill # Append a string of lattice distribcell offsets to the string outstr += ', '.join(map(str, fuel.offsets.flatten())) + '\n' diff --git a/tests/test_mgxs_library_distribcell/results_true.dat b/tests/test_mgxs_library_distribcell/results_true.dat index 7b4be0f468..ad9b949de9 100644 --- a/tests/test_mgxs_library_distribcell/results_true.dat +++ b/tests/test_mgxs_library_distribcell/results_true.dat @@ -1,5 +1,5 @@ - sum(distribcell) group in nuclide mean std. dev. -0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 total 0.720213 1.424323 sum(distribcell) group in nuclide mean std. dev. -0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 total 0 0 sum(distribcell) group in group out nuclide mean std. dev. -0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 1 total 0.70466 1.403916 sum(distribcell) group out nuclide mean std. dev. + avg(distribcell) group in nuclide mean std. dev. +0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 total 0.720213 1.424323 avg(distribcell) group in nuclide mean std. dev. +0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 total 0 0 avg(distribcell) group in group out nuclide mean std. dev. +0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 1 total 0.70466 1.403916 avg(distribcell) group out nuclide mean std. dev. 0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 total 0 0 \ No newline at end of file From 411e7f241a840d952d95aef171a98323388e1fbb Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Sun, 21 Feb 2016 17:15:03 -0500 Subject: [PATCH 28/34] Fixed issue with MGXS merging - now null out base tallies since fluxes cannot be merged and reused to compute merged cross sections --- openmc/mgxs/mgxs.py | 69 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 63 insertions(+), 6 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 35830ff712..f5c23dfd55 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -114,6 +114,8 @@ class MGXS(object): sparse : bool Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format for compressed data storage + derived : bool + Whether or not the MGXS is merged from one or more other MGXS """ @@ -135,6 +137,7 @@ class MGXS(object): self._rxn_rate_tally = None self._xs_tally = None self._sparse = False + self._derived = False self.name = name self.by_nuclide = by_nuclide @@ -163,6 +166,7 @@ class MGXS(object): clone._rxn_rate_tally = copy.deepcopy(self._rxn_rate_tally, memo) clone._xs_tally = copy.deepcopy(self._xs_tally, memo) clone._sparse = self.sparse + clone._derived = self.derived clone._tallies = OrderedDict() for tally_type, tally in self.tallies.items(): @@ -255,6 +259,10 @@ class MGXS(object): else: return 'sum' + @property + def derived(self): + return self._derived + @name.setter def name(self, name): cv.check_type('name', name, basestring) @@ -1014,8 +1022,7 @@ class MGXS(object): # Create deep copy of tally to return as merged tally merged_mgxs = copy.deepcopy(self) - merged_mgxs._rxn_rate_tally = None - merged_mgxs._xs_tally = None + merged_mgxs._derived = True # Merge energy groups if self.energy_groups != other.energy_groups: @@ -1034,10 +1041,10 @@ class MGXS(object): # Concatenate lists of nuclides for the merged MGXS merged_mgxs.nuclides = self.nuclides + other.nuclides - # Merge tallies - for tally_key in self.tallies: - merged_tally = self.tallies[tally_key].merge(other.tallies[tally_key]) - merged_mgxs.tallies[tally_key] = merged_tally + # Null base tallies but merge reaction rate and cross section tallies + merged_mgxs._tallies = OrderedDict() + merged_mgxs._rxn_rate_tally = self.rxn_rate_tally.merge(other.rxn_rate_tally) + merged_mgxs._xs_tally = self.xs_tally.merge(other.xs_tally) return merged_mgxs @@ -2377,6 +2384,56 @@ class Chi(MGXS): slice_xs.sparse = self.sparse return slice_xs + def merge(self, other): + """Merge another Chi with this one + + If results have been loaded from a statepoint, then Chi are only + mergeable along one and only one of energy groups or nuclides. + + Parameters + ---------- + other : MGXS + MGXS to merge with this one + + Returns + ------- + merged_mgxs : MGXS + Merged MGXS + """ + + if not self.can_merge(other): + raise ValueError('Unable to merge Chi') + + # Create deep copy of tally to return as merged tally + merged_mgxs = copy.deepcopy(self) + merged_mgxs._derived = True + merged_mgxs._rxn_rate_tally = None + merged_mgxs._xs_tally = None + + # Merge energy groups + if self.energy_groups != other.energy_groups: + merged_groups = self.energy_groups.merge(other.energy_groups) + merged_mgxs.energy_groups = merged_groups + + # Merge nuclides + if self.nuclides != other.nuclides: + + # The nuclides must be mutually exclusive + for nuclide in self.nuclides: + if nuclide in other.nuclides: + msg = 'Unable to merge Chi with shared nuclides' + raise ValueError(msg) + + # Concatenate lists of nuclides for the merged MGXS + merged_mgxs.nuclides = self.nuclides + other.nuclides + + # Merge tallies + for tally_key in self.tallies: + merged_tally = self.tallies[tally_key].merge(other.tallies[tally_key]) + merged_mgxs.tallies[tally_key] = merged_tally + + return merged_mgxs + def get_xs(self, groups='all', subdomains='all', nuclides='all', xs_type='macro', order_groups='increasing', value='mean'): """Returns an array of the fission spectrum. From ead3f50d27ae7b96e5050fb8127f9f12ede93600 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Sun, 21 Feb 2016 21:29:49 -0500 Subject: [PATCH 29/34] Eliminated Pandas deprecation warning from MGXS Pandas DataFrame builder method --- openmc/mgxs/mgxs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index f5c23dfd55..022acef5f4 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -1467,7 +1467,7 @@ class MGXS(object): # Sort the dataframe by domain type id (e.g., distribcell id) and # energy groups such that data is from fast to thermal - df.sort([self.domain_type] + columns, inplace=True) + df.sort_values(by=[self.domain_type] + columns, inplace=True) return df From da6f5d98a8d1c26b1383e958e252c91bb985d87c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 24 Feb 2016 07:11:09 -0600 Subject: [PATCH 30/34] Use common naming scheme for all abstract interfaces --- src/distribution_multivariate.F90 | 12 ++++++------ src/distribution_univariate.F90 | 6 +++--- src/energy_distribution.F90 | 6 +++--- src/geometry_header.F90 | 22 ++++++++++------------ src/input_xml.F90 | 22 ++++++++++++++-------- src/nuclide_header.F90 | 8 +++----- src/particle_header.F90 | 2 +- src/scattdata_header.F90 | 20 ++++++++++---------- src/secondary_header.F90 | 7 ++++--- src/surface_header.F90 | 18 +++++++++--------- src/tally.F90 | 15 +++++++-------- 11 files changed, 70 insertions(+), 68 deletions(-) diff --git a/src/distribution_multivariate.F90 b/src/distribution_multivariate.F90 index 694fac3013..68b246df84 100644 --- a/src/distribution_multivariate.F90 +++ b/src/distribution_multivariate.F90 @@ -16,15 +16,15 @@ module distribution_multivariate type, abstract :: UnitSphereDistribution real(8) :: reference_uvw(3) contains - procedure(iSample), deferred :: sample + procedure(unitsphere_distribution_sample_), deferred :: sample end type UnitSphereDistribution abstract interface - function iSample(this) result(uvw) + function unitsphere_distribution_sample_(this) result(uvw) import UnitSphereDistribution class(UnitSphereDistribution), intent(in) :: this real(8) :: uvw(3) - end function iSample + end function unitsphere_distribution_sample_ end interface !=============================================================================== @@ -58,15 +58,15 @@ module distribution_multivariate type, abstract :: SpatialDistribution contains - procedure(iSampleSpatial), deferred :: sample + procedure(spatial_distribution_sample_), deferred :: sample end type SpatialDistribution abstract interface - function iSampleSpatial(this) result(xyz) + function spatial_distribution_sample_(this) result(xyz) import SpatialDistribution class(SpatialDistribution), intent(in) :: this real(8) :: xyz(3) - end function iSampleSpatial + end function spatial_distribution_sample_ end interface type, extends(SpatialDistribution) :: CartesianIndependent diff --git a/src/distribution_univariate.F90 b/src/distribution_univariate.F90 index f3e4fdee2e..6c053e5942 100644 --- a/src/distribution_univariate.F90 +++ b/src/distribution_univariate.F90 @@ -16,7 +16,7 @@ module distribution_univariate type, abstract :: Distribution contains - procedure(iSample), deferred :: sample + procedure(distribution_sample_), deferred :: sample end type Distribution type DistributionContainer @@ -24,11 +24,11 @@ module distribution_univariate end type DistributionContainer abstract interface - function iSample(this) result(x) + function distribution_sample_(this) result(x) import Distribution class(Distribution), intent(in) :: this real(8) :: x - end function iSample + end function distribution_sample_ end interface !=============================================================================== diff --git a/src/energy_distribution.F90 b/src/energy_distribution.F90 index 2cfc1b1841..8b2cc10c9c 100644 --- a/src/energy_distribution.F90 +++ b/src/energy_distribution.F90 @@ -16,16 +16,16 @@ module energy_distribution type, abstract :: EnergyDistribution contains - procedure(iSampleEnergy), deferred :: sample + procedure(energy_distribution_sample_), deferred :: sample end type EnergyDistribution abstract interface - function iSampleEnergy(this, E_in) result(E_out) + function energy_distribution_sample_(this, E_in) result(E_out) import EnergyDistribution class(EnergyDistribution), intent(in) :: this real(8), intent(in) :: E_in real(8) :: E_out - end function iSampleEnergy + end function energy_distribution_sample_ end interface type :: EnergyDistributionContainer diff --git a/src/geometry_header.F90 b/src/geometry_header.F90 index 519b15bff4..1adda3ea34 100644 --- a/src/geometry_header.F90 +++ b/src/geometry_header.F90 @@ -31,12 +31,10 @@ module geometry_header integer :: outer ! universe to tile outside the lat logical :: is_3d ! Lattice has cells on z axis integer, allocatable :: offset(:,:,:,:) ! Distribcell offsets - - contains - - procedure(are_valid_indices_), deferred :: are_valid_indices - procedure(get_indices_), deferred :: get_indices - procedure(get_local_xyz_), deferred :: get_local_xyz + contains + procedure(lattice_are_valid_indices_), deferred :: are_valid_indices + procedure(lattice_get_indices_), deferred :: get_indices + procedure(lattice_get_local_xyz_), deferred :: get_local_xyz end type Lattice abstract interface @@ -45,33 +43,33 @@ module geometry_header ! ARE_VALID_INDICES returns .true. if the given lattice indices fit within the ! bounds of the lattice. Returns false otherwise. - function are_valid_indices_(this, i_xyz) result(is_valid) + function lattice_are_valid_indices_(this, i_xyz) result(is_valid) import Lattice class(Lattice), intent(in) :: this integer, intent(in) :: i_xyz(3) logical :: is_valid - end function are_valid_indices_ + end function lattice_are_valid_indices_ !=============================================================================== ! GET_INDICES returns the indices in a lattice for the given global xyz. - function get_indices_(this, global_xyz) result(i_xyz) + function lattice_get_indices_(this, global_xyz) result(i_xyz) import Lattice class(Lattice), intent(in) :: this real(8), intent(in) :: global_xyz(3) integer :: i_xyz(3) - end function get_indices_ + end function lattice_get_indices_ !=============================================================================== ! GET_LOCAL_XYZ returns the translated local version of the given global xyz. - function get_local_xyz_(this, global_xyz, i_xyz) result(local_xyz) + function lattice_get_local_xyz_(this, global_xyz, i_xyz) result(local_xyz) import Lattice class(Lattice), intent(in) :: this real(8), intent(in) :: global_xyz(3) integer, intent(in) :: i_xyz(3) real(8) :: local_xyz(3) - end function get_local_xyz_ + end function lattice_get_local_xyz_ end interface !=============================================================================== diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 9ef439bb04..03ef8dcbc4 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -131,15 +131,21 @@ contains if (run_CE) then call get_environment_variable("OPENMC_CROSS_SECTIONS", env_variable) if (len_trim(env_variable) == 0) then - call fatal_error("No cross_sections.xml file was specified in & - &settings.xml or in the OPENMC_CROSS_SECTIONS environment & - &variable. OpenMC needs such a file to identify where to & - &find ACE cross section libraries. Please consult the user's & - &guide at http://mit-crpg.github.io/openmc for information on & - &how to set up ACE cross section libraries.") - else - path_cross_sections = trim(env_variable) + call get_environment_variable("CROSS_SECTIONS", env_variable) + if (len_trim(env_variable) == 0) then + call fatal_error("No cross_sections.xml file was specified in & + &settings.xml or in the OPENMC_CROSS_SECTIONS environment & + &variable. OpenMC needs such a file to identify where to & + &find ACE cross section libraries. Please consult the user's & + &guide at http://mit-crpg.github.io/openmc for information on & + &how to set up ACE cross section libraries.") + else + call warning("The CROSS_SECTIONS environment variable is & + &deprecated. Please update your environment to use & + &OPENMC_CROSS_SECTIONS instead.") + end if end if + path_cross_sections = trim(env_variable) else call get_environment_variable("OPENMC_MG_CROSS_SECTIONS", env_variable) if (len_trim(env_variable) == 0) then diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 9bcce57a75..43fea77b65 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -33,17 +33,15 @@ module nuclide_header logical :: fissionable ! nuclide is fissionable? contains - procedure(print_nuclide_), deferred :: print ! Writes nuclide info + procedure(nuclide_print_), deferred :: print ! Writes nuclide info end type Nuclide abstract interface - - subroutine print_nuclide_(this, unit) + subroutine nuclide_print_(this, unit) import Nuclide class(Nuclide),intent(in) :: this integer, optional, intent(in) :: unit - end subroutine print_nuclide_ - + end subroutine nuclide_print_ end interface type, extends(Nuclide) :: NuclideCE diff --git a/src/particle_header.F90 b/src/particle_header.F90 index c1f02eca24..4ad4119b76 100644 --- a/src/particle_header.F90 +++ b/src/particle_header.F90 @@ -217,7 +217,7 @@ contains integer, intent(in) :: type logical, intent(in) :: run_CE - integer :: n + integer(8) :: n ! Check to make sure that the hard-limit on secondary particles is not ! exceeded. diff --git a/src/scattdata_header.F90 b/src/scattdata_header.F90 index b04115e570..f8fddbc6b3 100644 --- a/src/scattdata_header.F90 +++ b/src/scattdata_header.F90 @@ -20,22 +20,22 @@ module scattdata_header real(8), allocatable :: data(:,:,:) ! (Order/Nmu x Gout x Gin) contains - procedure(init_), deferred :: init ! Initializes ScattData - procedure(calc_f_), deferred :: calc_f ! Calculates f, given mu - procedure(sample_), deferred :: sample ! sample the scatter event + procedure(scattdata_init_), deferred :: init ! Initializes ScattData + procedure(scattdata_calc_f_), deferred :: calc_f ! Calculates f, given mu + procedure(scattdata_sample_), deferred :: sample ! sample the scatter event end type ScattData abstract interface - subroutine init_(this, order, energy, mult, coeffs) + subroutine scattdata_init_(this, order, energy, mult, coeffs) import ScattData class(ScattData), intent(inout) :: this ! Object to work on integer, intent(in) :: order ! Data Order real(8), intent(in) :: energy(:,:) ! Energy Transfer Matrix real(8), intent(in) :: mult(:,:) ! Scatter Prod'n Matrix real(8), intent(in) :: coeffs(:,:,:) ! Coefficients to use - end subroutine init_ + end subroutine scattdata_init_ - pure function calc_f_(this, gin, gout, mu) result(f) + pure function scattdata_calc_f_(this, gin, gout, mu) result(f) import ScattData class(ScattData), intent(in) :: this ! The ScattData to evaluate integer, intent(in) :: gin ! Incoming Energy Group @@ -43,16 +43,16 @@ module scattdata_header real(8), intent(in) :: mu ! Angle of interest real(8) :: f ! Return value of f(mu) - end function calc_f_ + end function scattdata_calc_f_ - subroutine sample_(this, gin, gout, mu, wgt) + subroutine scattdata_sample_(this, gin, gout, mu, wgt) import ScattData class(ScattData), intent(in) :: this ! Scattering Object to Use integer, intent(in) :: gin ! Incoming neutron group integer, intent(out) :: gout ! Sampled outgoin group real(8), intent(out) :: mu ! Sampled change in angle real(8), intent(inout) :: wgt ! Particle weight - end subroutine sample_ + end subroutine scattdata_sample_ end interface type, extends(ScattData) :: ScattDataLegendre @@ -486,4 +486,4 @@ contains end subroutine scattdatatabular_sample -end module scattdata_header \ No newline at end of file +end module scattdata_header diff --git a/src/secondary_header.F90 b/src/secondary_header.F90 index 7449a5793b..d9a18b6b15 100644 --- a/src/secondary_header.F90 +++ b/src/secondary_header.F90 @@ -14,17 +14,17 @@ module secondary_header type, abstract :: AngleEnergy contains - procedure(iSampleAngleEnergy), deferred :: sample + procedure(angleenergy_sample_), deferred :: sample end type AngleEnergy abstract interface - subroutine iSampleAngleEnergy(this, E_in, E_out, mu) + subroutine angleenergy_sample_(this, E_in, E_out, mu) import AngleEnergy class(AngleEnergy), intent(in) :: this real(8), intent(in) :: E_in real(8), intent(out) :: E_out real(8), intent(out) :: mu - end subroutine iSampleAngleEnergy + end subroutine angleenergy_sample_ end interface type :: AngleEnergyContainer @@ -54,6 +54,7 @@ contains real(8), intent(out) :: E_out ! sampled outgoing energy real(8), intent(out) :: mu ! sampled scattering cosine + integer :: i ! loop counter integer :: n ! number of angle-energy distributions real(8) :: prob ! cumulative probability real(8) :: c ! sampled cumulative probability diff --git a/src/surface_header.F90 b/src/surface_header.F90 index 76562f4937..4686552176 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -19,34 +19,34 @@ module surface_header contains procedure :: sense procedure :: reflect - procedure(iEvaluate), deferred :: evaluate - procedure(iDistance), deferred :: distance - procedure(iNormal), deferred :: normal + procedure(surface_evaluate_), deferred :: evaluate + procedure(surface_distance_), deferred :: distance + procedure(surface_normal_), deferred :: normal end type Surface abstract interface - pure function iEvaluate(this, xyz) result(f) + pure function surface_evaluate_(this, xyz) result(f) import Surface class(Surface), intent(in) :: this real(8), intent(in) :: xyz(3) real(8) :: f - end function iEvaluate + end function surface_evaluate_ - pure function iDistance(this, xyz, uvw, coincident) result(d) + pure function surface_distance_(this, xyz, uvw, coincident) result(d) import Surface class(Surface), intent(in) :: this real(8), intent(in) :: xyz(3) real(8), intent(in) :: uvw(3) logical, intent(in) :: coincident real(8) :: d - end function iDistance + end function surface_distance_ - pure function iNormal(this, xyz) result(uvw) + pure function surface_normal_(this, xyz) result(uvw) import Surface class(Surface), intent(in) :: this real(8), intent(in) :: xyz(3) real(8) :: uvw(3) - end function iNormal + end function surface_normal_ end interface !=============================================================================== diff --git a/src/tally.F90 b/src/tally.F90 index f265bdb274..5a54d9846e 100644 --- a/src/tally.F90 +++ b/src/tally.F90 @@ -28,12 +28,12 @@ module tally !$omp threadprivate(position) - procedure(score_general_intfc), pointer :: score_general => null() - procedure(get_scoring_bins_intfc), pointer :: get_scoring_bins => null() + procedure(score_general_), pointer :: score_general => null() + procedure(get_scoring_bins_), pointer :: get_scoring_bins => null() abstract interface - subroutine score_general_intfc(p, t, start_index, filter_index, i_nuclide, & - atom_density, flux) + subroutine score_general_(p, t, start_index, filter_index, i_nuclide, & + atom_density, flux) import Particle import TallyObject type(Particle), intent(in) :: p @@ -43,15 +43,14 @@ module tally integer, intent(in) :: filter_index ! for % results real(8), intent(in) :: flux ! flux estimate real(8), intent(in) :: atom_density ! atom/b-cm - end subroutine score_general_intfc + end subroutine score_general_ - subroutine get_scoring_bins_intfc(p, i_tally, found_bin) + subroutine get_scoring_bins_(p, i_tally, found_bin) import Particle type(Particle), intent(in) :: p integer, intent(in) :: i_tally logical, intent(out) :: found_bin - end subroutine get_scoring_bins_intfc - + end subroutine get_scoring_bins_ end interface contains From d66556a6375add6c855bae66af6f8a170482fe36 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Fri, 26 Feb 2016 19:44:03 -0500 Subject: [PATCH 31/34] Addressed comments by @samuelshaner --- openmc/arithmetic.py | 5 ----- openmc/filter.py | 2 ++ openmc/geometry.py | 10 +++++----- openmc/mgxs/mgxs.py | 30 ++++++++++++++++++------------ openmc/tallies.py | 4 ++-- 5 files changed, 27 insertions(+), 24 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index 521d33e9f0..5271e49a61 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -927,11 +927,6 @@ class AggregateFilter(object): if bin in other.bins: return False - # None of the bins in the other filter should match in this filter - for bin in other.bins: - if bin in self.bins: - return False - # If all conditional checks passed then filters are mergeable return True diff --git a/openmc/filter.py b/openmc/filter.py index 0c45d67d9a..67e15605ba 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -86,6 +86,8 @@ class Filter(object): else: return False else: + # Compare largest/smallest energy bin edges in energy filters + # This logic is used when merging tallies with energy filters if 'energy' in self.type and 'energy' in other.type: return self.bins[0] >= other.bins[-1] else: diff --git a/openmc/geometry.py b/openmc/geometry.py index 807dcf7c66..ab3af872f6 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -253,7 +253,7 @@ class Geometry(object): """ - if case_sensitive: + if not case_sensitive: name = name.lower() all_materials = self.get_all_materials() @@ -293,7 +293,7 @@ class Geometry(object): """ - if case_sensitive: + if not case_sensitive: name = name.lower() all_cells = self.get_all_cells() @@ -333,7 +333,7 @@ class Geometry(object): """ - if case_sensitive: + if not case_sensitive: name = name.lower() all_cells = self.get_all_cells() @@ -373,7 +373,7 @@ class Geometry(object): """ - if case_sensitive: + if not case_sensitive: name = name.lower() all_universes = self.get_all_universes() @@ -413,7 +413,7 @@ class Geometry(object): """ - if case_sensitive: + if not case_sensitive: name = name.lower() all_lattices = self.get_all_lattices() diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 022acef5f4..ce02a4393d 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -241,8 +241,7 @@ class MGXS(object): @property def num_subdomains(self): - tally = list(self.tallies.values())[0] - domain_filter = tally.find_filter(self.domain_type) + domain_filter = self.xs_tally.find_filter(self.domain_type) return domain_filter.num_bins @property @@ -877,14 +876,19 @@ class MGXS(object): # Clone this MGXS to initialize the subdomain-averaged version avg_xs = copy.deepcopy(self) - avg_xs._rxn_rate_tally = None - avg_xs._xs_tally = None - # Average each of the tallies across subdomains - for tally_type, tally in avg_xs.tallies.items(): - tally_avg = tally.average(filter_type=self.domain_type, - filter_bins=subdomains) - avg_xs.tallies[tally_type] = tally_avg + if self.derived: + avg_xs._rxn_rate_tally = avg_xs.rxn_rate_tally.average( + filter_type=self.domain_type, filter_bins=subdomains) + else: + avg_xs._rxn_rate_tally = None + avg_xs._xs_tally = None + + # Average each of the tallies across subdomains + for tally_type, tally in avg_xs.tallies.items(): + tally_avg = tally.average(filter_type=self.domain_type, + filter_bins=subdomains) + avg_xs.tallies[tally_type] = tally_avg avg_xs._domain_type = 'avg({0})'.format(self.domain_type) avg_xs.sparse = self.sparse @@ -1002,8 +1006,10 @@ class MGXS(object): def merge(self, other): """Merge another MGXS with this one - If results have been loaded from a statepoint, then MGXS are only - mergeable along one and only one of energy groups or nuclides. + MGXS are only mergeable if their energy groups and nuclides are either + identical or mutually exclusive. If results have been loaded from a + statepoint, then MGXS are only mergeable along one and only one of + energy groups or nuclides. Parameters ---------- @@ -1510,7 +1516,7 @@ class TotalXS(MGXS): @property def rxn_rate_tally(self): - if self._rxn_rate_tally is None: + if self._rxn_rate_tally is None : self._rxn_rate_tally = self.tallies['total'] self._rxn_rate_tally.sparse = self.sparse return self._rxn_rate_tally diff --git a/openmc/tallies.py b/openmc/tallies.py index 60200a2012..cba7ff9276 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -881,7 +881,7 @@ class Tally(object): # Differentiate Tally with a new auto-generated Tally ID merged_tally.id = None - # If the two tallies are equal, simpy return copy + # If the two tallies are equal, simply return copy if self == other: return merged_tally @@ -936,7 +936,7 @@ class Tally(object): # If results have not been read, then return tally for input generation if self._results_read is None: return merged_tally - #Otherwise, this is a derived tally which needs merged results arrays + # Otherwise, this is a derived tally which needs merged results arrays else: self._derived = True From 3c2a38fa4ec3a38c0527838aa2e628d966076438 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Fri, 26 Feb 2016 20:38:42 -0500 Subject: [PATCH 32/34] Revised reporting of AggregateNuclides and AggregateScores in Pandas DataFrames --- openmc/arithmetic.py | 16 ++++++++++++++++ openmc/tallies.py | 19 ++++++++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index 5271e49a61..e9ba378d52 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -562,6 +562,13 @@ class AggregateScore(object): def aggregate_op(self): return self._aggregate_op + @property + def name(self): + + # Append each score in the aggregate to the string + string = '(' + ', '.join(map(str, self.scores)) + ')' + return string + @scores.setter def scores(self, scores): cv.check_iterable_type('scores', scores, basestring) @@ -649,6 +656,15 @@ class AggregateNuclide(object): def aggregate_op(self): return self._aggregate_op + @property + def name(self): + + # Append each nuclide in the aggregate to the string + names = [nuclide.name if isinstance(nuclide, Nuclide) else str(nuclide) + for nuclide in self.nuclides] + string = '(' + ', '.join(map(str, names)) + ')' + return string + @nuclides.setter def nuclides(self, nuclides): cv.check_iterable_type('nuclides', nuclides, diff --git a/openmc/tallies.py b/openmc/tallies.py index cba7ff9276..fb66eb77f8 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -1571,23 +1571,36 @@ class Tally(object): # Include DataFrame column for nuclides if user requested it if nuclides: nuclides = [] + column_name = 'nuclide' for nuclide in self.nuclides: - # Write Nuclide name if Summary info was linked with StatePoint if isinstance(nuclide, Nuclide): nuclides.append(nuclide.name) + elif isinstance(nuclide, AggregateNuclide): + nuclides.append(nuclide.name) + column_name = '{0}(nuclide)'.format(nuclide.aggregate_op) else: nuclides.append(nuclide) # Tile the nuclide bins into a DataFrame column nuclides = np.repeat(nuclides, len(self.scores)) tile_factor = data_size / len(nuclides) - df['nuclide'] = np.tile(nuclides, int(tile_factor)) + df[column_name] = np.tile(nuclides, int(tile_factor)) # Include column for scores if user requested it if scores: + scores = [] + column_name = 'score' + + for score in self.scores: + if isinstance(score, (basestring, CrossScore)): + scores.append(score) + elif isinstance(score, AggregateScore): + scores.append(score.name) + column_name = '{0}(score)'.format(score.aggregate_op) + tile_factor = data_size / len(self.scores) - df['score'] = np.tile(self.scores, int(tile_factor)) + df[column_name] = np.tile(scores, int(tile_factor)) # Append columns with mean, std. dev. for each tally bin df['mean'] = self.mean.ravel() From 08176672a22c112f15bf75841dbfca377352f361 Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Fri, 26 Feb 2016 21:15:08 -0500 Subject: [PATCH 33/34] Fixed issue in MGXS.can_merge(...) method such that it now compares xs_tally and rxn_rate_tally attributes --- openmc/mgxs/mgxs.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index ce02a4393d..4b2ec5d3fb 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -992,13 +992,10 @@ class MGXS(object): return False elif 'distribcell' not in self.domain_type and self.domain != other.domain: return False - elif len(self.tallies) != len(other.tallies): + elif not self.xs_tally.can_merge(other.xs_tally): + return False + elif not self.rxn_rate_tally.can_merge(other.rxn_rate_tally): return False - - # See if each individual tally is mergeable - for tally_key in self.tallies: - if not self.tallies[tally_key].can_merge(other.tallies[tally_key]): - return False # If all conditionals pass then MGXS are mergeable return True From a4d20444f867d11018f2bae86ab129a97c3644be Mon Sep 17 00:00:00 2001 From: "wbinventor@gmail.com" Date: Wed, 2 Mar 2016 11:35:26 -0500 Subject: [PATCH 34/34] Fixed code per comments by @paulromano --- openmc/arithmetic.py | 4 ++-- openmc/filter.py | 4 ++-- openmc/geometry.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index e9ba378d52..5869cad802 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -566,7 +566,7 @@ class AggregateScore(object): def name(self): # Append each score in the aggregate to the string - string = '(' + ', '.join(map(str, self.scores)) + ')' + string = '(' + ', '.join(self.scores) + ')' return string @scores.setter @@ -742,7 +742,7 @@ class AggregateFilter(object): other.aggregate_filter.type in _FILTER_TYPES: delta = _FILTER_TYPES.index(self.aggregate_filter.type) - \ _FILTER_TYPES.index(other.aggregate_filter.type) - return True if delta > 0 else False + return delta > 0 else: return False else: diff --git a/openmc/filter.py b/openmc/filter.py index 67e15605ba..2ae8eeb626 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -82,7 +82,7 @@ class Filter(object): if self.type in _FILTER_TYPES and other.type in _FILTER_TYPES: delta = _FILTER_TYPES.index(self.type) - \ _FILTER_TYPES.index(other.type) - return True if delta > 0 else False + return delta > 0 else: return False else: @@ -327,7 +327,7 @@ class Filter(object): # Count bins in the merged filter if 'energy' in merged_filter.type: - merged_filter.num_bins = len(merged_bins) -1 + merged_filter.num_bins = len(merged_bins) - 1 else: merged_filter.num_bins = len(merged_bins) diff --git a/openmc/geometry.py b/openmc/geometry.py index ab3af872f6..dac0bd90f1 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -99,7 +99,7 @@ class Geometry(object): all_cells = self._root_universe.get_all_cells() cells = set() - for cell_id, cell in all_cells.items(): + for cell in all_cells.values(): if cell._type == 'normal': cells.add(cell) @@ -120,7 +120,7 @@ class Geometry(object): all_universes = self._root_universe.get_all_universes() universes = set() - for universe_id, universe in all_universes.items(): + for universe in all_universes.values(): universes.add(universe) universes = list(universes)